@runtypelabs/persona 3.18.0 → 3.19.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.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/dist/index.cjs +47 -47
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +281 -4
  5. package/dist/index.d.ts +281 -4
  6. package/dist/index.global.js +102 -1636
  7. package/dist/index.global.js.map +1 -1
  8. package/dist/index.js +47 -47
  9. package/dist/index.js.map +1 -1
  10. package/dist/theme-editor.cjs +1438 -619
  11. package/dist/theme-editor.d.cts +119 -1
  12. package/dist/theme-editor.d.ts +119 -1
  13. package/dist/theme-editor.js +1552 -619
  14. package/dist/widget.css +348 -0
  15. package/package.json +1 -1
  16. package/src/components/composer-builder.test.ts +52 -0
  17. package/src/components/composer-builder.ts +67 -490
  18. package/src/components/composer-parts.test.ts +152 -0
  19. package/src/components/composer-parts.ts +452 -0
  20. package/src/components/header-builder.ts +22 -299
  21. package/src/components/header-parts.ts +360 -0
  22. package/src/components/panel.test.ts +61 -0
  23. package/src/components/panel.ts +262 -5
  24. package/src/components/pill-composer-builder.test.ts +85 -0
  25. package/src/components/pill-composer-builder.ts +183 -0
  26. package/src/index.ts +4 -0
  27. package/src/runtime/init.ts +4 -2
  28. package/src/runtime/persist-state.test.ts +152 -0
  29. package/src/styles/widget.css +348 -0
  30. package/src/types.ts +121 -1
  31. package/src/ui.component-directive.test.ts +183 -0
  32. package/src/ui.composer-bar.test.ts +1009 -0
  33. package/src/ui.ts +809 -72
  34. package/src/utils/attachment-manager.ts +1 -1
  35. package/src/utils/dock.test.ts +45 -0
  36. package/src/utils/dock.ts +3 -0
  37. package/src/utils/icons.ts +314 -58
  38. package/src/utils/stream-animation.ts +7 -2
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var Gu=Object.create;var sa=Object.defineProperty;var Qu=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var Xu=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty;var em=(e,n)=>{for(var t in n)sa(e,t,{get:n[t],enumerable:!0})},Bd=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Yu(n))!Zu.call(e,s)&&s!==t&&sa(e,s,{get:()=>n[s],enumerable:!(r=Qu(n,s))||r.enumerable});return e};var Dd=(e,n,t)=>(t=e!=null?Gu(Xu(e)):{},Bd(n||!e||!e.__esModule?sa(t,"default",{value:e,enumerable:!0}):t,e)),tm=e=>Bd(sa({},"__esModule",{value:!0}),e);var Bf={};em(Bf,{ASK_USER_QUESTION_TOOL_NAME:()=>Ti,AgentWidgetClient:()=>vo,AgentWidgetSession:()=>qo,AttachmentManager:()=>So,DEFAULT_COMPONENTS:()=>ci,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ca,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>On,DEFAULT_PALETTE:()=>ii,DEFAULT_SEMANTIC:()=>li,DEFAULT_WIDGET_CONFIG:()=>Rt,PRESETS:()=>tl,PRESET_FULLSCREEN:()=>el,PRESET_MINIMAL:()=>Zi,PRESET_SHOP:()=>Xi,THEME_ZONES:()=>cp,VERSION:()=>Lo,accessibilityPlugin:()=>_u,animationsPlugin:()=>ju,applyThemeVariables:()=>Jr,attachHeaderToContainer:()=>Eo,brandPlugin:()=>Uu,buildComposer:()=>Jo,buildDefaultHeader:()=>bi,buildHeader:()=>kr,buildHeaderWithLayout:()=>Vo,buildMinimalHeader:()=>xi,collectEnrichedPageContext:()=>Eu,componentRegistry:()=>Pr,createActionManager:()=>Us,createAgentExperience:()=>Ja,createAskUserQuestionBubble:()=>Vp,createBestAvailableVoiceProvider:()=>va,createBubbleWithLayout:()=>Pp,createCSATFeedback:()=>qa,createComboButton:()=>Wa,createComponentMiddleware:()=>iu,createComponentStreamParser:()=>$a,createDefaultSanitizer:()=>oi,createDemoCarousel:()=>$u,createDirectivePostprocessor:()=>_d,createDropdownMenu:()=>Qr,createFlexibleJsonStreamParser:()=>Vd,createIconButton:()=>Ft,createImagePart:()=>Zd,createJsonStreamParser:()=>ua,createLabelButton:()=>Ds,createLocalStorageAdapter:()=>Oa,createMarkdownProcessor:()=>vs,createMarkdownProcessorFromConfig:()=>bo,createMessageActions:()=>Ci,createNPSFeedback:()=>za,createPlainTextParser:()=>da,createPlugin:()=>Vu,createRegexJsonParser:()=>pa,createStandardBubble:()=>Ko,createTextPart:()=>As,createTheme:()=>zo,createThemeObserver:()=>Ta,createToggleGroup:()=>Ns,createTypingIndicator:()=>To,createVoiceProvider:()=>Ao,createWidgetHostLayout:()=>qs,createXmlParser:()=>ma,default:()=>Hf,defaultActionHandlers:()=>ko,defaultJsonActionParser:()=>js,defaultParseRules:()=>Ki,detectColorScheme:()=>ks,directivePostprocessor:()=>jd,ensureAskUserQuestionSheet:()=>Zo,escapeHtml:()=>$o,extractComponentDirectiveFromMessage:()=>Ua,fileToImagePart:()=>ep,formatEnrichedContext:()=>Tu,generateAssistantMessageId:()=>wo,generateCodeSnippet:()=>Ru,generateMessageId:()=>Kd,generateStableSelector:()=>Gi,generateUserMessageId:()=>Uo,getActiveTheme:()=>Ls,getColorScheme:()=>pi,getDisplayText:()=>Qd,getHeaderLayout:()=>vi,getImageParts:()=>Xd,getPreset:()=>Ku,hasComponentDirective:()=>ja,hasImages:()=>Yd,headerLayouts:()=>Ra,highContrastPlugin:()=>zu,initAgentWidget:()=>qi,isAskUserQuestionMessage:()=>Lr,isComponentDirectiveType:()=>au,isDockedMountMode:()=>Yt,isVoiceSupported:()=>Es,listRegisteredStreamAnimations:()=>Ap,markdownPostprocessor:()=>ri,mergeWithDefaults:()=>Aa,normalizeContent:()=>Gd,parseAskUserQuestionPayload:()=>Ir,pluginRegistry:()=>_s,reducedMotionPlugin:()=>qu,registerStreamAnimationPlugin:()=>wp,removeAskUserQuestionSheet:()=>Zr,renderComponentDirective:()=>_a,renderLoadingIndicatorWithFallback:()=>wi,resolveDockConfig:()=>Zn,resolveSanitizer:()=>_o,resolveTokens:()=>Sa,themeToCssVariables:()=>Ea,unregisterStreamAnimationPlugin:()=>Cp,validateImageFile:()=>tp,validateTheme:()=>di});module.exports=tm(Bf);var Fd=require("marked"),nm=e=>{if(e)return e},vs=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Fd.Marked({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=nm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},bo=e=>e?vs({markedOptions:e.options,renderer:e.renderer}):vs(),rm=vs(),ri=e=>rm(e),$o=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Od=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Nd=e=>`%%FORM_PLACEHOLDER_${e}%%`,$d=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Nd(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Nd(n.length);return n.push({token:o,type:s}),o}),t},_d=e=>{let n=bo(e);return t=>{let r=[],s=$d(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Od(i)}"></div>`;o=o.replace(p,u)}),o}},jd=e=>{let n=[],t=$d(e,n),r=ri(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Od(o)}"></div>`;r=r.replace(a,p)}),r};var Ud=Dd(require("dompurify"),1),om={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},sm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,oi=()=>{let e=(0,Ud.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!sm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,om)},_o=e=>e===!1?null:typeof e=="function"?e:oi();var Tr=require("partial-json"),aa=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),jo=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)}},am=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},qd=e=>e.status==="complete"?am(e):e.status==="pending"?"Waiting":"",im=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 zd=e=>e.status==="complete"?im(e):"Using tool...",ia=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},Cs=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return ia(n)},la=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return ia(n)},si=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Cs(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},ca=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&ws(r,t.slice(o,a.index),[]),a[1]!==void 0?ws(r,a[1],["bold"]):a[2]!==void 0?ws(r,a[2],["italic"]):a[3]!==void 0&&ws(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&ws(r,t.slice(o),[]),r},ws=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},lm=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
1
+ "use strict";var Pm=Object.create;var Aa=Object.defineProperty;var Im=Object.getOwnPropertyDescriptor;var Wm=Object.getOwnPropertyNames;var Rm=Object.getPrototypeOf,Hm=Object.prototype.hasOwnProperty;var Bm=(e,n)=>{for(var t in n)Aa(e,t,{get:n[t],enumerable:!0})},vp=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Wm(n))!Hm.call(e,s)&&s!==t&&Aa(e,s,{get:()=>n[s],enumerable:!(r=Im(n,s))||r.enumerable});return e};var Dm=(e,n,t)=>(t=e!=null?Pm(Rm(e)):{},vp(n||!e||!e.__esModule?Aa(t,"default",{value:e,enumerable:!0}):t,e)),Nm=e=>vp(Aa({},"__esModule",{value:!0}),e);var vh={};Bm(vh,{ASK_USER_QUESTION_TOOL_NAME:()=>Zi,AgentWidgetClient:()=>Io,AgentWidgetSession:()=>Zo,AttachmentManager:()=>Bo,DEFAULT_COMPONENTS:()=>Ni,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>$a,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>jn,DEFAULT_PALETTE:()=>Bi,DEFAULT_SEMANTIC:()=>Di,DEFAULT_WIDGET_CONFIG:()=>Bt,PRESETS:()=>Ml,PRESET_FULLSCREEN:()=>kl,PRESET_MINIMAL:()=>Tl,PRESET_SHOP:()=>El,THEME_ZONES:()=>Jp,VERSION:()=>$o,accessibilityPlugin:()=>Cm,animationsPlugin:()=>Am,applyThemeVariables:()=>ro,attachHeaderToContainer:()=>Do,brandPlugin:()=>Sm,buildComposer:()=>os,buildDefaultHeader:()=>zi,buildHeader:()=>Nr,buildHeaderWithLayout:()=>rs,buildMinimalHeader:()=>Vi,collectEnrichedPageContext:()=>am,componentRegistry:()=>$r,createActionManager:()=>ta,createAgentExperience:()=>Ci,createAskUserQuestionBubble:()=>ku,createBestAvailableVoiceProvider:()=>Fa,createBubbleWithLayout:()=>uu,createCSATFeedback:()=>xi,createComboButton:()=>ti,createComponentMiddleware:()=>Uu,createComponentStreamParser:()=>fi,createDefaultSanitizer:()=>Wi,createDemoCarousel:()=>wm,createDirectivePostprocessor:()=>Ep,createDropdownMenu:()=>io,createFlexibleJsonStreamParser:()=>Pp,createIconButton:()=>Ot,createImagePart:()=>Np,createJsonStreamParser:()=>Pa,createLabelButton:()=>Ks,createLocalStorageAdapter:()=>gi,createMarkdownProcessor:()=>Is,createMarkdownProcessorFromConfig:()=>Mo,createMessageActions:()=>Gi,createNPSFeedback:()=>vi,createPlainTextParser:()=>Ma,createPlugin:()=>km,createRegexJsonParser:()=>La,createStandardBubble:()=>ss,createTextPart:()=>Hs,createTheme:()=>ts,createThemeObserver:()=>qa,createToggleGroup:()=>Gs,createTypingIndicator:()=>No,createVoiceProvider:()=>Ho,createWidgetHostLayout:()=>na,createXmlParser:()=>Ia,default:()=>xh,defaultActionHandlers:()=>Oo,defaultJsonActionParser:()=>ea,defaultParseRules:()=>wl,detectColorScheme:()=>Fs,directivePostprocessor:()=>Tp,ensureAskUserQuestionSheet:()=>ds,escapeHtml:()=>Lo,extractComponentDirectiveFromMessage:()=>bi,fileToImagePart:()=>Fp,formatEnrichedContext:()=>im,generateAssistantMessageId:()=>Wo,generateCodeSnippet:()=>gm,generateMessageId:()=>Wp,generateStableSelector:()=>Cl,generateUserMessageId:()=>Yo,getActiveTheme:()=>ns,getColorScheme:()=>Oi,getDisplayText:()=>Hp,getHeaderLayout:()=>Ji,getImageParts:()=>Dp,getPreset:()=>Lm,hasComponentDirective:()=>yi,hasImages:()=>Bp,headerLayouts:()=>ni,highContrastPlugin:()=>Tm,initAgentWidget:()=>yl,isAskUserQuestionMessage:()=>Fr,isComponentDirectiveType:()=>_u,isDockedMountMode:()=>nn,isVoiceSupported:()=>Ds,listRegisteredStreamAnimations:()=>su,markdownPostprocessor:()=>Ii,mergeWithDefaults:()=>_a,normalizeContent:()=>Rp,parseAskUserQuestionPayload:()=>Or,pluginRegistry:()=>Zs,reducedMotionPlugin:()=>Em,registerStreamAnimationPlugin:()=>ru,removeAskUserQuestionSheet:()=>po,renderComponentDirective:()=>hi,renderLoadingIndicatorWithFallback:()=>Ki,renderLucideIcon:()=>ge,resolveDockConfig:()=>Xn,resolveSanitizer:()=>Qo,resolveTokens:()=>Ua,themeToCssVariables:()=>ja,unregisterStreamAnimationPlugin:()=>ou,validateImageFile:()=>Op,validateTheme:()=>Fi});module.exports=Nm(vh);var Cp=require("marked"),Fm=e=>{if(e)return e},Is=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Cp.Marked({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=Fm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Mo=e=>e?Is({markedOptions:e.options,renderer:e.renderer}):Is(),Om=Is(),Ii=e=>Om(e),Lo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ap=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),wp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Sp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=wp(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=wp(n.length);return n.push({token:o,type:s}),o}),t},Ep=e=>{let n=Mo(e);return t=>{let r=[],s=Sp(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Ap(i)}"></div>`;o=o.replace(d,u)}),o}},Tp=e=>{let n=[],t=Sp(e,n),r=Ii(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Ap(o)}"></div>`;r=r.replace(a,d)}),r};var kp=Dm(require("dompurify"),1),$m={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"]},_m=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wi=()=>{let e=(0,kp.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!_m.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,$m)},Qo=e=>e===!1?null:typeof e=="function"?e:Wi();var Br=require("partial-json"),Sa=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Xo=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)}},Um=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Mp=e=>e.status==="complete"?Um(e):e.status==="pending"?"Waiting":"",jm=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 Lp=e=>e.status==="complete"?jm(e):"Using tool...",Ea=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},Rs=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ea(n)},Ta=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ea(n)},Ri=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Rs(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},ka=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Ws(r,t.slice(o,a.index),[]),a[1]!==void 0?Ws(r,a[1],["bold"]):a[2]!==void 0?Ws(r,a[2],["italic"]):a[3]!==void 0&&Ws(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Ws(r,t.slice(o),[]),r},Ws=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},qm=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},xo=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},da=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pa=()=>{var n;let e=lm();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},ua=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,Tr.parse)(t,Tr.STR|Tr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?aa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=aa(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Vd=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?aa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?aa(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=(0,Tr.parse)(o,Tr.STR|Tr.OBJ),p=s(i);p!==null&&(n=p)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},ma=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var ga=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var cm="https://api.runtype.com/v1/dispatch",fa="https://api.runtype.com",ai=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 dm(e){switch(e){case"json":return ua;case"regex-json":return pa;case"xml":return ma;default:return da}}var Jd=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function pm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=Jd(t);if(!Jd(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=xo(e);return xo(n)!==null&&a===null?n:e}var vo=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:cm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:dm(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let p=await this.initSession();if(new Date>=new Date(p.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(n.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:p.sessionId,messages:n.messages.filter(ai).map(g=>{var v,E,w;return{id:g.id,role:g.role,content:(w=(E=(v=g.contentParts)!=null?v:g.llmContent)!=null?E:g.rawContent)!=null?w:g.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...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:r.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 E=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:E}),E}if(f.status===429){let E=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:E}),E}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,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(p){let c=p instanceof Error?p:new Error(String(p));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var i,p;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||fa}/resume`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,body:JSON.stringify({executionId:n,toolOutputs:t,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(ai).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}}),r={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:n,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&&(r.context=s)}return r}async buildPayload(n){let r={messages:n.slice().filter(ai).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:n,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&&(r.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...r},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let p=u=>{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(),...u!==void 0&&{partId:u}};return r.current=d,s(d),d},c=u=>r.current?r.current:p(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var he,Ye,Ot,$t;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),p=0,c=()=>i+p++,u=D=>{let se=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,Re=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,Ue=D.tools?D.tools.map(Qe=>({...Qe,chunks:Qe.chunks?[...Qe.chunks]:void 0})):void 0;return{...D,reasoning:se,toolCall:Re,tools:Ue}},d=D=>{t({type:"message",message:u(D)})},f=null,g={current:null},v={current:null},E=!1,w=new Map,A=new Map,I=new Map,U=new Map,k={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},M=(D,se,Re="")=>`${D}::${se}::${Re}`,P=(D,se)=>`${D}::${se}::`,N=(D,se,Re,Ue)=>{let Qe=M(D,se,Re),Ze=I.get(Qe);if(Ze)return Ze;let H=Re?`-${Re}`:"",Te={id:`nested-${D}-${se}${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Re?{partId:Re}:{},agentMetadata:{executionId:Ue,parentToolId:D,parentStepId:se}};return I.set(Qe,Te),d(Te),Te},K=D=>{if(D==null)return null;try{return String(D)}catch{return null}},G=D=>{var se,Re,Ue,Qe,Ze;return K((Ze=(Qe=(Ue=(Re=(se=D.stepId)!=null?se:D.step_id)!=null?Re:D.step)!=null?Ue:D.parentId)!=null?Qe:D.flowStepId)!=null?Ze:D.flow_step_id)},j=D=>{var se,Re,Ue,Qe,Ze,H,Te;return K((Te=(H=(Ze=(Qe=(Ue=(Re=(se=D.callId)!=null?se:D.call_id)!=null?Re:D.requestId)!=null?Ue:D.request_id)!=null?Qe:D.toolCallId)!=null?Ze:D.tool_call_id)!=null?H:D.stepId)!=null?Te:D.step_id)},ie=r,ve=!1,ue=()=>{if(f)return f;let D;return!ve&&ie?(D=ie,ve=!0):ie&&v.current?D=`${ie}_${v.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},Oe=(D,se)=>{k.lastId=se,D&&k.byStep.set(D,se)},fe=(D,se)=>{var Ze;let Re=(Ze=D.reasoningId)!=null?Ze:D.id,Ue=G(D);if(Re){let H=String(Re);return Oe(Ue,H),H}if(Ue){let H=k.byStep.get(Ue);if(H)return k.lastId=H,H}if(k.lastId&&!se)return k.lastId;if(!se)return null;let Qe=`reason-${c()}`;return Oe(Ue,Qe),Qe},De=D=>{let se=w.get(D);if(se)return se;let Re={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:D,status:"streaming",chunks:[]}};return w.set(D,Re),d(Re),Re},Le=(D,se)=>{L.lastId=se,D&&L.byCall.set(D,se)},Ne=new Set,de=new Map,X=new Set,ge=new Map,Q=D=>{if(!D)return!1;let se=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return se==="emit_artifact_markdown"||se==="emit_artifact_component"},me=(D,se)=>{var Ze;let Re=(Ze=D.toolId)!=null?Ze:D.id,Ue=j(D);if(Re){let H=String(Re);return Le(Ue,H),H}if(Ue){let H=L.byCall.get(Ue);if(H)return L.lastId=H,H}if(L.lastId&&!se)return L.lastId;if(!se)return null;let Qe=`tool-${c()}`;return Le(Ue,Qe),Qe},pe=D=>{let se=A.get(D);if(se)return se;let Re={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:D,status:"pending"}};return A.set(D,Re),d(Re),Re},oe=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let se=Number(D);if(!Number.isNaN(se)&&Number.isFinite(se))return se;let Re=Date.parse(D);if(!Number.isNaN(Re))return Re}return Date.now()},Ie=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Pe=new Map,R=new Map,z=new Map,ne=new Map,_=null,q=(D,se,Re)=>{var Te;let Ue=z.get(D);Ue||(Ue=[],z.set(D,Ue));let Qe=0,Ze=Ue.length;for(;Qe<Ze;){let Fe=Qe+Ze>>>1;Ue[Fe].seq<se?Qe=Fe+1:Ze=Fe}((Te=Ue[Qe])==null?void 0:Te.seq)===se?Ue[Qe]={seq:se,text:Re}:Ue.splice(Qe,0,{seq:se,text:Re});let H="";for(let Fe=0;Fe<Ue.length;Fe++)H+=Ue[Fe].text;return H},le=(D,se)=>{let Re=Ie(se),Ue=R.get(D.id),Qe=pm(Ue,Re);D.rawContent=Qe;let Ze=Pe.get(D.id),H=re=>{var dt;let qe=(dt=D.content)!=null?dt:"";re.trim()!==""&&(qe.trim().length===0||re.startsWith(qe)||re.trimStart().startsWith(qe.trim()))&&(D.content=re)},Te=()=>{var re;if(Ze){let qe=(re=Ze.close)==null?void 0:re.call(Ze);qe instanceof Promise&&qe.catch(()=>{})}Pe.delete(D.id),R.delete(D.id),D.streaming=!1,d(D)};if(!Ze){H(Re),Te();return}let Fe=xo(Qe);if(Fe!==null&&Fe.trim()!==""){H(Fe),Te();return}let ct=re=>{var Nt;let qe=typeof re=="string"?re:(Nt=re==null?void 0:re.text)!=null?Nt:null;if(qe!==null&&qe.trim()!=="")return qe;let dt=Ze.getExtractedText();return dt!==null&&dt.trim()!==""?dt:Re},Z;try{Z=Ze.processChunk(Qe)}catch{H(Re),Te();return}if(Z instanceof Promise){Z.then(re=>{H(ct(re)),Te()}).catch(()=>{H(Re),Te()});return}H(ct(Z)),Te()},Ee=[],ee=!1,ae,Lt=()=>{ee||(ee=!0,queueMicrotask(()=>{ee=!1,ae()}))},xt=new ga((D,se)=>{Ee.push({payloadType:D,payload:se}),Lt()}),Ke=null,sn=new Map,nt=(he=this.config.iterationDisplay)!=null?he:"separate";for(ae=()=>{var D,se,Re,Ue,Qe,Ze,H,Te,Fe,ct,Z,re,qe,dt,Nt,an,ht,ft,it,Me,st,ze,ln,cn,$n,dn,rt,Rr,kn,no,_n,Io,Hr,hr,yt,Ln,In,hn,It,jn,Un,Pn,Br,yr,Dr,Wn,Pt,yn,qn,Nr,br,Fr,lr,Rn,cr,At,zt,Vt,Hn,Or,zn,nr,Bn,F,rr,Vn,Jn,$r,ce,bn,Dn,xr,ro,zs,rs,Vs,Po,pt,os,Kn,Cn,Js,Ks,Wo,vr,Gs,oo,ss,wr,as,_r,jr,Qs,Ys,ti,so,ao,_t,Ro,Ho,is,dr,Xs,ls,cs,ds,xn,Nn,Cr,ot,ps,io,or,Zs,Bo,Do,lo,Ur,ea,ta,sr,co,na,ra,Ar,jt,Ut,qr,us,ms,gs,fs,hs,ni,ys,zr,No,Sr;for(let po=0;po<Ee.length;po++){let Ve=Ee[po].payloadType,x=Ee[po].payload;if(Ve==="reason_start"){let O=(D=fe(x,!0))!=null?D:`reason-${c()}`,C=De(O);C.reasoning=(se=C.reasoning)!=null?se:{id:O,status:"streaming",chunks:[]},C.reasoning.startedAt=(Ue=C.reasoning.startedAt)!=null?Ue:oe((Re=x.startedAt)!=null?Re:x.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let O=(Ze=(Qe=fe(x,!1))!=null?Qe:fe(x,!0))!=null?Ze:`reason-${c()}`,C=De(O);C.reasoning=(H=C.reasoning)!=null?H:{id:O,status:"streaming",chunks:[]},C.reasoning.startedAt=(Fe=C.reasoning.startedAt)!=null?Fe:oe((Te=x.startedAt)!=null?Te:x.timestamp);let J=(re=(Z=(ct=x.reasoningText)!=null?ct:x.text)!=null?Z:x.delta)!=null?re:"";if(J&&x.hidden!==!0){let He=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(He!==void 0){let te=q(O,He,String(J));C.reasoning.chunks=[te]}else C.reasoning.chunks.push(String(J))}if(C.reasoning.status=x.done?"complete":"streaming",x.done){C.reasoning.completedAt=oe((qe=x.completedAt)!=null?qe:x.timestamp);let He=(dt=C.reasoning.startedAt)!=null?dt:Date.now();C.reasoning.durationMs=Math.max(0,((Nt=C.reasoning.completedAt)!=null?Nt:Date.now())-He)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(Ve==="reason_complete"){let O=(ht=(an=fe(x,!1))!=null?an:fe(x,!0))!=null?ht:`reason-${c()}`,C=w.get(O);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=oe((ft=x.completedAt)!=null?ft:x.timestamp);let He=(it=C.reasoning.startedAt)!=null?it:Date.now();C.reasoning.durationMs=Math.max(0,((Me=C.reasoning.completedAt)!=null?Me:Date.now())-He),C.streaming=!1,d(C)}let J=G(x);J&&k.byStep.delete(J)}else if(Ve==="tool_start"){let O=(st=me(x,!0))!=null?st:`tool-${c()}`,C=(ze=x.toolName)!=null?ze:x.name;if(Q(C)){Ne.add(O);continue}let J=pe(O),He=(ln=J.toolCall)!=null?ln:{id:O,status:"pending"};He.name=C!=null?C:He.name,He.status="running",x.args!==void 0?He.args=x.args:x.parameters!==void 0&&(He.args=x.parameters),He.startedAt=($n=He.startedAt)!=null?$n:oe((cn=x.startedAt)!=null?cn:x.timestamp),He.completedAt=void 0,He.durationMs=void 0,J.toolCall=He,J.streaming=!0;let te=x.agentContext;(te||x.executionId)&&(J.agentMetadata={executionId:(dn=te==null?void 0:te.executionId)!=null?dn:x.executionId,iteration:(rt=te==null?void 0:te.iteration)!=null?rt:x.iteration}),d(J)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let O=(kn=(Rr=me(x,!1))!=null?Rr:me(x,!0))!=null?kn:`tool-${c()}`;if(Ne.has(O))continue;let C=pe(O),J=(no=C.toolCall)!=null?no:{id:O,status:"running"};J.startedAt=(Io=J.startedAt)!=null?Io:oe((_n=x.startedAt)!=null?_n:x.timestamp);let He=(yt=(hr=(Hr=x.text)!=null?Hr:x.delta)!=null?hr:x.message)!=null?yt:"";He&&(J.chunks=(Ln=J.chunks)!=null?Ln:[],J.chunks.push(String(He))),J.status="running",C.toolCall=J,C.streaming=!0;let te=x.agentContext;(te||x.executionId)&&(C.agentMetadata=(It=C.agentMetadata)!=null?It:{executionId:(In=te==null?void 0:te.executionId)!=null?In:x.executionId,iteration:(hn=te==null?void 0:te.iteration)!=null?hn:x.iteration}),d(C)}else if(Ve==="tool_complete"){let O=(Un=(jn=me(x,!1))!=null?jn:me(x,!0))!=null?Un:`tool-${c()}`;if(Ne.has(O)){Ne.delete(O);continue}let C=pe(O),J=(Pn=C.toolCall)!=null?Pn:{id:O,status:"running"};J.status="complete",x.result!==void 0&&(J.result=x.result),typeof x.duration=="number"&&(J.duration=x.duration),J.completedAt=oe((Br=x.completedAt)!=null?Br:x.timestamp);let He=(yr=x.duration)!=null?yr:x.executionTime;if(typeof He=="number")J.durationMs=He;else{let et=(Dr=J.startedAt)!=null?Dr:Date.now();J.durationMs=Math.max(0,((Wn=J.completedAt)!=null?Wn:Date.now())-et)}C.toolCall=J,C.streaming=!1;let te=x.agentContext;(te||x.executionId)&&(C.agentMetadata=(qn=C.agentMetadata)!=null?qn:{executionId:(Pt=te==null?void 0:te.executionId)!=null?Pt:x.executionId,iteration:(yn=te==null?void 0:te.iteration)!=null?yn:x.iteration}),d(C);let We=j(x);We&&L.byCall.delete(We)}else if(Ve==="step_await"&&x.awaitReason==="local_tool_required"&&x.toolName){let O=(Nr=x.toolId)!=null?Nr:`local-${c()}`,C=pe(O),J=(br=C.toolCall)!=null?br:{id:O,status:"pending"};J.name=x.toolName,J.args=x.parameters,J.status="complete",J.chunks=(Fr=J.chunks)!=null?Fr:[],J.startedAt=(Rn=J.startedAt)!=null?Rn:oe((lr=x.startedAt)!=null?lr:x.timestamp),J.completedAt=(cr=J.completedAt)!=null?cr:J.startedAt,C.toolCall=J,C.streaming=!1,C.agentMetadata={...C.agentMetadata,executionId:(zt=x.executionId)!=null?zt:(At=C.agentMetadata)==null?void 0:At.executionId,awaitingLocalTool:!0},d(C)}else if(Ve==="text_start"){if((Vt=x.toolContext)!=null&&Vt.toolId)continue;let O=x.partId;if(O!==void 0&&v.current!==null&&O!==v.current){let C=f;C&&(C.streaming=!1,d(C),_=C,f=null,E=!0)}O!==void 0&&(v.current=O)}else if(Ve==="text_end"){if((Hn=x.toolContext)!=null&&Hn.toolId)continue;let O=f;O&&(O.streaming=!1,d(O),_=O,f=null,E=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let O=x.stepType,C=x.executionType;if(O==="tool"||C==="context")continue;let J=x.toolContext;if(J!=null&&J.toolId){let et=String((zn=(Or=x.id)!=null?Or:J.stepId)!=null?zn:`step-${c()}`),lt=x.partId!==void 0&&x.partId!==null?String(x.partId):"",bt=`${J.toolId}::${et}`,Mt=U.get(bt);if(lt!==""&&Mt!==void 0&&Mt!==""&&Mt!==lt){let Ct=I.get(M(J.toolId,et,Mt));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,d(Ct))}lt!==""&&U.set(bt,lt);let Ht=N(J.toolId,et,lt,J.executionId),Xt=(rr=(F=(Bn=(nr=x.text)!=null?nr:x.delta)!=null?Bn:x.content)!=null?F:x.chunk)!=null?rr:"";Xt&&(Ht.content+=String(Xt),Ht.streaming=!0,d(Ht)),x.isComplete&&(Ht.streaming=!1,d(Ht));continue}let He=x.partId;if(He!==void 0&&v.current!==null&&He!==v.current){let et=f;et&&(et.streaming=!1,d(et),_=et,f=null,E=!0)}He!==void 0&&(v.current=He);let te=He!==void 0&&(Vn=ne.get(He))!=null?Vn:ue();He!==void 0&&(te.partId||(te.partId=He),ne.set(He,te));let We=(bn=(ce=($r=(Jn=x.text)!=null?Jn:x.delta)!=null?$r:x.content)!=null?ce:x.chunk)!=null?bn:"";if(We){let et=typeof x.seq=="number"?x.seq:void 0,lt=He!=null?He:te.id,bt=et!==void 0?q(lt,et,String(We)):((Dn=R.get(te.id))!=null?Dn:"")+We;te.rawContent=bt,Pe.has(te.id)||Pe.set(te.id,this.createStreamParser());let Mt=Pe.get(te.id),Ht=bt.trim().startsWith("{")||bt.trim().startsWith("[");if(Ht&&R.set(te.id,bt),Mt.__isPlainTextParser===!0){te.content=et!==void 0?bt:te.content+We,R.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,d(te);continue}let Ct=Mt.processChunk(bt);if(Ct instanceof Promise)Ct.then(kt=>{var un;let Zt=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(Zt!==null&&Zt.trim()!=="")te.content=Zt,d(te);else if(!Ht&&!bt.trim().startsWith("<")){let pn=f,Jt=pn&&pn.id===te.id?pn:te;Jt.id===te.id&&(Jt.content=et!==void 0?bt:Jt.content+We,R.delete(Jt.id),Pe.delete(Jt.id),Jt.rawContent=void 0,d(Jt))}}).catch(()=>{te.content=et!==void 0?bt:te.content+We,R.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,d(te)});else{let kt=typeof Ct=="string"?Ct:(xr=Ct==null?void 0:Ct.text)!=null?xr:null;kt!==null&&kt.trim()!==""?(te.content=kt,d(te)):!Ht&&!bt.trim().startsWith("<")&&(te.content=et!==void 0?bt:te.content+We,R.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,d(te))}}if(x.isComplete){let et=(zs=(ro=x.result)==null?void 0:ro.response)!=null?zs:te.content;if(et){let lt=R.get(te.id),bt=lt!=null?lt:Ie(et);te.rawContent=bt;let Mt=Pe.get(te.id),Ht=null,Xt=!1;if(Mt&&(Ht=Mt.getExtractedText(),Ht===null&&(Ht=xo(bt)),Ht===null)){let Ct=Mt.processChunk(bt);Ct instanceof Promise?(Xt=!0,Ct.then(kt=>{var un;let Zt=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(Zt!==null){let pn=f;pn&&pn.id===te.id&&(pn.content=Zt,pn.streaming=!1,Pe.delete(pn.id),R.delete(pn.id),d(pn))}})):Ht=typeof Ct=="string"?Ct:(rs=Ct==null?void 0:Ct.text)!=null?rs:null}if(!Xt){Ht!==null&&Ht.trim()!==""?te.content=Ht:R.has(te.id)||(te.content=Ie(et));let Ct=Pe.get(te.id);if(Ct){let kt=(Vs=Ct.close)==null?void 0:Vs.call(Ct);kt instanceof Promise&&kt.catch(()=>{}),Pe.delete(te.id)}R.delete(te.id),te.streaming=!1,d(te)}}}}else if(Ve==="step_complete"){let O=x.stepType,C=x.executionType;if(O==="tool"||C==="context")continue;let J=x.toolContext;if(J!=null&&J.toolId){let et=String((pt=(Po=x.id)!=null?Po:J.stepId)!=null?pt:"");if(et){let lt=P(J.toolId,et);for(let[bt,Mt]of I)bt.startsWith(lt)&&Mt.streaming!==!1&&(Mt.streaming=!1,d(Mt));U.delete(`${J.toolId}::${et}`)}continue}let He=x.stopReason;if(E){if(f!==null){let bt=f;He&&(bt.stopReason=He),Pe.delete(bt.id),R.delete(bt.id),bt.streaming!==!1&&(bt.streaming=!1,d(bt))}let et=(os=x.result)==null?void 0:os.response,lt=_;lt&&(He&&(lt.stopReason=He),et!=null?le(lt,et):(Pe.delete(lt.id),R.delete(lt.id))),_=null;continue}let te=(Kn=x.result)==null?void 0:Kn.response,We=ue();if(He&&(We.stopReason=He),te!=null){let et=Pe.get(We.id),lt=!1,bt=!1;if(et){let Mt=et.getExtractedText(),Ht=R.get(We.id),Xt=Ht!=null?Ht:Ie(te);if(We.rawContent=Xt,Mt!==null&&Mt.trim()!=="")We.content=Mt,lt=!0;else{let Ct=xo(Xt);if(Ct!==null)We.content=Ct,lt=!0;else{let kt=et.processChunk(Xt);if(kt instanceof Promise)bt=!0,kt.then(Zt=>{var pn;let un=typeof Zt=="string"?Zt:(pn=Zt==null?void 0:Zt.text)!=null?pn:null;if(un!==null&&un.trim()!==""){let Jt=f;Jt&&Jt.id===We.id&&(Jt.content=un,Jt.streaming=!1,Pe.delete(Jt.id),R.delete(Jt.id),d(Jt))}else{let Jt=et.getExtractedText(),Gn=f;Gn&&Gn.id===We.id&&(Jt!==null&&Jt.trim()!==""?Gn.content=Jt:R.has(Gn.id)||(Gn.content=Ie(te)),Gn.streaming=!1,Pe.delete(Gn.id),R.delete(Gn.id),d(Gn))}});else{let Zt=typeof kt=="string"?kt:(Cn=kt==null?void 0:kt.text)!=null?Cn:null;if(Zt!==null&&Zt.trim()!=="")We.content=Zt,lt=!0;else{let un=et.getExtractedText();un!==null&&un.trim()!==""&&(We.content=un,lt=!0)}}}}}if(!bt){if(!We.rawContent){let Mt=R.get(We.id);We.rawContent=Mt!=null?Mt:Ie(te)}if(!lt&&!R.has(We.id)&&(We.content=Ie(te)),et){let Mt=(Js=et.close)==null?void 0:Js.call(et);Mt instanceof Promise&&Mt.catch(()=>{})}Pe.delete(We.id),R.delete(We.id),We.streaming=!1,d(We)}}else Pe.delete(We.id),R.delete(We.id),We.streaming=!1,d(We)}else if(Ve==="flow_complete"){let O=(Ks=x.result)==null?void 0:Ks.response;if(E){if(f!==null){let C=f;Pe.delete(C.id),R.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}}else if(O!=null){let C=ue(),J=R.get(C.id),He=J!=null?J:Ie(O);C.rawContent=He;let te=Ie(O),We=Pe.get(C.id);if(We){let bt=xo(He);if(bt!==null)te=bt;else{let Mt=We.processChunk(He);Mt instanceof Promise&&Mt.then(Xt=>{var kt;let Ct=typeof Xt=="string"?Xt:(kt=Xt==null?void 0:Xt.text)!=null?kt:null;Ct!==null&&(C.content=Ct,C.streaming=!1,d(C))});let Ht=We.getExtractedText();Ht!==null&&(te=Ht)}}Pe.delete(C.id),R.delete(C.id);let et=te!==C.content,lt=C.streaming!==!1;et&&(C.content=te),C.streaming=!1,(et||lt)&&d(C)}else if(f!==null){let C=f;Pe.delete(C.id),R.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}t({type:"status",status:"idle"})}else if(Ve==="agent_start")Ke={executionId:x.executionId,agentId:(Wo=x.agentId)!=null?Wo:"virtual",agentName:(vr=x.agentName)!=null?vr:"",status:"running",currentIteration:0,maxTurns:(Gs=x.maxTurns)!=null?Gs:1,startedAt:oe(x.startedAt)};else if(Ve==="agent_iteration_start"){if(Ke&&(Ke.currentIteration=x.iteration),nt==="separate"&&x.iteration>1){let O=f;O&&(O.streaming=!1,d(O),sn.set(x.iteration-1,O),f=null)}}else if(Ve!=="agent_turn_start"){if(Ve==="agent_turn_delta"){if(x.contentType==="text"){let O=ue();O.content+=(oo=x.delta)!=null?oo:"",O.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId,agentName:Ke==null?void 0:Ke.agentName},d(O)}else if(x.contentType==="thinking"){let O=(ss=x.turnId)!=null?ss:`agent-think-${x.iteration}`,C=De(O);C.reasoning=(wr=C.reasoning)!=null?wr:{id:O,status:"streaming",chunks:[]},C.reasoning.chunks.push((as=x.delta)!=null?as:""),C.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId},d(C)}else if(x.contentType==="tool_input"){let O=(_r=x.toolCallId)!=null?_r:L.lastId;if(O){let C=A.get(O);C!=null&&C.toolCall&&(C.toolCall.chunks=(jr=C.toolCall.chunks)!=null?jr:[],C.toolCall.chunks.push((Qs=x.delta)!=null?Qs:""),d(C))}}}else if(Ve==="agent_turn_complete"){let O=x.turnId;if(O){let J=w.get(O);if(J!=null&&J.reasoning){J.reasoning.status="complete",J.reasoning.completedAt=oe(x.completedAt);let He=(Ys=J.reasoning.startedAt)!=null?Ys:Date.now();J.reasoning.durationMs=Math.max(0,((ti=J.reasoning.completedAt)!=null?ti:Date.now())-He),J.streaming=!1,d(J)}}let C=x.stopReason;if(C&&f!==null){let J=x.turnId;(!J||((so=f.agentMetadata)==null?void 0:so.turnId)===J)&&(f.stopReason=C,d(f))}}else if(Ve==="agent_tool_start"){let O=(ao=x.toolCallId)!=null?ao:`agent-tool-${c()}`;Le(j(x),O);let C=pe(O),J=(_t=C.toolCall)!=null?_t:{id:O,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(Ho=(Ro=x.toolName)!=null?Ro:x.name)!=null?Ho:J.name,J.status="running",x.parameters!==void 0&&(J.args=x.parameters),J.startedAt=oe((is=x.startedAt)!=null?is:x.timestamp),C.toolCall=J,C.streaming=!0,C.agentMetadata={executionId:x.executionId,iteration:x.iteration},d(C)}else if(Ve==="agent_tool_delta"){let O=(dr=x.toolCallId)!=null?dr:L.lastId;if(O){let C=(Xs=A.get(O))!=null?Xs:pe(O);C.toolCall&&(C.toolCall.chunks=(ls=C.toolCall.chunks)!=null?ls:[],C.toolCall.chunks.push((cs=x.delta)!=null?cs:""),C.toolCall.status="running",C.streaming=!0,d(C))}}else if(Ve==="agent_tool_complete"){let O=(ds=x.toolCallId)!=null?ds:L.lastId;if(O){let C=(xn=A.get(O))!=null?xn:pe(O);if(C.toolCall){C.toolCall.status="complete",x.result!==void 0&&(C.toolCall.result=x.result),typeof x.executionTime=="number"&&(C.toolCall.durationMs=x.executionTime),C.toolCall.completedAt=oe((Nn=x.completedAt)!=null?Nn:x.timestamp),C.streaming=!1,d(C);let J=j(x);J&&L.byCall.delete(J)}}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let O=`agent-reflection-${x.executionId}-${x.iteration}`,C={id:O,role:"assistant",content:(Cr=x.reflection)!=null?Cr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:O,status:"complete",chunks:[(ot=x.reflection)!=null?ot:""]},agentMetadata:{executionId:x.executionId,iteration:x.iteration}};d(C)}else if(Ve==="agent_complete"){Ke&&(Ke.status=x.success?"complete":"error",Ke.completedAt=oe(x.completedAt),Ke.stopReason=x.stopReason);let O=f;O&&(O.streaming=!1,d(O)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let O=typeof x.error=="string"?x.error:(io=(ps=x.error)==null?void 0:ps.message)!=null?io:"Agent execution error";x.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",O):t({type:"error",error:new Error(O)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let O=(or=x.approvalId)!=null?or:`approval-${c()}`,C={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:O,status:"pending",agentId:(Zs=Ke==null?void 0:Ke.agentId)!=null?Zs:"virtual",executionId:(Do=(Bo=x.executionId)!=null?Bo:Ke==null?void 0:Ke.executionId)!=null?Do:"",toolName:(lo=x.toolName)!=null?lo:"",toolType:x.toolType,description:(ea=x.description)!=null?ea:`Execute ${(Ur=x.toolName)!=null?Ur:"tool"}`,parameters:x.parameters}};d(C)}else if(Ve==="step_await"&&x.awaitReason==="approval_required"){let O=(ta=x.approvalId)!=null?ta:`approval-${c()}`,C={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:O,status:"pending",agentId:(sr=Ke==null?void 0:Ke.agentId)!=null?sr:"virtual",executionId:(na=(co=x.executionId)!=null?co:Ke==null?void 0:Ke.executionId)!=null?na:"",toolName:(ra=x.toolName)!=null?ra:"",toolType:x.toolType,description:(jt=x.description)!=null?jt:`Execute ${(Ar=x.toolName)!=null?Ar:"tool"}`,parameters:x.parameters}};d(C)}else if(Ve==="agent_approval_complete"){let O=x.approvalId;if(O){let J={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:O,status:(Ut=x.decision)!=null?Ut:"approved",agentId:(qr=Ke==null?void 0:Ke.agentId)!=null?qr:"virtual",executionId:(ms=(us=x.executionId)!=null?us:Ke==null?void 0:Ke.executionId)!=null?ms:"",toolName:(gs=x.toolName)!=null?gs:"",description:(fs=x.description)!=null?fs:"",resolvedAt:Date.now()}};d(J)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let O=x.artifactType,C=String(x.id),J=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:C,artifactType:O,title:J,component:typeof x.component=="string"?x.component:void 0}),ge.set(C,{markdown:"",title:J}),!X.has(C)){X.add(C);let He={id:`artifact-ref-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:C,title:J,artifactType:O,status:"streaming"}})};de.set(C,He),d(He)}}else if(Ve==="artifact_delta"){let O=String(x.id),C=typeof x.delta=="string"?x.delta:String((hs=x.delta)!=null?hs:"");t({type:"artifact_delta",id:O,artDelta:C});let J=ge.get(O);J&&(J.markdown+=C)}else if(Ve==="artifact_update"){let O=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:O,component:typeof x.component=="string"?x.component:void 0})}else if(Ve==="artifact_complete"){let O=String(x.id);t({type:"artifact_complete",id:O});let C=de.get(O);if(C){C.streaming=!1;try{let J=JSON.parse((ni=C.rawContent)!=null?ni:"{}");if(J.props){J.props.status="complete";let He=ge.get(O);He!=null&&He.markdown&&(J.props.markdown=He.markdown)}C.rawContent=JSON.stringify(J)}catch{}ge.delete(O),d(C),de.delete(O)}}}else if(Ve==="transcript_insert"){let O=x.message;if(!O||typeof O!="object")continue;let C=String((ys=O.id)!=null?ys:`msg-${c()}`),J=O.role,te={id:C,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof O.content=="string"?O.content:"",rawContent:typeof O.rawContent=="string"?O.rawContent:void 0,createdAt:typeof O.createdAt=="string"?O.createdAt:new Date().toISOString(),streaming:O.streaming===!0,...typeof O.variant=="string"?{variant:O.variant}:{},sequence:c()};if(d(te),te.rawContent)try{let We=JSON.parse(te.rawContent),et=(zr=We==null?void 0:We.props)==null?void 0:zr.artifactId;typeof et=="string"&&X.add(et)}catch{}f=null,g.current=null,Pe.delete(C),R.delete(C)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let O=null;if(x.error instanceof Error)O=x.error;else if(Ve==="dispatch_error"){let C=(No=x.message)!=null?No:x.error;C!=null&&C!==""&&(O=new Error(String(C)))}else if(Ve==="step_error"||Ve==="flow_error"){let C=x.error;typeof C=="string"&&C!==""?O=new Error(C):C!=null&&typeof C=="object"&&"message"in C&&(O=new Error(String((Sr=C.message)!=null?Sr:C)))}else Ve==="error"&&x.error!=null&&x.error!==""&&(O=new Error(String(x.error)));if(O){t({type:"error",error:O});let C=f;C&&C.streaming&&(C.streaming=!1,d(C)),t({type:"status",status:"idle"})}}}}}}Ee.length=0};;){let{done:D,value:se}=await s.read();if(D)break;a+=o.decode(se,{stream:!0});let Re=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 r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Po=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ma=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},La=()=>{var n;let e=qm();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Pa=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,Br.parse)(t,Br.STR|Br.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Sa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Sa(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Pp=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Sa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Sa(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=(0,Br.parse)(o,Br.STR|Br.OBJ),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},Ia=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Wa=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var zm="https://api.runtype.com/v1/dispatch",Ra="https://api.runtype.com",Hi=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 Vm(e){switch(e){case"json":return Pa;case"regex-json":return La;case"xml":return Ia;default:return Ma}}var Ip=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Jm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=Ip(t);if(!Ip(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Po(e);return Po(n)!==null&&a===null?n:e}var Io=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:zm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Vm(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ra;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ra}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(Hi).map(g=>{var w,x,M;return{id:g.id,role:g.role,content:(M=(x=(w=g.contentParts)!=null?w:g.llmContent)!=null?x:g.rawContent)!=null?M:g.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let 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 x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}if(f.status===429){let x=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:x}),x}let w=new Error(g.error||"Failed to send message");throw t({type:"error",error:w}),w}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,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ra}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var i,d;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||Ra}/resume`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,body:JSON.stringify({executionId:n,toolOutputs:t,streamResponse:(d=r==null?void 0:r.streamResponse)!=null?d:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Hi).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}}),r={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:n,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&&(r.context=s)}return r}async buildPayload(n){let r={messages:n.slice().filter(Hi).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:n,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&&(r.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...r},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var It,zt,wr,pr;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=I=>{let se=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,Ie=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,ze=I.tools?I.tools.map(Oe=>({...Oe,chunks:Oe.chunks?[...Oe.chunks]:void 0})):void 0;return{...I,reasoning:se,toolCall:Ie,tools:ze}},p=I=>{t({type:"message",message:u(I)})},f=null,g={current:null},w={current:null},x=!1,M=new Map,A=new Map,P=new Map,N=new Map,R={lastId:null,byStep:new Map},T={lastId:null,byCall:new Map},L=(I,se,Ie="")=>`${I}::${se}::${Ie}`,$=(I,se)=>`${I}::${se}::`,q=(I,se,Ie,ze)=>{let Oe=L(I,se,Ie),$e=P.get(Oe);if($e)return $e;let et=Ie?`-${Ie}`:"",wt={id:`nested-${I}-${se}${et}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ie?{partId:Ie}:{},agentMetadata:{executionId:ze,parentToolId:I,parentStepId:se}};return P.set(Oe,wt),p(wt),wt},_=I=>{if(I==null)return null;try{return String(I)}catch{return null}},B=I=>{var se,Ie,ze,Oe,$e;return _(($e=(Oe=(ze=(Ie=(se=I.stepId)!=null?se:I.step_id)!=null?Ie:I.step)!=null?ze:I.parentId)!=null?Oe:I.flowStepId)!=null?$e:I.flow_step_id)},O=I=>{var se,Ie,ze,Oe,$e,et,wt;return _((wt=(et=($e=(Oe=(ze=(Ie=(se=I.callId)!=null?se:I.call_id)!=null?Ie:I.requestId)!=null?ze:I.request_id)!=null?Oe:I.toolCallId)!=null?$e:I.tool_call_id)!=null?et:I.stepId)!=null?wt:I.step_id)},G=r,re=!1,Ee=()=>{if(f)return f;let I;return!re&&G?(I=G,re=!0):G&&w.current?I=`${G}_${w.current}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:I,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Re=(I,se)=>{R.lastId=se,I&&R.byStep.set(I,se)},Ue=(I,se)=>{var $e;let Ie=($e=I.reasoningId)!=null?$e:I.id,ze=B(I);if(Ie){let et=String(Ie);return Re(ze,et),et}if(ze){let et=R.byStep.get(ze);if(et)return R.lastId=et,et}if(R.lastId&&!se)return R.lastId;if(!se)return null;let Oe=`reason-${l()}`;return Re(ze,Oe),Oe},he=I=>{let se=M.get(I);if(se)return se;let Ie={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:I,status:"streaming",chunks:[]}};return M.set(I,Ie),p(Ie),Ie},ue=(I,se)=>{T.lastId=se,I&&T.byCall.set(I,se)},ke=new Set,je=new Map,te=new Set,ve=new Map,X=I=>{if(!I)return!1;let se=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return se==="emit_artifact_markdown"||se==="emit_artifact_component"},oe=(I,se)=>{var $e;let Ie=($e=I.toolId)!=null?$e:I.id,ze=O(I);if(Ie){let et=String(Ie);return ue(ze,et),et}if(ze){let et=T.byCall.get(ze);if(et)return T.lastId=et,et}if(T.lastId&&!se)return T.lastId;if(!se)return null;let Oe=`tool-${l()}`;return ue(ze,Oe),Oe},Le=I=>{let se=A.get(I);if(se)return se;let Ie={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:I,status:"pending"}};return A.set(I,Ie),p(Ie),Ie},ie=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let se=Number(I);if(!Number.isNaN(se)&&Number.isFinite(se))return se;let Ie=Date.parse(I);if(!Number.isNaN(Ie))return Ie}return Date.now()},De=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},He=new Map,K=new Map,Ne=new Map,Be=new Map,Q=null,J=(I,se,Ie)=>{var wt;let ze=Ne.get(I);ze||(ze=[],Ne.set(I,ze));let Oe=0,$e=ze.length;for(;Oe<$e;){let _t=Oe+$e>>>1;ze[_t].seq<se?Oe=_t+1:$e=_t}((wt=ze[Oe])==null?void 0:wt.seq)===se?ze[Oe]={seq:se,text:Ie}:ze.splice(Oe,0,{seq:se,text:Ie});let et="";for(let _t=0;_t<ze.length;_t++)et+=ze[_t].text;return et},we=(I,se)=>{let Ie=De(se),ze=K.get(I.id),Oe=Jm(ze,Ie);I.rawContent=Oe;let $e=He.get(I.id),et=ae=>{var ut;let Ce=(ut=I.content)!=null?ut:"";ae.trim()!==""&&(Ce.trim().length===0||ae.startsWith(Ce)||ae.trimStart().startsWith(Ce.trim()))&&(I.content=ae)},wt=()=>{var ae;if($e){let Ce=(ae=$e.close)==null?void 0:ae.call($e);Ce instanceof Promise&&Ce.catch(()=>{})}He.delete(I.id),K.delete(I.id),I.streaming=!1,p(I)};if(!$e){et(Ie),wt();return}let _t=Po(Oe);if(_t!==null&&_t.trim()!==""){et(_t),wt();return}let Vt=ae=>{var Ke;let Ce=typeof ae=="string"?ae:(Ke=ae==null?void 0:ae.text)!=null?Ke:null;if(Ce!==null&&Ce.trim()!=="")return Ce;let ut=$e.getExtractedText();return ut!==null&&ut.trim()!==""?ut:Ie},H;try{H=$e.processChunk(Oe)}catch{et(Ie),wt();return}if(H instanceof Promise){H.then(ae=>{et(Vt(ae)),wt()}).catch(()=>{et(Ie),wt()});return}et(Vt(H)),wt()},de=[],ne=!1,fe,Xe=()=>{ne||(ne=!0,queueMicrotask(()=>{ne=!1,fe()}))},$t=new Wa((I,se)=>{de.push({payloadType:I,payload:se}),Xe()}),le=null,Fe=new Map,ln=(It=this.config.iterationDisplay)!=null?It:"separate";for(fe=()=>{var I,se,Ie,ze,Oe,$e,et,wt,_t,Vt,H,ae,Ce,ut,Ke,Ft,cn,Ct,yt,Et,lt,Jt,Cr,qn,Ur,vt,ur,mr,Ar,er,dt,go,gr,fo,Tn,_o,jr,Sr,gt,Wn,Rn,bn,Tt,zn,Vn,Hn,qr,Er,zr,Bn,Mt,xn,Jn,Vr,Tr,Jr,fr,Dn,tr,pt,Kt,Gt,Nn,Kr,Kn,nr,Fn,U,pe,On,rr,hr,gs,or,sr,ar,kr,ho,ra,fs,oa,Uo,ct,hs,Gn,kn,sa,aa,jo,Mr,ia,yo,ys,Lr,bs,Gr,Qr,la,ca,Pi,bo,Xr,da,xs,Yr,pa,vs,Zr,ws,ua,Pr,ma,eo,Wt,qo,zo,Cs,yr,ga,As,Ss,Es,Ts,vn,$n,Ir,tt,ks,xo,ir,fa,Vo,Jo,vo,to,ha,ya,lr;for(let Wr=0;Wr<de.length;Wr++){let Je=de[Wr].payloadType,C=de[Wr].payload;if(Je==="reason_start"){let j=(I=Ue(C,!0))!=null?I:`reason-${l()}`,S=he(j);S.reasoning=(se=S.reasoning)!=null?se:{id:j,status:"streaming",chunks:[]},S.reasoning.startedAt=(ze=S.reasoning.startedAt)!=null?ze:ie((Ie=C.startedAt)!=null?Ie:C.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",p(S)}else if(Je==="reason_delta"||Je==="reason_chunk"){let j=($e=(Oe=Ue(C,!1))!=null?Oe:Ue(C,!0))!=null?$e:`reason-${l()}`,S=he(j);S.reasoning=(et=S.reasoning)!=null?et:{id:j,status:"streaming",chunks:[]},S.reasoning.startedAt=(_t=S.reasoning.startedAt)!=null?_t:ie((wt=C.startedAt)!=null?wt:C.timestamp);let z=(ae=(H=(Vt=C.reasoningText)!=null?Vt:C.text)!=null?H:C.delta)!=null?ae:"";if(z&&C.hidden!==!0){let Me=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(Me!==void 0){let ee=J(j,Me,String(z));S.reasoning.chunks=[ee]}else S.reasoning.chunks.push(String(z))}if(S.reasoning.status=C.done?"complete":"streaming",C.done){S.reasoning.completedAt=ie((Ce=C.completedAt)!=null?Ce:C.timestamp);let Me=(ut=S.reasoning.startedAt)!=null?ut:Date.now();S.reasoning.durationMs=Math.max(0,((Ke=S.reasoning.completedAt)!=null?Ke:Date.now())-Me)}S.streaming=S.reasoning.status!=="complete",p(S)}else if(Je==="reason_complete"){let j=(cn=(Ft=Ue(C,!1))!=null?Ft:Ue(C,!0))!=null?cn:`reason-${l()}`,S=M.get(j);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=ie((Ct=C.completedAt)!=null?Ct:C.timestamp);let Me=(yt=S.reasoning.startedAt)!=null?yt:Date.now();S.reasoning.durationMs=Math.max(0,((Et=S.reasoning.completedAt)!=null?Et:Date.now())-Me),S.streaming=!1,p(S)}let z=B(C);z&&R.byStep.delete(z)}else if(Je==="tool_start"){let j=(lt=oe(C,!0))!=null?lt:`tool-${l()}`,S=(Jt=C.toolName)!=null?Jt:C.name;if(X(S)){ke.add(j);continue}let z=Le(j),Me=(Cr=z.toolCall)!=null?Cr:{id:j,status:"pending"};Me.name=S!=null?S:Me.name,Me.status="running",C.args!==void 0?Me.args=C.args:C.parameters!==void 0&&(Me.args=C.parameters),Me.startedAt=(Ur=Me.startedAt)!=null?Ur:ie((qn=C.startedAt)!=null?qn:C.timestamp),Me.completedAt=void 0,Me.durationMs=void 0,z.toolCall=Me,z.streaming=!0;let ee=C.agentContext;(ee||C.executionId)&&(z.agentMetadata={executionId:(vt=ee==null?void 0:ee.executionId)!=null?vt:C.executionId,iteration:(ur=ee==null?void 0:ee.iteration)!=null?ur:C.iteration}),p(z)}else if(Je==="tool_chunk"||Je==="tool_delta"){let j=(Ar=(mr=oe(C,!1))!=null?mr:oe(C,!0))!=null?Ar:`tool-${l()}`;if(ke.has(j))continue;let S=Le(j),z=(er=S.toolCall)!=null?er:{id:j,status:"running"};z.startedAt=(go=z.startedAt)!=null?go:ie((dt=C.startedAt)!=null?dt:C.timestamp);let Me=(Tn=(fo=(gr=C.text)!=null?gr:C.delta)!=null?fo:C.message)!=null?Tn:"";Me&&(z.chunks=(_o=z.chunks)!=null?_o:[],z.chunks.push(String(Me))),z.status="running",S.toolCall=z,S.streaming=!0;let ee=C.agentContext;(ee||C.executionId)&&(S.agentMetadata=(gt=S.agentMetadata)!=null?gt:{executionId:(jr=ee==null?void 0:ee.executionId)!=null?jr:C.executionId,iteration:(Sr=ee==null?void 0:ee.iteration)!=null?Sr:C.iteration}),p(S)}else if(Je==="tool_complete"){let j=(Rn=(Wn=oe(C,!1))!=null?Wn:oe(C,!0))!=null?Rn:`tool-${l()}`;if(ke.has(j)){ke.delete(j);continue}let S=Le(j),z=(bn=S.toolCall)!=null?bn:{id:j,status:"running"};z.status="complete",C.result!==void 0&&(z.result=C.result),typeof C.duration=="number"&&(z.duration=C.duration),z.completedAt=ie((Tt=C.completedAt)!=null?Tt:C.timestamp);let Me=(zn=C.duration)!=null?zn:C.executionTime;if(typeof Me=="number")z.durationMs=Me;else{let Ge=(Vn=z.startedAt)!=null?Vn:Date.now();z.durationMs=Math.max(0,((Hn=z.completedAt)!=null?Hn:Date.now())-Ge)}S.toolCall=z,S.streaming=!1;let ee=C.agentContext;(ee||C.executionId)&&(S.agentMetadata=(zr=S.agentMetadata)!=null?zr:{executionId:(qr=ee==null?void 0:ee.executionId)!=null?qr:C.executionId,iteration:(Er=ee==null?void 0:ee.iteration)!=null?Er:C.iteration}),p(S);let Ye=O(C);Ye&&T.byCall.delete(Ye)}else if(Je==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let j=(Bn=C.toolId)!=null?Bn:`local-${l()}`,S=Le(j),z=(Mt=S.toolCall)!=null?Mt:{id:j,status:"pending"};z.name=C.toolName,z.args=C.parameters,z.status="complete",z.chunks=(xn=z.chunks)!=null?xn:[],z.startedAt=(Vr=z.startedAt)!=null?Vr:ie((Jn=C.startedAt)!=null?Jn:C.timestamp),z.completedAt=(Tr=z.completedAt)!=null?Tr:z.startedAt,S.toolCall=z,S.streaming=!1,S.agentMetadata={...S.agentMetadata,executionId:(fr=C.executionId)!=null?fr:(Jr=S.agentMetadata)==null?void 0:Jr.executionId,awaitingLocalTool:!0},p(S)}else if(Je==="text_start"){if((Dn=C.toolContext)!=null&&Dn.toolId)continue;let j=C.partId;if(j!==void 0&&w.current!==null&&j!==w.current){let S=f;S&&(S.streaming=!1,p(S),Q=S,f=null,x=!0)}j!==void 0&&(w.current=j)}else if(Je==="text_end"){if((tr=C.toolContext)!=null&&tr.toolId)continue;let j=f;j&&(j.streaming=!1,p(j),Q=j,f=null,x=!0)}else if(Je==="step_chunk"||Je==="step_delta"){let j=C.stepType,S=C.executionType;if(j==="tool"||S==="context")continue;let z=C.toolContext;if(z!=null&&z.toolId){let Ge=String((Kt=(pt=C.id)!=null?pt:z.stepId)!=null?Kt:`step-${l()}`),Lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",ft=`${z.toolId}::${Ge}`,Pt=N.get(ft);if(Lt!==""&&Pt!==void 0&&Pt!==""&&Pt!==Lt){let bt=P.get(L(z.toolId,Ge,Pt));bt&&bt.streaming!==!1&&(bt.streaming=!1,p(bt))}Lt!==""&&N.set(ft,Lt);let Dt=q(z.toolId,Ge,Lt,z.executionId),Qt=(Kn=(Kr=(Nn=(Gt=C.text)!=null?Gt:C.delta)!=null?Nn:C.content)!=null?Kr:C.chunk)!=null?Kn:"";Qt&&(Dt.content+=String(Qt),Dt.streaming=!0,p(Dt)),C.isComplete&&(Dt.streaming=!1,p(Dt));continue}let Me=C.partId;if(Me!==void 0&&w.current!==null&&Me!==w.current){let Ge=f;Ge&&(Ge.streaming=!1,p(Ge),Q=Ge,f=null,x=!0)}Me!==void 0&&(w.current=Me);let ee=Me!==void 0&&(nr=Be.get(Me))!=null?nr:Ee();Me!==void 0&&(ee.partId||(ee.partId=Me),Be.set(Me,ee));let Ye=(On=(pe=(U=(Fn=C.text)!=null?Fn:C.delta)!=null?U:C.content)!=null?pe:C.chunk)!=null?On:"";if(Ye){let Ge=typeof C.seq=="number"?C.seq:void 0,Lt=Me!=null?Me:ee.id,ft=Ge!==void 0?J(Lt,Ge,String(Ye)):((rr=K.get(ee.id))!=null?rr:"")+Ye;ee.rawContent=ft,He.has(ee.id)||He.set(ee.id,this.createStreamParser());let Pt=He.get(ee.id),Dt=ft.trim().startsWith("{")||ft.trim().startsWith("[");if(Dt&&K.set(ee.id,ft),Pt.__isPlainTextParser===!0){ee.content=Ge!==void 0?ft:ee.content+Ye,K.delete(ee.id),He.delete(ee.id),ee.rawContent=void 0,p(ee);continue}let bt=Pt.processChunk(ft);if(bt instanceof Promise)bt.then(ht=>{var mn;let rn=typeof ht=="string"?ht:(mn=ht==null?void 0:ht.text)!=null?mn:null;if(rn!==null&&rn.trim()!=="")ee.content=rn,p(ee);else if(!Dt&&!ft.trim().startsWith("<")){let dn=f,Xt=dn&&dn.id===ee.id?dn:ee;Xt.id===ee.id&&(Xt.content=Ge!==void 0?ft:Xt.content+Ye,K.delete(Xt.id),He.delete(Xt.id),Xt.rawContent=void 0,p(Xt))}}).catch(()=>{ee.content=Ge!==void 0?ft:ee.content+Ye,K.delete(ee.id),He.delete(ee.id),ee.rawContent=void 0,p(ee)});else{let ht=typeof bt=="string"?bt:(hr=bt==null?void 0:bt.text)!=null?hr:null;ht!==null&&ht.trim()!==""?(ee.content=ht,p(ee)):!Dt&&!ft.trim().startsWith("<")&&(ee.content=Ge!==void 0?ft:ee.content+Ye,K.delete(ee.id),He.delete(ee.id),ee.rawContent=void 0,p(ee))}}if(C.isComplete){let Ge=(or=(gs=C.result)==null?void 0:gs.response)!=null?or:ee.content;if(Ge){let Lt=K.get(ee.id),ft=Lt!=null?Lt:De(Ge);ee.rawContent=ft;let Pt=He.get(ee.id),Dt=null,Qt=!1;if(Pt&&(Dt=Pt.getExtractedText(),Dt===null&&(Dt=Po(ft)),Dt===null)){let bt=Pt.processChunk(ft);bt instanceof Promise?(Qt=!0,bt.then(ht=>{var mn;let rn=typeof ht=="string"?ht:(mn=ht==null?void 0:ht.text)!=null?mn:null;if(rn!==null){let dn=f;dn&&dn.id===ee.id&&(dn.content=rn,dn.streaming=!1,He.delete(dn.id),K.delete(dn.id),p(dn))}})):Dt=typeof bt=="string"?bt:(sr=bt==null?void 0:bt.text)!=null?sr:null}if(!Qt){Dt!==null&&Dt.trim()!==""?ee.content=Dt:K.has(ee.id)||(ee.content=De(Ge));let bt=He.get(ee.id);if(bt){let ht=(ar=bt.close)==null?void 0:ar.call(bt);ht instanceof Promise&&ht.catch(()=>{}),He.delete(ee.id)}K.delete(ee.id),ee.streaming=!1,p(ee)}}}}else if(Je==="step_complete"){let j=C.stepType,S=C.executionType;if(j==="tool"||S==="context")continue;let z=C.toolContext;if(z!=null&&z.toolId){let Ge=String((ho=(kr=C.id)!=null?kr:z.stepId)!=null?ho:"");if(Ge){let Lt=$(z.toolId,Ge);for(let[ft,Pt]of P)ft.startsWith(Lt)&&Pt.streaming!==!1&&(Pt.streaming=!1,p(Pt));N.delete(`${z.toolId}::${Ge}`)}continue}let Me=C.stopReason;if(x){if(f!==null){let ft=f;Me&&(ft.stopReason=Me),He.delete(ft.id),K.delete(ft.id),ft.streaming!==!1&&(ft.streaming=!1,p(ft))}let Ge=(ra=C.result)==null?void 0:ra.response,Lt=Q;Lt&&(Me&&(Lt.stopReason=Me),Ge!=null?we(Lt,Ge):(He.delete(Lt.id),K.delete(Lt.id))),Q=null;continue}let ee=(fs=C.result)==null?void 0:fs.response,Ye=Ee();if(Me&&(Ye.stopReason=Me),ee!=null){let Ge=He.get(Ye.id),Lt=!1,ft=!1;if(Ge){let Pt=Ge.getExtractedText(),Dt=K.get(Ye.id),Qt=Dt!=null?Dt:De(ee);if(Ye.rawContent=Qt,Pt!==null&&Pt.trim()!=="")Ye.content=Pt,Lt=!0;else{let bt=Po(Qt);if(bt!==null)Ye.content=bt,Lt=!0;else{let ht=Ge.processChunk(Qt);if(ht instanceof Promise)ft=!0,ht.then(rn=>{var dn;let mn=typeof rn=="string"?rn:(dn=rn==null?void 0:rn.text)!=null?dn:null;if(mn!==null&&mn.trim()!==""){let Xt=f;Xt&&Xt.id===Ye.id&&(Xt.content=mn,Xt.streaming=!1,He.delete(Xt.id),K.delete(Xt.id),p(Xt))}else{let Xt=Ge.getExtractedText(),an=f;an&&an.id===Ye.id&&(Xt!==null&&Xt.trim()!==""?an.content=Xt:K.has(an.id)||(an.content=De(ee)),an.streaming=!1,He.delete(an.id),K.delete(an.id),p(an))}});else{let rn=typeof ht=="string"?ht:(oa=ht==null?void 0:ht.text)!=null?oa:null;if(rn!==null&&rn.trim()!=="")Ye.content=rn,Lt=!0;else{let mn=Ge.getExtractedText();mn!==null&&mn.trim()!==""&&(Ye.content=mn,Lt=!0)}}}}}if(!ft){if(!Ye.rawContent){let Pt=K.get(Ye.id);Ye.rawContent=Pt!=null?Pt:De(ee)}if(!Lt&&!K.has(Ye.id)&&(Ye.content=De(ee)),Ge){let Pt=(Uo=Ge.close)==null?void 0:Uo.call(Ge);Pt instanceof Promise&&Pt.catch(()=>{})}He.delete(Ye.id),K.delete(Ye.id),Ye.streaming=!1,p(Ye)}}else He.delete(Ye.id),K.delete(Ye.id),Ye.streaming=!1,p(Ye)}else if(Je==="flow_complete"){let j=(ct=C.result)==null?void 0:ct.response;if(x){if(f!==null){let S=f;He.delete(S.id),K.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}}else if(j!=null){let S=Ee(),z=K.get(S.id),Me=z!=null?z:De(j);S.rawContent=Me;let ee=De(j),Ye=He.get(S.id);if(Ye){let ft=Po(Me);if(ft!==null)ee=ft;else{let Pt=Ye.processChunk(Me);Pt instanceof Promise&&Pt.then(Qt=>{var ht;let bt=typeof Qt=="string"?Qt:(ht=Qt==null?void 0:Qt.text)!=null?ht:null;bt!==null&&(S.content=bt,S.streaming=!1,p(S))});let Dt=Ye.getExtractedText();Dt!==null&&(ee=Dt)}}He.delete(S.id),K.delete(S.id);let Ge=ee!==S.content,Lt=S.streaming!==!1;Ge&&(S.content=ee),S.streaming=!1,(Ge||Lt)&&p(S)}else if(f!==null){let S=f;He.delete(S.id),K.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}t({type:"status",status:"idle"})}else if(Je==="agent_start")le={executionId:C.executionId,agentId:(hs=C.agentId)!=null?hs:"virtual",agentName:(Gn=C.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(kn=C.maxTurns)!=null?kn:1,startedAt:ie(C.startedAt)};else if(Je==="agent_iteration_start"){if(le&&(le.currentIteration=C.iteration),ln==="separate"&&C.iteration>1){let j=f;j&&(j.streaming=!1,p(j),Fe.set(C.iteration-1,j),f=null)}}else if(Je!=="agent_turn_start"){if(Je==="agent_turn_delta"){if(C.contentType==="text"){let j=Ee();j.content+=(sa=C.delta)!=null?sa:"",j.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:le==null?void 0:le.agentName},p(j)}else if(C.contentType==="thinking"){let j=(aa=C.turnId)!=null?aa:`agent-think-${C.iteration}`,S=he(j);S.reasoning=(jo=S.reasoning)!=null?jo:{id:j,status:"streaming",chunks:[]},S.reasoning.chunks.push((Mr=C.delta)!=null?Mr:""),S.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(S)}else if(C.contentType==="tool_input"){let j=(ia=C.toolCallId)!=null?ia:T.lastId;if(j){let S=A.get(j);S!=null&&S.toolCall&&(S.toolCall.chunks=(yo=S.toolCall.chunks)!=null?yo:[],S.toolCall.chunks.push((ys=C.delta)!=null?ys:""),p(S))}}}else if(Je==="agent_turn_complete"){let j=C.turnId;if(j){let z=M.get(j);if(z!=null&&z.reasoning){z.reasoning.status="complete",z.reasoning.completedAt=ie(C.completedAt);let Me=(Lr=z.reasoning.startedAt)!=null?Lr:Date.now();z.reasoning.durationMs=Math.max(0,((bs=z.reasoning.completedAt)!=null?bs:Date.now())-Me),z.streaming=!1,p(z)}}let S=C.stopReason;if(S&&f!==null){let z=C.turnId;(!z||((Gr=f.agentMetadata)==null?void 0:Gr.turnId)===z)&&(f.stopReason=S,p(f))}}else if(Je==="agent_tool_start"){let j=(Qr=C.toolCallId)!=null?Qr:`agent-tool-${l()}`;ue(O(C),j);let S=Le(j),z=(la=S.toolCall)!=null?la:{id:j,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};z.name=(Pi=(ca=C.toolName)!=null?ca:C.name)!=null?Pi:z.name,z.status="running",C.parameters!==void 0&&(z.args=C.parameters),z.startedAt=ie((bo=C.startedAt)!=null?bo:C.timestamp),S.toolCall=z,S.streaming=!0,S.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(S)}else if(Je==="agent_tool_delta"){let j=(Xr=C.toolCallId)!=null?Xr:T.lastId;if(j){let S=(da=A.get(j))!=null?da:Le(j);S.toolCall&&(S.toolCall.chunks=(xs=S.toolCall.chunks)!=null?xs:[],S.toolCall.chunks.push((Yr=C.delta)!=null?Yr:""),S.toolCall.status="running",S.streaming=!0,p(S))}}else if(Je==="agent_tool_complete"){let j=(pa=C.toolCallId)!=null?pa:T.lastId;if(j){let S=(vs=A.get(j))!=null?vs:Le(j);if(S.toolCall){S.toolCall.status="complete",C.result!==void 0&&(S.toolCall.result=C.result),typeof C.executionTime=="number"&&(S.toolCall.durationMs=C.executionTime),S.toolCall.completedAt=ie((Zr=C.completedAt)!=null?Zr:C.timestamp),S.streaming=!1,p(S);let z=O(C);z&&T.byCall.delete(z)}}}else if(Je!=="agent_iteration_complete"){if(Je==="agent_reflection"||Je==="agent_reflect"){let j=`agent-reflection-${C.executionId}-${C.iteration}`,S={id:j,role:"assistant",content:(ws=C.reflection)!=null?ws:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(ua=C.reflection)!=null?ua:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(S)}else if(Je==="agent_complete"){le&&(le.status=C.success?"complete":"error",le.completedAt=ie(C.completedAt),le.stopReason=C.stopReason);let j=f;j&&(j.streaming=!1,p(j)),t({type:"status",status:"idle"})}else if(Je==="agent_error"){let j=typeof C.error=="string"?C.error:(ma=(Pr=C.error)==null?void 0:Pr.message)!=null?ma:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):t({type:"error",error:new Error(j)})}else if(Je!=="agent_ping"){if(Je==="agent_approval_start"){let j=(eo=C.approvalId)!=null?eo:`approval-${l()}`,S={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Wt=le==null?void 0:le.agentId)!=null?Wt:"virtual",executionId:(zo=(qo=C.executionId)!=null?qo:le==null?void 0:le.executionId)!=null?zo:"",toolName:(Cs=C.toolName)!=null?Cs:"",toolType:C.toolType,description:(ga=C.description)!=null?ga:`Execute ${(yr=C.toolName)!=null?yr:"tool"}`,parameters:C.parameters}};p(S)}else if(Je==="step_await"&&C.awaitReason==="approval_required"){let j=(As=C.approvalId)!=null?As:`approval-${l()}`,S={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ss=le==null?void 0:le.agentId)!=null?Ss:"virtual",executionId:(Ts=(Es=C.executionId)!=null?Es:le==null?void 0:le.executionId)!=null?Ts:"",toolName:(vn=C.toolName)!=null?vn:"",toolType:C.toolType,description:(Ir=C.description)!=null?Ir:`Execute ${($n=C.toolName)!=null?$n:"tool"}`,parameters:C.parameters}};p(S)}else if(Je==="agent_approval_complete"){let j=C.approvalId;if(j){let z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(tt=C.decision)!=null?tt:"approved",agentId:(ks=le==null?void 0:le.agentId)!=null?ks:"virtual",executionId:(ir=(xo=C.executionId)!=null?xo:le==null?void 0:le.executionId)!=null?ir:"",toolName:(fa=C.toolName)!=null?fa:"",description:(Vo=C.description)!=null?Vo:"",resolvedAt:Date.now()}};p(z)}}else if(Je==="artifact_start"||Je==="artifact_delta"||Je==="artifact_update"||Je==="artifact_complete"){if(Je==="artifact_start"){let j=C.artifactType,S=String(C.id),z=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:S,artifactType:j,title:z,component:typeof C.component=="string"?C.component:void 0}),ve.set(S,{markdown:"",title:z}),!te.has(S)){te.add(S);let Me={id:`artifact-ref-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:S,title:z,artifactType:j,status:"streaming"}})};je.set(S,Me),p(Me)}}else if(Je==="artifact_delta"){let j=String(C.id),S=typeof C.delta=="string"?C.delta:String((Jo=C.delta)!=null?Jo:"");t({type:"artifact_delta",id:j,artDelta:S});let z=ve.get(j);z&&(z.markdown+=S)}else if(Je==="artifact_update"){let j=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:j,component:typeof C.component=="string"?C.component:void 0})}else if(Je==="artifact_complete"){let j=String(C.id);t({type:"artifact_complete",id:j});let S=je.get(j);if(S){S.streaming=!1;try{let z=JSON.parse((vo=S.rawContent)!=null?vo:"{}");if(z.props){z.props.status="complete";let Me=ve.get(j);Me!=null&&Me.markdown&&(z.props.markdown=Me.markdown)}S.rawContent=JSON.stringify(z)}catch{}ve.delete(j),p(S),je.delete(j)}}}else if(Je==="transcript_insert"){let j=C.message;if(!j||typeof j!="object")continue;let S=String((to=j.id)!=null?to:`msg-${l()}`),z=j.role,ee={id:S,role:z==="user"?"user":z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(p(ee),ee.rawContent)try{let Ye=JSON.parse(ee.rawContent),Ge=(ha=Ye==null?void 0:Ye.props)==null?void 0:ha.artifactId;typeof Ge=="string"&&te.add(Ge)}catch{}f=null,g.current=null,He.delete(S),K.delete(S)}else if(Je==="error"||Je==="step_error"||Je==="dispatch_error"||Je==="flow_error"){let j=null;if(C.error instanceof Error)j=C.error;else if(Je==="dispatch_error"){let S=(ya=C.message)!=null?ya:C.error;S!=null&&S!==""&&(j=new Error(String(S)))}else if(Je==="step_error"||Je==="flow_error"){let S=C.error;typeof S=="string"&&S!==""?j=new Error(S):S!=null&&typeof S=="object"&&"message"in S&&(j=new Error(String((lr=S.message)!=null?lr:S)))}else Je==="error"&&C.error!=null&&C.error!==""&&(j=new Error(String(C.error)));if(j){t({type:"error",error:j});let S=f;S&&S.streaming&&(S.streaming=!1,p(S)),t({type:"status",status:"idle"})}}}}}}de.length=0};;){let{done:I,value:se}=await s.read();if(I)break;a+=o.decode(se,{stream:!0});let Ie=a.split(`
5
5
 
6
- `);a=(Ye=Re.pop())!=null?Ye:"";for(let Ue of Re){let Qe=Ue.split(`
7
- `),Ze="message",H="";for(let ct of Qe)ct.startsWith("event:")?Ze=ct.replace("event:","").trim():ct.startsWith("data:")&&(H+=ct.replace("data:","").trim());if(!H)continue;let Te;try{Te=JSON.parse(H)}catch(ct){t({type:"error",error:ct instanceof Error?ct:new Error("Failed to parse chat stream payload")});continue}let Fe=Ze!=="message"?Ze:(Ot=Te.type)!=null?Ot:"message";if(($t=this.onSSEEvent)==null||$t.call(this,Fe,Te),this.parseSSEEvent){g.current=f;let ct=await this.handleCustomSSEEvent(Te,t,g,d,c,v);if(g.current&&g.current!==f&&(f=g.current),ct)continue}xt.push(Fe,Te),ae()}}xt.flushPending(),ae(),xt.destroy()}};function Kd(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Uo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function wo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var ha="[Image]";function Gd(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Qd(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Yd(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Xd(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function As(e){return{type:"text",text:e}}function Zd(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function ep(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function tp(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var np=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],um=["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"],Mr=[...np,...um];function mm(e){return np.includes(e)||e.startsWith("image/")}function ya(e){return mm(e.type)}async function rp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;ya(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function op(e,n=Mr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function gm(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function sp(e,n){let t=gm(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var ba=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let p=new Uint8Array(this.remainder.length+n.length);p.set(this.remainder),p.set(n,this.remainder.length),t=p,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let p=this.activeSources.indexOf(a);p!==-1&&this.activeSources.splice(p,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var xa=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let p=Math.sqrt(i/a.length);(r==="silence"?p<s.threshold:p>=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 Ss=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new xa;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,p=(r=this.config)==null?void 0:r.clientToken;if(!i||!p)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=${p}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let u=`${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,E=A=>{v||(v=!0,clearTimeout(w),g(new Error(A)))},w=setTimeout(()=>E("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{E("WebSocket connection failed to "+u+"."+d)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!v){let I=A.code!==1006?` (code ${A.code})`:"";E("WebSocket connection failed"+I+"."+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(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ba(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let 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=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,p=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:p,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 u=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",d=new Blob(this.audioChunks,{type:u});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(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let c=0;c<t.length;c++)r[c]=t.charCodeAt(c);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),p=new Audio(i);this.currentAudio=p,this.currentAudioUrl=i,p.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===p&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await p.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Co=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(p=>p[0]).map(p=>p.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(p=>p({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ao(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ss(e.runtype);case"browser":if(!Co.isSupported())throw new Error("Browser speech recognition not supported");return new Co(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function va(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ao({type:"runtype",runtype:e.runtype});if(Co.isSupported())return Ao({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Es(e){try{return va(e),!0}catch{return!1}}var qo=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,p;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=n.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(p=(i=this.callbacks).onError)==null||p.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new vo(n);for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Es((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Ao(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",p=(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 u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var u,d,f,g,v,E;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=c.transcript)!=null&&u.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 w=(E=this.pendingVoiceAssistantMessageId)!=null?E:(v=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:v.id;w&&this.ttsSpokenMessageIds.add(w)}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:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var u,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(u=this.callbacks).onVoiceStatusChanged)==null||d.call(u,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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,p,c,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(p=n.runtype)==null?void 0:p.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=n.browser)==null?void 0:c.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new vo(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:p,streaming:c=!1,voiceProcessing:u}=n,f={id:a!=null?a:t==="user"?Uo():t==="assistant"?wo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u}};return this.upsertMessage(f),f}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:p,createdAt:c,sequence:u,streaming:d=!1}=r,g={id:p!=null?p:s==="user"?Uo():s==="assistant"?wo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u: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(n,t){var c,u,d,f,g;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=Uo(),o=wo(),a={id:s,role:"user",content:r||ha,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 p=[...this.messages];try{await this.client.dispatch({messages:p,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!E){let w={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(w)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,E||(v instanceof Error?(d=(u=this.callbacks).onError)==null||d.call(u,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,p;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=wo();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(c){let u={id:n,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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(p=(i=this.callbacks).onError)==null||p.call(i,new Error(String(c)))}}async connectStream(n,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var p,c,u;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let d;if(i?d=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):d=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((p=g==null?void 0:g.error)!=null?p:`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-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(u=(c=this.callbacks).onError)==null||u.call(c,d instanceof Error?d:new Error(String(d)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,d,f,g,v,E,w,A,I,U,k;let r=this.messages.find(L=>L.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(d=n.agentMetadata)==null?void 0:d.executionId,o=(f=n.toolCall)==null?void 0:f.name;if(!s||!o){(v=(g=this.callbacks).onError)==null||v.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let L=(E=n.toolCall)==null?void 0:E.args,M=Array.isArray(L==null?void 0:L.questions)?L.questions:[];if(M.length===1){let P=typeof((w=M[0])==null?void 0:w.question)=="string"?M[0].question:"";P&&(a={[P]:t})}}this.markAskUserQuestionResolved(n,a);let i=n.toolCall.id,p=(A=n.toolCall)==null?void 0:A.args,c=Array.isArray(p==null?void 0:p.questions)?p.questions:[];if(c.length===0){let L=typeof t=="string"?t:Object.entries(t).map(([M,P])=>`${M}: ${Array.isArray(P)?P.join(", "):P}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:L,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let L=a!=null?a:{};c.forEach((M,P)=>{let N=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!N)return;let K=L[N],G=Array.isArray(K)?K.join(", "):typeof K=="string"?K:"";this.appendMessage({id:`ask-user-q-${i}-${P}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${P}`,role:"user",content:G||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let L=await this.client.resumeFlow(s,{[o]:t});if(!L.ok){let M=await L.json().catch(()=>null);throw new Error((I=M==null?void 0:M.error)!=null?I:`Resume failed: ${L.status}`)}L.body&&await this.connectStream(L.body)}catch(L){(k=(U=this.callbacks).onError)==null||k.call(U,L instanceof Error?L:new Error(String(L)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var i;if(o!==r)return s;let a={...s,...t};return((i=s.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var p,c;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(p=t.sequence)!=null?p:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},gr=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var fm=Dd(require("lucide"),1),Ae=(e,n=24,t="currentColor",r=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=fm[s];return o?hm(o,n,t,r):(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 hm(e,n,t,r){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&p.setAttribute(c,String(u))}),s.appendChild(p)}}}),s}var wa={allowedTypes:Mr,maxFileSize:10*1024*1024,maxFiles:4};function ym(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function bm(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 So=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:wa.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:wa.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:wa.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:wa.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,p;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let u=op(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let d=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await rp(c),f=ya(c)?URL.createObjectURL(c):null,g={id:ym(),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(),(p=(i=this.config).onAttachmentsChange)==null||p.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(p=>p.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=ya(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=bm(n.file.type),p=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let c=h("span");c.textContent=sp(n.file.type,n.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let 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=Ae("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var ap=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ts(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];ap(o)&&ap(s)?t[r]=Ts(o,s):t[r]=s}return t}var On="min(440px, calc(100vw - 24px))",Ca="440px",Rt={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:On,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ip(e,n){if(!(!e&&!n))return e?n?Ts(e,n):e:n}function Aa(e){var n,t,r,s,o,a,i,p,c,u,d,f,g,v,E,w,A,I,U,k,L;return e?{...Rt,...e,theme:ip(Rt.theme,e.theme),darkTheme:ip(Rt.darkTheme,e.darkTheme),launcher:{...Rt.launcher,...e.launcher,dock:{...(n=Rt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Rt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Rt.copy,...e.copy},sendButton:{...Rt.sendButton,...e.sendButton},statusIndicator:{...Rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Rt.voiceRecognition,...e.voiceRecognition},features:(()=>{var Le,Ne,de,X,ge,Q,me,pe;let M=(Le=Rt.features)==null?void 0:Le.artifacts,P=(Ne=e.features)==null?void 0:Ne.artifacts,N=(de=Rt.features)==null?void 0:de.scrollToBottom,K=(X=e.features)==null?void 0:X.scrollToBottom,G=(ge=Rt.features)==null?void 0:ge.streamAnimation,j=(Q=e.features)==null?void 0:Q.streamAnimation,ie=(me=Rt.features)==null?void 0:me.askUserQuestion,ve=(pe=e.features)==null?void 0:pe.askUserQuestion,ue=M===void 0&&P===void 0?void 0:{...M,...P,layout:{...M==null?void 0:M.layout,...P==null?void 0:P.layout}},Oe=N===void 0&&K===void 0?void 0:{...N,...K},fe=G===void 0&&j===void 0?void 0:{...G,...j},De=ie===void 0&&ve===void 0?void 0:{...ie,...ve,styles:{...ie==null?void 0:ie.styles,...ve==null?void 0:ve.styles}};return{...Rt.features,...e.features,...Oe!==void 0?{scrollToBottom:Oe}:{},...ue!==void 0?{artifacts:ue}:{},...fe!==void 0?{streamAnimation:fe}:{},...De!==void 0?{askUserQuestion:De}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Rt.suggestionChips,suggestionChipsConfig:{...Rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Rt.layout,...e.layout,header:{...(a=Rt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(p=Rt.layout)==null?void 0:p.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(u=Rt.layout)==null?void 0:u.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(E=(v=Rt.layout)==null?void 0:v.messages)==null?void 0:E.timestamp,...(A=(w=e.layout)==null?void 0:w.messages)==null?void 0:A.timestamp}},slots:{...(I=Rt.layout)==null?void 0:I.slots,...(U=e.layout)==null?void 0:U.slots}},markdown:{...Rt.markdown,...e.markdown,options:{...(k=Rt.markdown)==null?void 0:k.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Rt.messageActions,...e.messageActions}}:Rt}var ii={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"}},li={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"}},ci={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:On,maxWidth:Ca,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ms(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Ms(e,r):r}function Sa(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let p=Ms(e,a);p!==void 0&&(n[i]={path:i,value:p,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function di(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function lp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=lp(o,s):t[r]=s}return t}function xm(e,n){return n?lp(e,n):e}function zo(e,n={}){var s,o,a,i,p,c,u,d,f,g,v,E,w;let t={palette:ii,semantic:li,components:ci},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(p=e==null?void 0:e.palette)==null?void 0:p.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,...(u=e==null?void 0:e.semantic)==null?void 0:u.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,...(E=e==null?void 0:e.semantic)==null?void 0:E.spacing},typography:{...t.semantic.typography,...(w=e==null?void 0:e.semantic)==null?void 0:w.typography}},components:xm(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let A=di(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(I=>I.message).join(", ")}`)}if(n.plugins)for(let A of n.plugins)r=A.transform(r);return r}function Ea(e){var E,w,A,I,U,k,L,M,P,N,K,G,j,ie,ve,ue,Oe,fe,De,Le,Ne,de,X,ge,Q,me,pe,oe,Ie,Pe,R,z,ne,_,q,le,Ee,ee,ae,Lt,xt,Ke,sn,nt,he,Ye,Ot,$t,D,se,Re,Ue,Qe,Ze,H,Te,Fe,ct,Z,re,qe,dt,Nt,an,ht,ft,it,Me,st,ze,ln,cn,$n,dn,rt,Rr,kn,no,_n,Io,Hr,hr,yt,Ln,In,hn,It,jn,Un,Pn,Br,yr,Dr,Wn,Pt,yn,qn,Nr,br,Fr,lr,Rn,cr,At,zt,Vt,Hn,Or,zn,nr,Bn,F,rr,Vn,Jn,$r;let n=Sa(e),t={};for(let[ce,bn]of Object.entries(n)){let Dn=ce.replace(/\./g,"-");t[`--persona-${Dn}`]=bn.value}t["--persona-primary"]=(E=t["--persona-semantic-colors-primary"])!=null?E:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(w=t["--persona-semantic-colors-secondary"])!=null?w:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(A=t["--persona-semantic-colors-accent"])!=null?A:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(I=t["--persona-semantic-colors-surface"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(U=t["--persona-semantic-colors-background"])!=null?U:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(k=t["--persona-semantic-colors-container"])!=null?k:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(L=t["--persona-semantic-colors-text"])!=null?L:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(M=t["--persona-semantic-colors-text-muted"])!=null?M: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"]=(N=t["--persona-semantic-colors-border"])!=null?N:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(K=t["--persona-semantic-colors-divider"])!=null?K:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(G=t["--persona-components-voice-recording-indicator"])!=null?G:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(j=t["--persona-components-voice-recording-background"])!=null?j:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(ie=t["--persona-components-voice-processing-icon"])!=null?ie:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ve=t["--persona-components-voice-speaking-icon"])!=null?ve:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ue=t["--persona-components-approval-requested-background"])!=null?ue:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Oe=t["--persona-components-approval-requested-border"])!=null?Oe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(fe=t["--persona-components-approval-requested-text"])!=null?fe: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"]=(Le=t["--persona-components-approval-deny-background"])!=null?Le:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Ne=t["--persona-components-attachment-image-background"])!=null?Ne:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(de=t["--persona-components-attachment-image-border"])!=null?de:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(X=t["--persona-semantic-typography-fontFamily"])!=null?X:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ge=t["--persona-semantic-typography-fontSize"])!=null?ge:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Q=t["--persona-semantic-typography-fontWeight"])!=null?Q:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(me=t["--persona-semantic-typography-lineHeight"])!=null?me: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"]=(pe=t["--persona-palette-radius-sm"])!=null?pe:"0.125rem",t["--persona-radius-md"]=(oe=t["--persona-palette-radius-md"])!=null?oe:"0.375rem",t["--persona-radius-lg"]=(Ie=t["--persona-palette-radius-lg"])!=null?Ie:"0.5rem",t["--persona-radius-xl"]=(Pe=t["--persona-palette-radius-xl"])!=null?Pe:"0.75rem",t["--persona-radius-full"]=(R=t["--persona-palette-radius-full"])!=null?R:"9999px",t["--persona-launcher-radius"]=(ne=(z=t["--persona-components-launcher-borderRadius"])!=null?z:t["--persona-palette-radius-full"])!=null?ne:"9999px",t["--persona-launcher-bg"]=(_=t["--persona-components-launcher-background"])!=null?_:t["--persona-primary"],t["--persona-launcher-fg"]=(q=t["--persona-components-launcher-foreground"])!=null?q:t["--persona-text-inverse"],t["--persona-launcher-border"]=(le=t["--persona-components-launcher-border"])!=null?le:t["--persona-border"],t["--persona-button-primary-bg"]=(Ee=t["--persona-components-button-primary-background"])!=null?Ee:t["--persona-primary"],t["--persona-button-primary-fg"]=(ee=t["--persona-components-button-primary-foreground"])!=null?ee:t["--persona-text-inverse"],t["--persona-button-radius"]=(Lt=(ae=t["--persona-components-button-primary-borderRadius"])!=null?ae:t["--persona-palette-radius-full"])!=null?Lt:"9999px",t["--persona-panel-radius"]=(Ke=(xt=t["--persona-components-panel-borderRadius"])!=null?xt:t["--persona-radius-xl"])!=null?Ke:"0.75rem",t["--persona-panel-border"]=(sn=t["--persona-components-panel-border"])!=null?sn:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(he=(nt=t["--persona-components-panel-shadow"])!=null?nt:t["--persona-palette-shadows-xl"])!=null?he:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ot=(Ye=t["--persona-components-input-borderRadius"])!=null?Ye:t["--persona-radius-lg"])!=null?Ot:"0.5rem",t["--persona-message-user-radius"]=(D=($t=t["--persona-components-message-user-borderRadius"])!=null?$t:t["--persona-radius-lg"])!=null?D:"0.5rem",t["--persona-message-assistant-radius"]=(Re=(se=t["--persona-components-message-assistant-borderRadius"])!=null?se:t["--persona-radius-lg"])!=null?Re:"0.5rem",t["--persona-header-bg"]=(Ue=t["--persona-components-header-background"])!=null?Ue:t["--persona-surface"],t["--persona-header-border"]=(Qe=t["--persona-components-header-border"])!=null?Qe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Ze=t["--persona-components-header-iconBackground"])!=null?Ze:t["--persona-primary"],t["--persona-header-icon-fg"]=(H=t["--persona-components-header-iconForeground"])!=null?H:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Te=t["--persona-components-header-titleForeground"])!=null?Te:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Fe=t["--persona-components-header-subtitleForeground"])!=null?Fe:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ct=t["--persona-components-header-actionIconForeground"])!=null?ct:t["--persona-muted"];let r=(Z=e.components)==null?void 0:Z.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(re=e.components)==null?void 0:re.introCard;t["--persona-intro-card-bg"]=(qe=t["--persona-components-introCard-background"])!=null?qe:t["--persona-surface"],t["--persona-intro-card-radius"]=(dt=t["--persona-components-introCard-borderRadius"])!=null?dt:"1rem",t["--persona-intro-card-padding"]=(Nt=t["--persona-components-introCard-padding"])!=null?Nt:"1.5rem",t["--persona-intro-card-shadow"]=(ht=(an=s==null?void 0:s.shadow)!=null?an:t["--persona-components-introCard-shadow"])!=null?ht:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(ft=t["--persona-components-input-background"])!=null?ft:t["--persona-surface"],t["--persona-input-placeholder"]=(it=t["--persona-components-input-placeholder"])!=null?it:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Me=t["--persona-components-message-user-background"])!=null?Me:t["--persona-accent"],t["--persona-message-user-text"]=(st=t["--persona-components-message-user-text"])!=null?st:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(ze=t["--persona-components-message-user-shadow"])!=null?ze:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(ln=t["--persona-components-message-assistant-background"])!=null?ln:t["--persona-surface"],t["--persona-message-assistant-text"]=(cn=t["--persona-components-message-assistant-text"])!=null?cn:t["--persona-text"],t["--persona-message-assistant-border"]=($n=t["--persona-components-message-assistant-border"])!=null?$n:t["--persona-border"],t["--persona-message-assistant-shadow"]=(dn=t["--persona-components-message-assistant-shadow"])!=null?dn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Rr=(rt=t["--persona-components-scrollToBottom-background"])!=null?rt:t["--persona-button-primary-bg"])!=null?Rr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(no=(kn=t["--persona-components-scrollToBottom-foreground"])!=null?kn:t["--persona-button-primary-fg"])!=null?no:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(_n=t["--persona-components-scrollToBottom-border"])!=null?_n:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Io=t["--persona-components-scrollToBottom-size"])!=null?Io:"40px",t["--persona-scroll-to-bottom-radius"]=(yt=(hr=(Hr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Hr:t["--persona-button-radius"])!=null?hr:t["--persona-radius-full"])!=null?yt:"9999px",t["--persona-scroll-to-bottom-shadow"]=(In=(Ln=t["--persona-components-scrollToBottom-shadow"])!=null?Ln:t["--persona-palette-shadows-sm"])!=null?In:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(hn=t["--persona-components-scrollToBottom-padding"])!=null?hn:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(It=t["--persona-components-scrollToBottom-gap"])!=null?It:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Un=(jn=t["--persona-components-scrollToBottom-fontSize"])!=null?jn:t["--persona-palette-typography-fontSize-sm"])!=null?Un:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Pn=t["--persona-components-scrollToBottom-iconSize"])!=null?Pn:"14px",t["--persona-tool-bubble-shadow"]=(Br=t["--persona-components-toolBubble-shadow"])!=null?Br:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(yr=t["--persona-components-reasoningBubble-shadow"])!=null?yr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Dr=t["--persona-components-composer-shadow"])!=null?Dr:"none",t["--persona-md-inline-code-bg"]=(Wn=t["--persona-components-markdown-inlineCode-background"])!=null?Wn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Pt=t["--persona-components-markdown-inlineCode-foreground"])!=null?Pt:t["--persona-text"],t["--persona-md-link-color"]=(qn=(yn=t["--persona-components-markdown-link-foreground"])!=null?yn:t["--persona-accent"])!=null?qn:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let p=t["--persona-components-markdown-heading-h2-fontWeight"];p&&(t["--persona-md-h2-weight"]=p);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Nr=t["--persona-components-markdown-codeBlock-background"])!=null?Nr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(br=t["--persona-components-markdown-codeBlock-borderColor"])!=null?br:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Fr=t["--persona-components-markdown-codeBlock-textColor"])!=null?Fr:"inherit",t["--persona-md-table-header-bg"]=(lr=t["--persona-components-markdown-table-headerBackground"])!=null?lr:t["--persona-container"],t["--persona-md-table-border-color"]=(Rn=t["--persona-components-markdown-table-borderColor"])!=null?Rn:t["--persona-border"],t["--persona-md-hr-color"]=(cr=t["--persona-components-markdown-hr-color"])!=null?cr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(At=t["--persona-components-markdown-blockquote-borderColor"])!=null?At:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(zt=t["--persona-components-markdown-blockquote-background"])!=null?zt:"transparent",t["--persona-md-blockquote-text-color"]=(Vt=t["--persona-components-markdown-blockquote-textColor"])!=null?Vt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Hn=t["--persona-components-collapsibleWidget-container"])!=null?Hn:t["--persona-surface"],t["--cw-surface"]=(Or=t["--persona-components-collapsibleWidget-surface"])!=null?Or:t["--persona-surface"],t["--cw-border"]=(zn=t["--persona-components-collapsibleWidget-border"])!=null?zn:t["--persona-border"],t["--persona-message-border"]=(nr=t["--persona-components-message-border"])!=null?nr:t["--persona-border"];let u=e.components,d=u==null?void 0:u.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 f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let g=u==null?void 0:u.toggleGroup;g&&(g.gap&&(t["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(t["--persona-toggle-group-radius"]=g.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let ce=v.toolbar;ce.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ce.iconHoverColor),ce.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ce.iconHoverBackground),ce.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ce.iconPadding),ce.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ce.iconBorderRadius),ce.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ce.iconBorder),ce.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ce.toggleGroupGap),ce.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ce.toggleBorderRadius),ce.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ce.copyBackground),ce.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ce.copyBorder),ce.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ce.copyColor),ce.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ce.copyBorderRadius),ce.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ce.copyPadding),ce.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ce.copyMenuBackground,t["--persona-dropdown-bg"]=(Bn=t["--persona-dropdown-bg"])!=null?Bn:ce.copyMenuBackground),ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ce.copyMenuBorder,t["--persona-dropdown-border"]=(F=t["--persona-dropdown-border"])!=null?F:ce.copyMenuBorder),ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(rr=t["--persona-dropdown-shadow"])!=null?rr:ce.copyMenuShadow),ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Vn=t["--persona-dropdown-radius"])!=null?Vn:ce.copyMenuBorderRadius),ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Jn=t["--persona-dropdown-item-hover-bg"])!=null?Jn:ce.copyMenuItemHoverBackground),ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ce.iconBackground),ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ce.toolbarBorder)}if(v!=null&&v.tab){let ce=v.tab;ce.background&&(t["--persona-artifact-tab-bg"]=ce.background),ce.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ce.activeBackground),ce.activeBorder&&(t["--persona-artifact-tab-active-border"]=ce.activeBorder),ce.borderRadius&&(t["--persona-artifact-tab-radius"]=ce.borderRadius),ce.textColor&&(t["--persona-artifact-tab-color"]=ce.textColor),ce.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ce.hoverBackground),ce.listBackground&&(t["--persona-artifact-tab-list-bg"]=ce.listBackground),ce.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ce.listBorderColor),ce.listPadding&&(t["--persona-artifact-tab-list-padding"]=ce.listPadding)}if(v!=null&&v.pane){let ce=v.pane;if(ce.toolbarBackground){let bn=($r=Ms(e,ce.toolbarBackground))!=null?$r:ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=bn}}return t}var cp={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 vm={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"}}},dp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ks=()=>{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"},wm=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":ks()},pi=e=>wm(e),Cm=e=>zo(e),Am=e=>{var t;let n=zo(void 0,{validate:!1});return zo({...e,palette:{...n.palette,colors:{...vm.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Ls=e=>{let n=pi(e),t=dp(e==null?void 0:e.theme),r=dp(e==null?void 0:e.darkTheme);return n==="dark"?Am(Ts(t!=null?t:{},r!=null?r:{})):Cm(t)},Sm=e=>Ea(e),Jr=(e,n)=>{var o;let t=Ls(n),r=Sm(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Ta=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(ks())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ks());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};var pp=require("idiomorph"),up=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;pp.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let p=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(p!==c)return}return!1}}}}})};function mp(e,n){var t,r,s,o,a,i,p,c,u,d,f,g,v,E,w,A,I,U,k,L,M,P,N,K,G,j,ie,ve,ue,Oe;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(p=(i=e.rawContent)==null?void 0:i.length)!=null?p:0,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(w=(E=e.toolCall)==null?void 0:E.name)!=null?w:"",(U=(I=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:I.length)!=null?U:0,(P=(M=(L=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:M.slice(-32))!=null?P:"",typeof((N=e.toolCall)==null?void 0:N.args)=="string"?e.toolCall.args.length:(K=e.toolCall)!=null&&K.args?JSON.stringify(e.toolCall.args).length:0,(ie=(j=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:j.length)!=null?ie:0,(ue=(ve=e.contentParts)==null?void 0:ve.length)!=null?ue:0,(Oe=e.stopReason)!=null?Oe:"",n].join("\0")}function gp(){return new Map}function fp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function hp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function yp(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Ma(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Is(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ps(e,n){return Is(e)-e.scrollTop<=n}function ka(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:c=!1}=e,u=t-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!n&&s&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&p&&!s?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function La(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Tn=1e5,Kr=Tn+1;var Ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Em=["pre","code","a","script","style"],xp=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Ws.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Ws.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ws.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ws.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ws.buffer}},vp=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Rs=new Map;for(let e of vp)Rs.set(e.name,e);var wp=e=>{Rs.set(e.name,e)},Cp=e=>{vp.some(n=>n.name===e)||Rs.delete(e)},Ap=()=>Array.from(Rs.keys()),Ia=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Rs.get(e))!=null?r:null},Sp=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
8
- `);return o<0?"":e.slice(0,o)}return e},Tm=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},Mm=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},ui=/\s/,km=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Lm=(e,n,t)=>{var p;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(p=e.nodeValue)!=null?p:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(ui.test(o[i])){let c=i;for(;c<o.length&&ui.test(o[c]);)c+=1;a.appendChild(r.createTextNode(o.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=i;for(;u<o.length&&!ui.test(o[u]);)c.appendChild(Tm(r,o[u],n,t.value)),t.value+=1,u+=1;a.appendChild(c),i=u}s.replaceChild(a,e)},Im=(e,n,t)=>{var p;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(p=e.nodeValue)!=null?p:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Mm(r,c,n,t.value)),t.value+=1));s.replaceChild(a,e)},gi=(e,n,t,r)=>{var d;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((d=r==null?void 0:r.skipTags)!=null?d:Em).map(f=>f.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)km(p,o)||i.push(p),p=a.nextNode();let c={value:0},u=n==="char"?Lm:Im;for(let f of i)u(f,t,c);return s.innerHTML},Ep=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},fi=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},bp=new WeakMap,Pm=(e,n)=>{var o;if(!e.styles)return;let t=bp.get(n);if(t||(t=new Set,bp.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},mi=new WeakMap,Wm=(e,n)=>{if(!e.onAttach)return;let t=mi.get(n);if(t||(t=new Map,mi.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},Tp=e=>{let n=mi.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},Mp=(e,n)=>{Pm(e,n),Wm(e,n)};function hi(e,n=Tn){let t=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var Hs=0,Gr=null;function yi(e=document){var t;if(Hs++,Hs===1){let r=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Gr={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,Hs=Math.max(0,Hs-1),Hs===0&&Gr)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=Gr.originalOverflow,s.style.position=Gr.originalPosition,s.style.top=Gr.originalTop,s.style.width=Gr.originalWidth,o.scrollTo(0,Gr.scrollY),Gr=null}}}var Pa={side:"right",width:"420px",animate:!0,reveal:"resize"},Yt=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Zn=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:Pa.side,width:(s=n==null?void 0:n.width)!=null?s:Pa.width,animate:(o=n==null?void 0:n.animate)!=null?o:Pa.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:Pa.reveal}};var ir={"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 Bs=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
6
+ `);a=(zt=Ie.pop())!=null?zt:"";for(let ze of Ie){let Oe=ze.split(`
7
+ `),$e="message",et="";for(let Vt of Oe)Vt.startsWith("event:")?$e=Vt.replace("event:","").trim():Vt.startsWith("data:")&&(et+=Vt.replace("data:","").trim());if(!et)continue;let wt;try{wt=JSON.parse(et)}catch(Vt){t({type:"error",error:Vt instanceof Error?Vt:new Error("Failed to parse chat stream payload")});continue}let _t=$e!=="message"?$e:(wr=wt.type)!=null?wr:"message";if((pr=this.onSSEEvent)==null||pr.call(this,_t,wt),this.parseSSEEvent){g.current=f;let Vt=await this.handleCustomSSEEvent(wt,t,g,p,l,w);if(g.current&&g.current!==f&&(f=g.current),Vt)continue}$t.push(_t,wt),fe()}}$t.flushPending(),fe(),$t.destroy()}};function Wp(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Yo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function Wo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Ha="[Image]";function Rp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Hp(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Bp(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Dp(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Hs(e){return{type:"text",text:e}}function Np(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Fp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Op(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var $p=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Km=["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"],Dr=[...$p,...Km];function Gm(e){return $p.includes(e)||e.startsWith("image/")}function Ba(e){return Gm(e.type)}async function _p(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ba(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Up(e,n=Dr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Qm(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function jp(e,n){let t=Qm(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var Da=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Na=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Bs=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Na;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let w=!1,x=A=>{w||(w=!0,clearTimeout(M),g(new Error(A)))},M=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!w){let P=A.code!==1006?` (code ${A.code})`:"";x("WebSocket connection failed"+P+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Da(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ro=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ho(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(e.runtype);case"browser":if(!Ro.isSupported())throw new Error("Browser speech recognition not supported");return new Ro(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Fa(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ho({type:"runtype",runtype:e.runtype});if(Ro.isSupported())return Ho({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ds(e){try{return Fa(e),!0}catch{return!1}}var Zo=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=n.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Io(n);for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Ds((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Ho(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,g,w,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.text)!=null&&g.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(x=this.pendingVoiceAssistantMessageId)!=null?x:(w=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:w.id;M&&this.ttsSpokenMessageIds.add(M)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Io(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u}=n,f={id:a!=null?a:t==="user"?Yo():t==="assistant"?Wo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u}};return this.upsertMessage(f),f}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1}=r,g={id:d!=null?d:s==="user"?Yo():s==="assistant"?Wo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(n,t){var l,u,p,f,g;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let s=Yo(),o=Wo(),a={id:s,role:"user",content:r||Ha,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(w){let x=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!x){let M={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(M)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(w instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,w):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(w))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=Wo();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let u={id:n,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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(n,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,l,u;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):p=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let g=await p.json().catch(()=>null);throw new Error((d=g==null?void 0:g.error)!=null?d:`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-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(u=(l=this.callbacks).onError)==null||u.call(l,p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,p,f,g,w,x,M,A,P,N,R;let r=this.messages.find(T=>T.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=n.agentMetadata)==null?void 0:p.executionId,o=(f=n.toolCall)==null?void 0:f.name;if(!s||!o){(w=(g=this.callbacks).onError)==null||w.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let T=(x=n.toolCall)==null?void 0:x.args,L=Array.isArray(T==null?void 0:T.questions)?T.questions:[];if(L.length===1){let $=typeof((M=L[0])==null?void 0:M.question)=="string"?L[0].question:"";$&&(a={[$]:t})}}this.markAskUserQuestionResolved(n,a);let i=n.toolCall.id,d=(A=n.toolCall)==null?void 0:A.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let T=typeof t=="string"?t:Object.entries(t).map(([L,$])=>`${L}: ${Array.isArray($)?$.join(", "):$}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let T=a!=null?a:{};l.forEach((L,$)=>{let q=typeof(L==null?void 0:L.question)=="string"?L.question:"";if(!q)return;let _=T[q],B=Array.isArray(_)?_.join(", "):typeof _=="string"?_:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:q,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${$}`,role:"user",content:B||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let T=await this.client.resumeFlow(s,{[o]:t});if(!T.ok){let L=await T.json().catch(()=>null);throw new Error((P=L==null?void 0:L.error)!=null?P:`Resume failed: ${T.status}`)}T.body&&await this.connectStream(T.body)}catch(T){(R=(N=this.callbacks).onError)==null||R.call(N,T instanceof Error?T:new Error(String(T)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var i;if(o!==r)return s;let a={...s,...t};return((i=s.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},xr=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var v=require("lucide"),Xm={activity:v.Activity,"arrow-down":v.ArrowDown,"arrow-up":v.ArrowUp,"arrow-up-right":v.ArrowUpRight,bot:v.Bot,"chevron-down":v.ChevronDown,"chevron-up":v.ChevronUp,"chevron-right":v.ChevronRight,"chevron-left":v.ChevronLeft,check:v.Check,clipboard:v.Clipboard,"clipboard-copy":v.ClipboardCopy,copy:v.Copy,file:v.File,"file-code":v.FileCode,"file-spreadsheet":v.FileSpreadsheet,"file-text":v.FileText,"image-plus":v.ImagePlus,loader:v.Loader,"loader-circle":v.LoaderCircle,mic:v.Mic,paperclip:v.Paperclip,"refresh-cw":v.RefreshCw,search:v.Search,send:v.Send,"shield-alert":v.ShieldAlert,"shield-check":v.ShieldCheck,"shield-x":v.ShieldX,square:v.Square,"thumbs-down":v.ThumbsDown,"thumbs-up":v.ThumbsUp,upload:v.Upload,"volume-2":v.Volume2,x:v.X,user:v.User,mail:v.Mail,phone:v.Phone,calendar:v.Calendar,clock:v.Clock,building:v.Building,"map-pin":v.MapPin,lock:v.Lock,key:v.Key,"credit-card":v.CreditCard,"at-sign":v.AtSign,hash:v.Hash,globe:v.Globe,link:v.Link,"circle-check":v.CircleCheck,"circle-x":v.CircleX,"triangle-alert":v.TriangleAlert,info:v.Info,ban:v.Ban,shield:v.Shield,"arrow-left":v.ArrowLeft,"arrow-right":v.ArrowRight,"external-link":v.ExternalLink,ellipsis:v.Ellipsis,"ellipsis-vertical":v.EllipsisVertical,menu:v.Menu,house:v.House,plus:v.Plus,minus:v.Minus,pencil:v.Pencil,trash:v.Trash,"trash-2":v.Trash2,save:v.Save,download:v.Download,share:v.Share,funnel:v.Funnel,settings:v.Settings,"rotate-cw":v.RotateCw,maximize:v.Maximize,minimize:v.Minimize,"shopping-cart":v.ShoppingCart,"shopping-bag":v.ShoppingBag,package:v.Package,truck:v.Truck,tag:v.Tag,gift:v.Gift,receipt:v.Receipt,wallet:v.Wallet,store:v.Store,"dollar-sign":v.DollarSign,percent:v.Percent,play:v.Play,pause:v.Pause,"volume-x":v.VolumeX,camera:v.Camera,image:v.Image,film:v.Film,headphones:v.Headphones,"message-circle":v.MessageCircle,"message-square":v.MessageSquare,bell:v.Bell,heart:v.Heart,star:v.Star,eye:v.Eye,"eye-off":v.EyeOff,bookmark:v.Bookmark,"calendar-days":v.CalendarDays,history:v.History,timer:v.Timer,folder:v.Folder,"folder-open":v.FolderOpen,files:v.Files,sparkles:v.Sparkles,zap:v.Zap,sun:v.Sun,moon:v.Moon,flag:v.Flag,monitor:v.Monitor,smartphone:v.Smartphone},ge=(e,n=24,t="currentColor",r=2)=>{let s=Xm[e];return s?Ym(s,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Ym(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var Oa={allowedTypes:Dr,maxFileSize:10*1024*1024,maxFiles:4};function Zm(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function eg(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Bo=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Oa.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Oa.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Oa.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Oa.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let u=Up(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await _p(l),f=Ba(l)?URL.createObjectURL(l):null,g={id:Zm(),file:l,previewUrl:f,contentPart:p};this.attachments.push(g),this.renderPreview(g)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ba(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=eg(n.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=jp(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=ge("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var qp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ns(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];qp(o)&&qp(s)?t[r]=Ns(o,s):t[r]=s}return t}var jn="min(440px, calc(100vw - 24px))",$a="440px",Bt={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:jn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function zp(e,n){if(!(!e&&!n))return e?n?Ns(e,n):e:n}function _a(e){var n,t,r,s,o,a,i,d,l,u,p,f,g,w,x,M,A,P,N,R,T;return e?{...Bt,...e,theme:zp(Bt.theme,e.theme),darkTheme:zp(Bt.darkTheme,e.darkTheme),launcher:{...Bt.launcher,...e.launcher,dock:{...(n=Bt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Bt.copy,...e.copy},sendButton:{...Bt.sendButton,...e.sendButton},statusIndicator:{...Bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ue,ke,je,te,ve,X,oe,Le;let L=(ue=Bt.features)==null?void 0:ue.artifacts,$=(ke=e.features)==null?void 0:ke.artifacts,q=(je=Bt.features)==null?void 0:je.scrollToBottom,_=(te=e.features)==null?void 0:te.scrollToBottom,B=(ve=Bt.features)==null?void 0:ve.streamAnimation,O=(X=e.features)==null?void 0:X.streamAnimation,G=(oe=Bt.features)==null?void 0:oe.askUserQuestion,re=(Le=e.features)==null?void 0:Le.askUserQuestion,Ee=L===void 0&&$===void 0?void 0:{...L,...$,layout:{...L==null?void 0:L.layout,...$==null?void 0:$.layout}},Re=q===void 0&&_===void 0?void 0:{...q,..._},Ue=B===void 0&&O===void 0?void 0:{...B,...O},he=G===void 0&&re===void 0?void 0:{...G,...re,styles:{...G==null?void 0:G.styles,...re==null?void 0:re.styles}};return{...Bt.features,...e.features,...Re!==void 0?{scrollToBottom:Re}:{},...Ee!==void 0?{artifacts:Ee}:{},...Ue!==void 0?{streamAnimation:Ue}:{},...he!==void 0?{askUserQuestion:he}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Bt.layout,...e.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Bt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(x=(w=Bt.layout)==null?void 0:w.messages)==null?void 0:x.timestamp,...(A=(M=e.layout)==null?void 0:M.messages)==null?void 0:A.timestamp}},slots:{...(P=Bt.layout)==null?void 0:P.slots,...(N=e.layout)==null?void 0:N.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(R=Bt.markdown)==null?void 0:R.options,...(T=e.markdown)==null?void 0:T.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var Bi={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"}},Di={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"}},Ni={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:jn,maxWidth:$a,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function es(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?es(e,r):r}function Ua(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=es(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function Fi(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function Vp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=Vp(o,s):t[r]=s}return t}function tg(e,n){return n?Vp(e,n):e}function ts(e,n={}){var s,o,a,i,d,l,u,p,f,g,w,x,M;let t={palette:Bi,semantic:Di,components:Ni},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(w=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:w.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:tg(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let A=Fi(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(P=>P.message).join(", ")}`)}if(n.plugins)for(let A of n.plugins)r=A.transform(r);return r}function ja(e){var x,M,A,P,N,R,T,L,$,q,_,B,O,G,re,Ee,Re,Ue,he,ue,ke,je,te,ve,X,oe,Le,ie,De,He,K,Ne,Be,Q,J,we,de,ne,fe,Xe,$t,le,Fe,ln,It,zt,wr,pr,I,se,Ie,ze,Oe,$e,et,wt,_t,Vt,H,ae,Ce,ut,Ke,Ft,cn,Ct,yt,Et,lt,Jt,Cr,qn,Ur,vt,ur,mr,Ar,er,dt,go,gr,fo,Tn,_o,jr,Sr,gt,Wn,Rn,bn,Tt,zn,Vn,Hn,qr,Er,zr,Bn,Mt,xn,Jn,Vr,Tr,Jr,fr,Dn,tr,pt,Kt,Gt,Nn,Kr,Kn,nr,Fn,U;let n=Ua(e),t={};for(let[pe,On]of Object.entries(n)){let rr=pe.replace(/\./g,"-");t[`--persona-${rr}`]=On.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(A=t["--persona-semantic-colors-accent"])!=null?A:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(P=t["--persona-semantic-colors-surface"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(N=t["--persona-semantic-colors-background"])!=null?N: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"]=(T=t["--persona-semantic-colors-text"])!=null?T:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=($=t["--persona-semantic-colors-text-inverse"])!=null?$:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(q=t["--persona-semantic-colors-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(B=t["--persona-components-voice-recording-indicator"])!=null?B:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(G=t["--persona-components-voice-processing-icon"])!=null?G:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee: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"]=(Ue=t["--persona-components-approval-requested-text"])!=null?Ue:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(he=t["--persona-components-approval-approve-background"])!=null?he:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ue=t["--persona-components-approval-deny-background"])!=null?ue: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"]=(je=t["--persona-components-attachment-image-border"])!=null?je:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(te=t["--persona-semantic-typography-fontFamily"])!=null?te:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ve=t["--persona-semantic-typography-fontSize"])!=null?ve:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(X=t["--persona-semantic-typography-fontWeight"])!=null?X:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(oe=t["--persona-semantic-typography-lineHeight"])!=null?oe:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(Le=t["--persona-palette-radius-sm"])!=null?Le:"0.125rem",t["--persona-radius-md"]=(ie=t["--persona-palette-radius-md"])!=null?ie:"0.375rem",t["--persona-radius-lg"]=(De=t["--persona-palette-radius-lg"])!=null?De:"0.5rem",t["--persona-radius-xl"]=(He=t["--persona-palette-radius-xl"])!=null?He:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=(Be=(Ne=t["--persona-components-launcher-borderRadius"])!=null?Ne:t["--persona-palette-radius-full"])!=null?Be:"9999px",t["--persona-launcher-bg"]=(Q=t["--persona-components-launcher-background"])!=null?Q:t["--persona-primary"],t["--persona-launcher-fg"]=(J=t["--persona-components-launcher-foreground"])!=null?J:t["--persona-text-inverse"],t["--persona-launcher-border"]=(we=t["--persona-components-launcher-border"])!=null?we:t["--persona-border"],t["--persona-button-primary-bg"]=(de=t["--persona-components-button-primary-background"])!=null?de:t["--persona-primary"],t["--persona-button-primary-fg"]=(ne=t["--persona-components-button-primary-foreground"])!=null?ne:t["--persona-text-inverse"],t["--persona-button-radius"]=(Xe=(fe=t["--persona-components-button-primary-borderRadius"])!=null?fe:t["--persona-palette-radius-full"])!=null?Xe:"9999px",t["--persona-panel-radius"]=(le=($t=t["--persona-components-panel-borderRadius"])!=null?$t:t["--persona-radius-xl"])!=null?le:"0.75rem",t["--persona-panel-border"]=(Fe=t["--persona-components-panel-border"])!=null?Fe:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(It=(ln=t["--persona-components-panel-shadow"])!=null?ln:t["--persona-palette-shadows-xl"])!=null?It:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(wr=(zt=t["--persona-components-input-borderRadius"])!=null?zt:t["--persona-radius-lg"])!=null?wr:"0.5rem",t["--persona-message-user-radius"]=(I=(pr=t["--persona-components-message-user-borderRadius"])!=null?pr:t["--persona-radius-lg"])!=null?I:"0.5rem",t["--persona-message-assistant-radius"]=(Ie=(se=t["--persona-components-message-assistant-borderRadius"])!=null?se:t["--persona-radius-lg"])!=null?Ie:"0.5rem",t["--persona-header-bg"]=(ze=t["--persona-components-header-background"])!=null?ze:t["--persona-surface"],t["--persona-header-border"]=(Oe=t["--persona-components-header-border"])!=null?Oe:t["--persona-divider"],t["--persona-header-icon-bg"]=($e=t["--persona-components-header-iconBackground"])!=null?$e:t["--persona-primary"],t["--persona-header-icon-fg"]=(et=t["--persona-components-header-iconForeground"])!=null?et:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(wt=t["--persona-components-header-titleForeground"])!=null?wt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(_t=t["--persona-components-header-subtitleForeground"])!=null?_t:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Vt=t["--persona-components-header-actionIconForeground"])!=null?Vt:t["--persona-muted"];let r=(H=e.components)==null?void 0:H.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(ae=e.components)==null?void 0:ae.introCard;t["--persona-intro-card-bg"]=(Ce=t["--persona-components-introCard-background"])!=null?Ce:t["--persona-surface"],t["--persona-intro-card-radius"]=(ut=t["--persona-components-introCard-borderRadius"])!=null?ut:"1rem",t["--persona-intro-card-padding"]=(Ke=t["--persona-components-introCard-padding"])!=null?Ke:"1.5rem",t["--persona-intro-card-shadow"]=(cn=(Ft=s==null?void 0:s.shadow)!=null?Ft:t["--persona-components-introCard-shadow"])!=null?cn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ct=t["--persona-components-input-background"])!=null?Ct:t["--persona-surface"],t["--persona-input-placeholder"]=(yt=t["--persona-components-input-placeholder"])!=null?yt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Et=t["--persona-components-message-user-background"])!=null?Et:t["--persona-accent"],t["--persona-message-user-text"]=(lt=t["--persona-components-message-user-text"])!=null?lt: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"]=(Cr=t["--persona-components-message-assistant-background"])!=null?Cr:t["--persona-surface"],t["--persona-message-assistant-text"]=(qn=t["--persona-components-message-assistant-text"])!=null?qn:t["--persona-text"],t["--persona-message-assistant-border"]=(Ur=t["--persona-components-message-assistant-border"])!=null?Ur:t["--persona-border"],t["--persona-message-assistant-shadow"]=(vt=t["--persona-components-message-assistant-shadow"])!=null?vt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(mr=(ur=t["--persona-components-scrollToBottom-background"])!=null?ur:t["--persona-button-primary-bg"])!=null?mr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(er=(Ar=t["--persona-components-scrollToBottom-foreground"])!=null?Ar:t["--persona-button-primary-fg"])!=null?er:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(dt=t["--persona-components-scrollToBottom-border"])!=null?dt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(go=t["--persona-components-scrollToBottom-size"])!=null?go:"40px",t["--persona-scroll-to-bottom-radius"]=(Tn=(fo=(gr=t["--persona-components-scrollToBottom-borderRadius"])!=null?gr:t["--persona-button-radius"])!=null?fo:t["--persona-radius-full"])!=null?Tn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(jr=(_o=t["--persona-components-scrollToBottom-shadow"])!=null?_o:t["--persona-palette-shadows-sm"])!=null?jr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Sr=t["--persona-components-scrollToBottom-padding"])!=null?Sr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(gt=t["--persona-components-scrollToBottom-gap"])!=null?gt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Rn=(Wn=t["--persona-components-scrollToBottom-fontSize"])!=null?Wn:t["--persona-palette-typography-fontSize-sm"])!=null?Rn:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(bn=t["--persona-components-scrollToBottom-iconSize"])!=null?bn:"14px",t["--persona-tool-bubble-shadow"]=(Tt=t["--persona-components-toolBubble-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(zn=t["--persona-components-reasoningBubble-shadow"])!=null?zn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Vn=t["--persona-components-composer-shadow"])!=null?Vn:"none",t["--persona-md-inline-code-bg"]=(Hn=t["--persona-components-markdown-inlineCode-background"])!=null?Hn:t["--persona-container"],t["--persona-md-inline-code-color"]=(qr=t["--persona-components-markdown-inlineCode-foreground"])!=null?qr:t["--persona-text"],t["--persona-md-link-color"]=(zr=(Er=t["--persona-components-markdown-link-foreground"])!=null?Er:t["--persona-accent"])!=null?zr:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Bn=t["--persona-components-markdown-codeBlock-background"])!=null?Bn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Mt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Mt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(xn=t["--persona-components-markdown-codeBlock-textColor"])!=null?xn:"inherit",t["--persona-md-table-header-bg"]=(Jn=t["--persona-components-markdown-table-headerBackground"])!=null?Jn:t["--persona-container"],t["--persona-md-table-border-color"]=(Vr=t["--persona-components-markdown-table-borderColor"])!=null?Vr:t["--persona-border"],t["--persona-md-hr-color"]=(Tr=t["--persona-components-markdown-hr-color"])!=null?Tr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Jr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Jr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(fr=t["--persona-components-markdown-blockquote-background"])!=null?fr:"transparent",t["--persona-md-blockquote-text-color"]=(Dn=t["--persona-components-markdown-blockquote-textColor"])!=null?Dn:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(tr=t["--persona-components-collapsibleWidget-container"])!=null?tr:t["--persona-surface"],t["--cw-surface"]=(pt=t["--persona-components-collapsibleWidget-surface"])!=null?pt:t["--persona-surface"],t["--cw-border"]=(Kt=t["--persona-components-collapsibleWidget-border"])!=null?Kt:t["--persona-border"],t["--persona-message-border"]=(Gt=t["--persona-components-message-border"])!=null?Gt:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let g=u==null?void 0:u.toggleGroup;g&&(g.gap&&(t["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(t["--persona-toggle-group-radius"]=g.borderRadius));let w=u==null?void 0:u.artifact;if(w!=null&&w.toolbar){let pe=w.toolbar;pe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=pe.iconHoverColor),pe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=pe.iconHoverBackground),pe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=pe.iconPadding),pe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=pe.iconBorderRadius),pe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=pe.iconBorder),pe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=pe.toggleGroupGap),pe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=pe.toggleBorderRadius),pe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=pe.copyBackground),pe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=pe.copyBorder),pe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=pe.copyColor),pe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=pe.copyBorderRadius),pe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=pe.copyPadding),pe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=pe.copyMenuBackground,t["--persona-dropdown-bg"]=(Nn=t["--persona-dropdown-bg"])!=null?Nn:pe.copyMenuBackground),pe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=pe.copyMenuBorder,t["--persona-dropdown-border"]=(Kr=t["--persona-dropdown-border"])!=null?Kr:pe.copyMenuBorder),pe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=pe.copyMenuShadow,t["--persona-dropdown-shadow"]=(Kn=t["--persona-dropdown-shadow"])!=null?Kn:pe.copyMenuShadow),pe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=pe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(nr=t["--persona-dropdown-radius"])!=null?nr:pe.copyMenuBorderRadius),pe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=pe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Fn=t["--persona-dropdown-item-hover-bg"])!=null?Fn:pe.copyMenuItemHoverBackground),pe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=pe.iconBackground),pe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=pe.toolbarBorder)}if(w!=null&&w.tab){let pe=w.tab;pe.background&&(t["--persona-artifact-tab-bg"]=pe.background),pe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=pe.activeBackground),pe.activeBorder&&(t["--persona-artifact-tab-active-border"]=pe.activeBorder),pe.borderRadius&&(t["--persona-artifact-tab-radius"]=pe.borderRadius),pe.textColor&&(t["--persona-artifact-tab-color"]=pe.textColor),pe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=pe.hoverBackground),pe.listBackground&&(t["--persona-artifact-tab-list-bg"]=pe.listBackground),pe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=pe.listBorderColor),pe.listPadding&&(t["--persona-artifact-tab-list-padding"]=pe.listPadding)}if(w!=null&&w.pane){let pe=w.pane;if(pe.toolbarBackground){let On=(U=es(e,pe.toolbarBackground))!=null?U:pe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=On}}return t}var Jp={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 ng={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"}}},Kp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Fs=()=>{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"},rg=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Fs()},Oi=e=>rg(e),og=e=>ts(e),sg=e=>{var t;let n=ts(void 0,{validate:!1});return ts({...e,palette:{...n.palette,colors:{...ng.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},ns=e=>{let n=Oi(e),t=Kp(e==null?void 0:e.theme),r=Kp(e==null?void 0:e.darkTheme);return n==="dark"?sg(Ns(t!=null?t:{},r!=null?r:{})):og(t)},ag=e=>ja(e),ro=(e,n)=>{var o;let t=ns(n),r=ag(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},qa=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Fs())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Fs());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};var Gp=require("idiomorph"),za=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Gp.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function Qp(e,n){var t,r,s,o,a,i,d,l,u,p,f,g,w,x,M,A,P,N,R,T,L,$,q,_,B,O,G,re,Ee,Re;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(w=(g=e.toolCall)==null?void 0:g.status)!=null?w:"",(M=(x=e.toolCall)==null?void 0:x.name)!=null?M:"",(N=(P=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:P.length)!=null?N:0,($=(L=(T=(R=e.toolCall)==null?void 0:R.chunks)==null?void 0:T[e.toolCall.chunks.length-1])==null?void 0:L.slice(-32))!=null?$:"",typeof((q=e.toolCall)==null?void 0:q.args)=="string"?e.toolCall.args.length:(_=e.toolCall)!=null&&_.args?JSON.stringify(e.toolCall.args).length:0,(G=(O=(B=e.reasoning)==null?void 0:B.chunks)==null?void 0:O.length)!=null?G:0,(Ee=(re=e.contentParts)==null?void 0:re.length)!=null?Ee:0,(Re=e.stopReason)!=null?Re:"",n].join("\0")}function Xp(){return new Map}function Yp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Zp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function eu(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Va(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Os(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function $s(e,n){return Os(e)-e.scrollTop<=n}function Ja(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!n&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Ka(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,oo=yn+1;var _s={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ig=["pre","code","a","script","style"],Ga=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:_s.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:_s.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:_s.speed,duration:(s=e==null?void 0:e.duration)!=null?s:_s.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:_s.buffer}},nu=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Us=new Map;for(let e of nu)Us.set(e.name,e);var ru=e=>{Us.set(e.name,e)},ou=e=>{nu.some(n=>n.name===e)||Us.delete(e)},su=()=>Array.from(Us.keys()),js=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Us.get(e))!=null?r:null},Qa=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
8
+ `);return o<0?"":e.slice(0,o)}return e},lg=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},cg=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},$i=/\s/,dg=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},pg=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if($i.test(o[i])){let l=i;for(;l<o.length&&$i.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!$i.test(o[u]);)l.appendChild(lg(r,o[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},ug=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(cg(r,l,n,t.value)),t.value+=1));s.replaceChild(a,e)},qs=(e,n,t,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((p=r==null?void 0:r.skipTags)!=null?p:ig).map(g=>g.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)dg(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?pg:ug;for(let g of i)u(g,t,l);return s.innerHTML},Xa=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},zs=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},tu=new WeakMap,mg=(e,n)=>{var o;if(!e.styles)return;let t=tu.get(n);if(t||(t=new Set,tu.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},_i=new WeakMap,gg=(e,n)=>{if(!e.onAttach)return;let t=_i.get(n);if(t||(t=new Map,_i.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},au=e=>{let n=_i.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},Ui=(e,n)=>{mg(e,n),gg(e,n)};function ji(e,n=yn){let t=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var Vs=0,so=null;function qi(e=document){var t;if(Vs++,Vs===1){let r=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;so={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,Vs=Math.max(0,Vs-1),Vs===0&&so)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=so.originalOverflow,s.style.position=so.originalPosition,s.style.top=so.originalTop,s.style.width=so.originalWidth,o.scrollTo(0,so.scrollY),so=null}}}var Ya={side:"right",width:"420px",animate:!0,reveal:"resize"},nn=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},ao=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},Xn=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:Ya.side,width:(s=n==null?void 0:n.width)!=null?s:Ya.width,animate:(o=n==null?void 0:n.animate)!=null?o:Ya.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:Ya.reveal}};var dr={"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 Js=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
9
9
  <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>
10
10
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
11
11
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -13,14 +13,14 @@
13
13
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
14
14
  </span>
15
15
  <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>
16
- `,t.addEventListener("click",n);let r=o=>{var U,k,L,M,P,N,K,G,j,ie,ve,ue,Oe,fe;let a=(U=o.launcher)!=null?U:{},i=Yt(o),p=t.querySelector("[data-role='launcher-title']");if(p){let De=(k=a.title)!=null?k:"Chat Assistant";p.textContent=De,p.setAttribute("title",De)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let De=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=De,c.setAttribute("title",De)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let De=(M=a.agentIconSize)!=null?M:"40px";if(d.style.height=De,d.style.width=De,d.innerHTML="",a.agentIconName){let Le=parseFloat(De)||24,Ne=Ae(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);Ne?(d.appendChild(Ne),d.style.display=""):(d.textContent=(P=a.agentIconText)!=null?P:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(N=a.agentIconText)!=null?N:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let De=(K=a.agentIconSize)!=null?K:"40px";f.style.height=De,f.style.width=De,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 De=(G=a.callToActionIconSize)!=null?G:"32px";g.style.height=De,g.style.width=De,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 Le=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Le=(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 Ne=parseFloat(De)||24,de=Math.max(Ne-Le,8),X=Ae(a.callToActionIconName,de,"currentColor",2);X?g.appendChild(X):g.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else g.textContent=(ie=a.callToActionIconText)!=null?ie:"\u2197"}let v=a.position&&ir[a.position]?ir[a.position]:ir["bottom-right"],E="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",w="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?w:`${E} ${v}`,i||(t.style.zIndex=String((ve=a.zIndex)!=null?ve:Tn));let A="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(ue=a.border)!=null?ue:A,t.style.boxShadow=(Oe=a.shadow)!=null?Oe:I,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=(fe=a.collapsedMaxWidth)!=null?fe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Mn={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))"},kr=e=>{var G,j,ie,ve,ue,Oe,fe,De,Le,Ne,de,X,ge,Q,me,pe,oe,Ie,Pe,R,z,ne,_,q,le,Ee,ee,ae,Lt,xt,Ke,sn;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(G=n==null?void 0:n.launcher)!=null?G:{},o=(j=s.headerIconSize)!=null?j:"48px",a=(ie=s.closeButtonSize)!=null?ie:"32px",i=(ve=s.closeButtonPlacement)!=null?ve:"inline",p=(ue=s.headerIconHidden)!=null?ue:!1,c=s.headerIconName,u=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(u.style.height=o,u.style.width=o,u.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",u.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!p)if(c){let nt=parseFloat(o)||24,he=Ae(c,nt*.6,"currentColor",1);he?u.replaceChildren(he):u.textContent=(fe=(Oe=n==null?void 0:n.launcher)==null?void 0:Oe.agentIconText)!=null?fe:"\u{1F4AC}"}else if((De=n==null?void 0:n.launcher)!=null&&De.iconUrl){let nt=h("img");nt.src=n.launcher.iconUrl,nt.alt="",nt.className="persona-rounded-xl persona-object-cover",nt.style.height=o,nt.style.width=o,u.replaceChildren(nt)}else u.textContent=(Ne=(Le=n==null?void 0:n.launcher)==null?void 0:Le.agentIconText)!=null?Ne:"\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=Mn.titleColor,f.textContent=(X=(de=n==null?void 0:n.launcher)==null?void 0:de.title)!=null?X:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(Q=(ge=n==null?void 0:n.launcher)==null?void 0:ge.subtitle)!=null?Q:"Here to help you get answers fast",d.append(f,g),p?r.append(d):r.append(u,d);let v=(me=s.clearChat)!=null?me:{},E=(pe=v.enabled)!=null?pe:!0,w=(oe=v.placement)!=null?oe:"inline",A=null,I=null;if(E){let nt=(Ie=v.size)!=null?Ie:"32px",he=(Pe=v.iconName)!=null?Pe:"refresh-cw",Ye=(R=v.iconColor)!=null?R:"",Ot=(z=v.backgroundColor)!=null?z:"",$t=(ne=v.borderWidth)!=null?ne:"",D=(_=v.borderColor)!=null?_:"",se=(q=v.borderRadius)!=null?q:"",Re=(le=v.paddingX)!=null?le:"",Ue=(Ee=v.paddingY)!=null?Ee:"",Qe=(ee=v.tooltipText)!=null?ee:"Clear chat",Ze=(ae=v.showTooltip)!=null?ae:!0;I=h("div",w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),w==="top-right"&&(I.style.right="48px"),A=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"),A.style.height=nt,A.style.width=nt,A.type="button",A.setAttribute("aria-label",Qe),A.style.color=Ye||Mn.actionIconColor;let H=Ae(he,"20px","currentColor",1);if(H&&(H.style.display="block",A.appendChild(H)),Ot&&(A.style.backgroundColor=Ot,A.classList.remove("hover:persona-bg-gray-100")),$t||D){let Te=$t||"0px",Fe=D||"transparent";A.style.border=`${Te} solid ${Fe}`,A.classList.remove("persona-border-none")}if(se&&(A.style.borderRadius=se,A.classList.remove("persona-rounded-full")),Re?(A.style.paddingLeft=Re,A.style.paddingRight=Re):(A.style.paddingLeft="",A.style.paddingRight=""),Ue?(A.style.paddingTop=Ue,A.style.paddingBottom=Ue):(A.style.paddingTop="",A.style.paddingBottom=""),I.appendChild(A),Ze&&Qe&&A&&I){let Te=null,Fe=()=>{if(Te||!A)return;let Z=A.ownerDocument,re=Z.body;if(!re)return;Te=gr(Z,"div","persona-clear-chat-tooltip"),Te.textContent=Qe;let qe=gr(Z,"div");qe.className="persona-clear-chat-tooltip-arrow",Te.appendChild(qe);let dt=A.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(Kr),Te.style.left=`${dt.left+dt.width/2}px`,Te.style.top=`${dt.top-8}px`,Te.style.transform="translate(-50%, -100%)",re.appendChild(Te)},ct=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};I.addEventListener("mouseenter",Fe),I.addEventListener("mouseleave",ct),A.addEventListener("focus",Fe),A.addEventListener("blur",ct),I._cleanupTooltip=()=>{ct(),I&&(I.removeEventListener("mouseenter",Fe),I.removeEventListener("mouseleave",ct)),A&&(A.removeEventListener("focus",Fe),A.removeEventListener("blur",ct))}}w==="inline"&&r.appendChild(I)}let U=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&w==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center"),k=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");k.style.height=a,k.style.width=a,k.type="button";let L=(Lt=s.closeButtonTooltipText)!=null?Lt:"Close chat",M=(xt=s.closeButtonShowTooltip)!=null?xt:!0;k.setAttribute("aria-label",L),k.style.display=t?"":"none";let P=(Ke=s.closeButtonIconName)!=null?Ke:"x",N=(sn=s.closeButtonIconText)!=null?sn:"\xD7";k.style.color=s.closeButtonColor||Mn.actionIconColor;let K=Ae(P,"28px","currentColor",1);if(K?(K.style.display="block",k.appendChild(K)):k.textContent=N,s.closeButtonBackgroundColor?(k.style.backgroundColor=s.closeButtonBackgroundColor,k.classList.remove("hover:persona-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let nt=s.closeButtonBorderWidth||"0px",he=s.closeButtonBorderColor||"transparent";k.style.border=`${nt} solid ${he}`,k.classList.remove("persona-border-none")}else k.style.border="",k.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(k.style.borderRadius=s.closeButtonBorderRadius,k.classList.remove("persona-rounded-full")):(k.style.borderRadius="",k.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(k.style.paddingLeft=s.closeButtonPaddingX,k.style.paddingRight=s.closeButtonPaddingX):(k.style.paddingLeft="",k.style.paddingRight=""),s.closeButtonPaddingY?(k.style.paddingTop=s.closeButtonPaddingY,k.style.paddingBottom=s.closeButtonPaddingY):(k.style.paddingTop="",k.style.paddingBottom=""),U.appendChild(k),M&&L){let nt=null,he=()=>{if(nt)return;let Ot=k.ownerDocument,$t=Ot.body;if(!$t)return;nt=gr(Ot,"div","persona-clear-chat-tooltip"),nt.textContent=L;let D=gr(Ot,"div");D.className="persona-clear-chat-tooltip-arrow",nt.appendChild(D);let se=k.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Kr),nt.style.left=`${se.left+se.width/2}px`,nt.style.top=`${se.top-8}px`,nt.style.transform="translate(-50%, -100%)",$t.appendChild(nt)},Ye=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};U.addEventListener("mouseenter",he),U.addEventListener("mouseleave",Ye),k.addEventListener("focus",he),k.addEventListener("blur",Ye),U._cleanupTooltip=()=>{Ye(),U.removeEventListener("mouseenter",he),U.removeEventListener("mouseleave",Ye),k.removeEventListener("focus",he),k.removeEventListener("blur",Ye)}}return i!=="top-right"&&r.appendChild(U),{header:r,iconHolder:u,headerTitle:f,headerSubtitle:g,closeButton:k,closeButtonWrapper:U,clearChatButton:A,clearChatButtonWrapper:I}},Eo=(e,n,t)=>{var a,i,p,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(p=r.clearChat)==null?void 0:p.placement)!=null?c:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Qr(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Kr)):(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 n){if(g.dividerBefore){let w=document.createElement("hr");a.appendChild(w)}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 w=Ae(g.icon,16,"currentColor",1.5);w&&v.appendChild(w)}let E=document.createElement("span");E.textContent=g.label,v.appendChild(E),v.addEventListener("click",w=>{w.stopPropagation(),u(),t(g.id)}),a.appendChild(v)}let i=null;function p(){if(!o)return;let g=r.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(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function d(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:d,destroy:f}}function Ft(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,p=h("button","persona-icon-btn"+(o?" "+o:""));p.type="button",p.setAttribute("aria-label",t),p.title=t;let c=Ae(n,r!=null?r:16,"currentColor",s!=null?s:2);if(c&&p.appendChild(c),a&&p.addEventListener("click",a),i)for(let[u,d]of Object.entries(i))p.setAttribute(u,d);return p}function Ds(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:p}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let u=h("button",c);if(u.type="button",u.setAttribute("aria-label",t),n){let f=Ae(n,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let d=h("span");if(d.textContent=t,u.appendChild(d),i&&u.addEventListener("click",i),p)for(let[f,g]of Object.entries(p))u.setAttribute(f,g);return u}function Ns(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function p(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let d;u.icon?d=Ft({icon:u.icon,label:u.label,onClick:()=>{a=u.id,p(),r(u.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",u.label),d.title=u.label,d.textContent=u.label,d.addEventListener("click",()=>{a=u.id,p(),r(u.id)})),d.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:d}),o.appendChild(d)}function c(u){a=u,p()}return{element:o,setSelected:c}}function Wa(e){var g,v;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:p}=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",n);let u=h("span","persona-combo-btn-label");u.textContent=n,c.appendChild(u);let d=Ae(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),p&&(c.style.borderRadius=(g=p.borderRadius)!=null?g:"10px",c.style.padding=(v=p.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 E,w;c.style.backgroundColor=(E=p.background)!=null?E:"",c.style.borderColor=(w=p.border)!=null?w:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Qr({items:r,onSelect:E=>{c.setAttribute("aria-expanded","false"),s(E)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",E=>{E.stopPropagation();let w=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),f.toggle()}),c.addEventListener("keydown",E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),c.click())}),{element:c,setLabel:E=>{u.textContent=E,c.setAttribute("aria-label",E)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let E=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var bi=e=>{var r;let n=kr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function Rm(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let p=Ae(a.icon,14,"currentColor",2);p&&i.appendChild(p)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let p=h("div","persona-relative");p.appendChild(i);let c=Qr({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:p,position:"bottom-left"});p.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(p)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var xi=e=>{var I,U,k,L,M,P,N,K,G;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(I=n==null?void 0:n.launcher)!=null?I:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=s==null?void 0:s.titleMenu,c,u;if(p)c=Wa({label:(U=a.title)!=null?U:"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Mn.titleColor,u=(k=c.querySelector(".persona-combo-btn-label"))!=null?k:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Mn.titleColor,u.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(u),Rm(c,s==null?void 0:s.trailingActions,(M=s==null?void 0:s.onAction)!=null?M:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ie=s.onTitleClick;c.addEventListener("click",ve=>{ve.target.closest("button")||ie()}),c.addEventListener("keydown",ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),ie())})}let j=s==null?void 0:s.titleRowHover;j&&(c.style.borderRadius=(P=j.borderRadius)!=null?P:"10px",c.style.padding=(N=j.padding)!=null?N:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ie,ve;c.style.backgroundColor=(ie=j.background)!=null?ie:"",c.style.borderColor=(ve=j.border)!=null?ve:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(K=a.closeButtonSize)!=null?K:"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||Mn.actionIconColor;let v=(G=a.closeButtonIconName)!=null?G:"x",E=Ae(v,"28px","currentColor",1);E?g.appendChild(E):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let w=h("div");w.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:w,headerTitle:u,headerSubtitle:A,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ra={default:bi,minimal:xi},vi=e=>{var n;return(n=Ra[e])!=null?n:Ra.default},Vo=(e,n,t)=>{var a,i,p;if(n!=null&&n.render){let c=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let 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:u,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=vi(r)({config:e,showClose:(p=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?p:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Jo=e=>{var Ee,ee,ae,Lt,xt,Ke,sn,nt,he,Ye,Ot,$t,D,se,Re,Ue,Qe,Ze,H,Te,Fe,ct,Z,re,qe,dt,Nt,an,ht,ft,it;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=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=(ee=(Ee=n==null?void 0:n.copy)==null?void 0:Ee.inputPlaceholder)!=null?ee:"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 p=3*20;o.style.maxHeight=`${p}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let Me=Math.min(o.scrollHeight,p);o.style.height=`${Me}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 u=(ae=n==null?void 0:n.sendButton)!=null?ae:{},d=(Lt=u.useIcon)!=null?Lt:!1,f=(xt=u.iconText)!=null?xt:"\u2191",g=u.iconName,v=(Ke=u.stopIconName)!=null?Ke:"square",E=(sn=u.tooltipText)!=null?sn:"Send message",w=(nt=u.stopTooltipText)!=null?nt:"Stop generating",A=(Ye=(he=n==null?void 0:n.copy)==null?void 0:he.sendButtonLabel)!=null?Ye:"Send",I=($t=(Ot=n==null?void 0:n.copy)==null?void 0:Ot.stopButtonLabel)!=null?$t:"Stop",U=(D=u.showTooltip)!=null?D:!1,k=(se=u.size)!=null?se:"40px",L=u.backgroundColor,M=u.textColor,P=h("div","persona-send-button-wrapper"),N=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");N.type="submit",N.setAttribute("data-persona-composer-submit","");let K=null,G=null;if(d){N.style.width=k,N.style.height=k,N.style.minWidth=k,N.style.minHeight=k,N.style.fontSize="18px",N.style.lineHeight="1",N.innerHTML="",M?N.style.color=M:N.style.color="var(--persona-button-primary-fg, #ffffff)";let Me=parseFloat(k)||24,st=(M==null?void 0:M.trim())||"currentColor";g?(K=Ae(g,Me,st,2),K?N.appendChild(K):N.textContent=f):N.textContent=f,G=Ae(v,Me,st,2),L?N.style.backgroundColor=L:N.classList.add("persona-bg-persona-primary")}else N.textContent=A,M?N.style.color=M:N.classList.add("persona-text-white");u.borderWidth&&(N.style.borderWidth=u.borderWidth,N.style.borderStyle="solid"),u.borderColor&&(N.style.borderColor=u.borderColor),u.paddingX?(N.style.paddingLeft=u.paddingX,N.style.paddingRight=u.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),u.paddingY?(N.style.paddingTop=u.paddingY,N.style.paddingBottom=u.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let j=null;U&&E&&(j=h("div","persona-send-button-tooltip"),j.textContent=E,P.appendChild(j)),N.setAttribute("aria-label",E),P.appendChild(N);let ie="send",ve=Me=>{if(Me===ie)return;ie=Me;let st=Me==="stop"?w:E;if(N.setAttribute("aria-label",st),j&&(j.textContent=st),d){if(K&&G){let ze=Me==="stop"?G:K,ln=Me==="stop"?K:G;ln.parentNode===N?N.replaceChild(ze,ln):N.appendChild(ze)}}else N.textContent=Me==="stop"?I:A},ue=(Re=n==null?void 0:n.voiceRecognition)!=null?Re:{},Oe=ue.enabled===!0,fe=null,De=null,Le=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ne=((Ue=ue.provider)==null?void 0:Ue.type)==="runtype";if(Oe&&(Le||Ne)){De=h("div","persona-send-button-wrapper"),fe=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),fe.type="button",fe.setAttribute("data-persona-composer-mic",""),fe.setAttribute("aria-label","Start voice recognition");let Me=(Qe=ue.iconName)!=null?Qe:"mic",st=(Ze=ue.iconSize)!=null?Ze:k,ze=parseFloat(st)||24,ln=(H=ue.backgroundColor)!=null?H:L,cn=(Te=ue.iconColor)!=null?Te:M;fe.style.width=st,fe.style.height=st,fe.style.minWidth=st,fe.style.minHeight=st,fe.style.fontSize="18px",fe.style.lineHeight="1",cn?fe.style.color=cn:fe.style.color="var(--persona-text, #111827)";let dn=Ae(Me,ze,cn||"currentColor",1.5);dn?fe.appendChild(dn):fe.textContent="\u{1F3A4}",ln&&(fe.style.backgroundColor=ln),ue.borderWidth&&(fe.style.borderWidth=ue.borderWidth,fe.style.borderStyle="solid"),ue.borderColor&&(fe.style.borderColor=ue.borderColor),ue.paddingX&&(fe.style.paddingLeft=ue.paddingX,fe.style.paddingRight=ue.paddingX),ue.paddingY&&(fe.style.paddingTop=ue.paddingY,fe.style.paddingBottom=ue.paddingY),De.appendChild(fe);let rt=(Fe=ue.tooltipText)!=null?Fe:"Start voice recognition";if(((ct=ue.showTooltip)!=null?ct:!1)&&rt){let kn=h("div","persona-send-button-tooltip");kn.textContent=rt,De.appendChild(kn)}}let X=(Z=n==null?void 0:n.attachments)!=null?Z:{},ge=X.enabled===!0,Q=null,me=null,pe=null,oe=null;if(ge){oe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),oe.style.display="none",pe=h("input"),pe.type="file",pe.accept=((re=X.allowedTypes)!=null?re:Mr).join(","),pe.multiple=((qe=X.maxFiles)!=null?qe:4)>1,pe.style.display="none",pe.setAttribute("aria-label","Attach files"),me=h("div","persona-send-button-wrapper"),Q=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Q.type="button",Q.setAttribute("aria-label",(dt=X.buttonTooltipText)!=null?dt:"Attach file");let Me=(Nt=X.buttonIconName)!=null?Nt:"paperclip",st=k,ze=parseFloat(st)||40,ln=Math.round(ze*.6);Q.style.width=st,Q.style.height=st,Q.style.minWidth=st,Q.style.minHeight=st,Q.style.fontSize="18px",Q.style.lineHeight="1",Q.style.backgroundColor="transparent",Q.style.color="var(--persona-primary, #111827)",Q.style.border="none",Q.style.borderRadius="6px",Q.style.transition="background-color 0.15s ease",Q.addEventListener("mouseenter",()=>{Q.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Q.addEventListener("mouseleave",()=>{Q.style.backgroundColor="transparent"});let cn=Ae(Me,ln,"currentColor",1.5);cn?Q.appendChild(cn):Q.textContent="\u{1F4CE}",Q.addEventListener("click",rt=>{rt.preventDefault(),pe==null||pe.click()}),me.appendChild(Q);let $n=(an=X.buttonTooltipText)!=null?an:"Attach file",dn=h("div","persona-send-button-tooltip");dn.textContent=$n,me.appendChild(dn)}s.addEventListener("click",Me=>{Me.target!==N&&Me.target!==P&&Me.target!==fe&&Me.target!==De&&Me.target!==Q&&Me.target!==me&&o.focus()}),oe&&(oe.style.gap="8px",s.append(oe)),pe&&s.append(pe),s.append(o);let Ie=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Pe=h("div","persona-flex persona-items-center persona-gap-2");me&&Pe.append(me);let R=h("div","persona-flex persona-items-center persona-gap-1");De&&R.append(De),R.append(P),Ie.append(Pe,R),s.append(Ie);let z=(ht=n==null?void 0:n.statusIndicator)!=null?ht:{},ne=z.align==="left"?"persona-text-left":z.align==="center"?"persona-text-center":"persona-text-right",_=h("div",`persona-mt-2 ${ne} persona-text-xs persona-text-persona-muted`);_.setAttribute("data-persona-composer-status","");let q=(ft=z.visible)!=null?ft:!0;_.style.display=q?"":"none";let le=(it=z.idleText)!=null?it:"Online";if(z.idleLink){let Me=h("a");Me.href=z.idleLink,Me.target="_blank",Me.rel="noopener noreferrer",Me.textContent=le,Me.style.color="inherit",Me.style.textDecoration="none",_.appendChild(Me)}else _.textContent=le;return t.append(r,s,_),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:N,sendButtonWrapper:P,micButton:fe,micButtonWrapper:De,statusText:_,attachmentButton:Q,attachmentButtonWrapper:me,attachmentInput:pe,attachmentPreviewsContainer:oe,actionsRow:Ie,leftActions:Pe,rightActions:R,setSendButtonMode:ve}};var kp=e=>{var c,u,d,f,g,v,E,w,A;let n=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(Yt(e)){let I=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return I.appendChild(U),{wrapper:I,panel:U}}if(!n){let I=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),k=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return I.style.width=k,U.style.width="100%",I.appendChild(U),{wrapper:I,panel:U}}let r=(g=e==null?void 0:e.launcher)!=null?g:{},s=r.position&&ir[r.position]?ir[r.position]:ir["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:Tn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(A=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?A:e==null?void 0:e.launcherWidth,p=i!=null?i:On;return a.style.width=p,a.style.maxWidth=p,o.appendChild(a),{wrapper:o,panel:a}},Lp=(e,n=!0)=>{var w,A,I,U,k,L,M,P,N;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-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 r=(w=e==null?void 0:e.layout)==null?void 0:w.header,s=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,o=r?Vo(e,r,{showClose:n}):kr({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Yt(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(U=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?U:"Hello \u{1F44B}";let c=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");c.textContent=(L=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",i.append(p,c);let u=h("div","persona-flex persona-flex-col persona-gap-3"),d=(M=e==null?void 0:e.layout)==null?void 0:M.contentMaxWidth;d&&(u.style.maxWidth=d,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((P=e==null?void 0:e.copy)==null?void 0:P.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=Jo({config:e}),v=((N=e==null?void 0:e.layout)==null?void 0:N.showFooter)!==!1;s?Eo(t,o,e):(o.header.style.display="none",Eo(t,o,e)),t.append(a);let E=h("div","persona-composer-overlay persona-pointer-events-none");return E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20",v||(g.footer.style.display="none"),t.append(g.footer),t.append(E),{container:t,body:a,messagesWrapper:u,composerOverlay:E,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:p,introSubtitle:c,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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Hm=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Bm=(e,n)=>{if(!e)return null;let t=Hm(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},Dm=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},Nm=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Fm=320,Om=320,$m=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),_m=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,p)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Fm}px`,c.style.maxHeight=`${Om}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 u=!1;s+=1,c.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{u=!0}),Nm(i.image)?(c.src=i.image,r.appendChild(c)):(u=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},To=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},wi=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:To};if(n){let s=n(r);if(s!==null)return s}return To()},jm=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Ip=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Um=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Ci=(e,n,t)=>{var g,v,E,w,A,I;let r=(g=n.showCopy)!=null?g:!0,s=(v=n.showUpvote)!=null?v:!0,o=(E=n.showDownvote)!=null?E:!0;if(!r&&!s&&!o){let U=h("div");return U.style.display="none",U.id=`actions-${e.id}`,U.setAttribute("data-actions-for",e.id),U}let a=(w=n.visibility)!=null?w:"hover",i=(A=n.align)!=null?A:"right",p=(I=n.layout)!=null?I:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[p],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(U,k,L)=>{let M=Ft({icon:U,label:k,size:14,className:"persona-message-action-btn"});return M.setAttribute("data-action",L),M};return r&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},Ko=(e,n,t,r,s,o)=>{var Le,Ne,de,X,ge,Q,me,pe,oe,Ie,Pe,R,z,ne,_,q,le;let a=t!=null?t:{},i=(Le=a.layout)!=null?Le:"bubble",p=a.avatar,c=a.timestamp,u=(Ne=p==null?void 0:p.show)!=null?Ne:!1,d=(de=c==null?void 0:c.show)!=null?de:!1,f=(X=p==null?void 0:p.position)!=null?X:"left",g=(ge=c==null?void 0:c.position)!=null?ge:"below",v=Um(e.role,i),E=h("div",v.join(" "));E.id=`bubble-${e.id}`,E.setAttribute("data-message-id",e.id),E.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(E.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",E.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(E.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",E.style.color="var(--persona-message-assistant-text, var(--persona-text))");let w=$m(e),A=(me=(Q=e.content)==null?void 0:Q.trim())!=null?me:"",U=w.length>0&&A===ha,k=xp((oe=(pe=o==null?void 0:o.widgetConfig)==null?void 0:pe.features)==null?void 0:oe.streamAnimation),L=(R=(Pe=(Ie=o==null?void 0:o.widgetConfig)==null?void 0:Ie.features)==null?void 0:Pe.streamAnimation)==null?void 0:R.plugins,M=e.role==="assistant"&&k.type!=="none"?Ia(k.type,L):null,P=e.role==="assistant"&&((z=M==null?void 0:M.isAnimating)==null?void 0:z.call(M,e))===!0,N=e.role==="assistant"&&M!==null&&(!!e.streaming||P);N&&(M!=null&&M.bubbleClass)&&E.classList.add(M.bubbleClass);let K=document.createElement("div");K.classList.add("persona-message-content"),N&&M&&(M.containerClass&&K.classList.add(M.containerClass),K.style.setProperty("--persona-stream-step",`${k.speed}ms`),K.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let G=N?Sp((ne=e.content)!=null?ne:"",k.buffer,M,e,!!e.streaming):(_=e.content)!=null?_:"",j=n({text:G,message:e,streaming:!!e.streaming,raw:e.rawContent}),ie=j;N&&(M==null?void 0:M.wrap)==="char"?ie=gi(j,"char",e.id,{skipTags:M.skipTags}):N&&(M==null?void 0:M.wrap)==="word"&&(ie=gi(j,"word",e.id,{skipTags:M.skipTags}));let ve=null;if(U?(ve=document.createElement("div"),ve.innerHTML=ie,ve.style.display="none",K.appendChild(ve)):K.innerHTML=ie,N&&(M!=null&&M.useCaret)&&!U&&A){let Ee=Ep(),ee=K.querySelectorAll(".persona-stream-char, .persona-stream-word"),ae=ee[ee.length-1];if(ae!=null&&ae.parentNode)ae.parentNode.insertBefore(Ee,ae.nextSibling);else{let Lt=K.lastElementChild;Lt?Lt.appendChild(Ee):K.appendChild(Ee)}}if(d&&g==="inline"&&e.createdAt){let Ee=Ip(e,c);Ee.classList.add("persona-ml-2","persona-inline"),K.appendChild(Ee)}if(w.length>0){let Ee=_m(w,!U&&!!A,()=>{U&&ve&&(ve.style.display="")});Ee?E.appendChild(Ee):U&&ve&&(ve.style.display="")}if(E.appendChild(K),d&&g==="below"&&e.createdAt){let Ee=Ip(e,c);Ee.classList.add("persona-mt-1"),E.appendChild(Ee)}let ue=e.role==="assistant"?Bm(e.stopReason,(le=(q=o==null?void 0:o.widgetConfig)==null?void 0:q.copy)==null?void 0:le.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Ee=!!(G&&G.trim()),ee=k.placeholder==="skeleton",ae=ee&&k.buffer==="line"&&Ee;if(Ee)ae&&E.appendChild(fi());else if(ee)E.appendChild(fi());else{let Lt=wi("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Lt&&E.appendChild(Lt)}}if(ue&&e.stopReason&&!e.streaming&&(A||(K.style.display="none"),E.appendChild(Dm(e.stopReason,ue))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Ee=Ci(e,r,s);E.appendChild(Ee)}if(!u||e.role==="system")return E;let fe=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),De=jm(p,e.role);return f==="right"||f==="left"&&e.role==="user"?fe.append(E,De):fe.append(De,E),E.classList.remove("persona-max-w-[85%]"),E.classList.add("persona-max-w-[calc(85%-2.5rem)]"),fe},Pp=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ko(e,n,t,r,s,o)};var Go=new Set,qm=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),zm=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
17
- `):""},Wp=(e,n)=>{let t=Go.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=Ae(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")},Ai=(e,n)=>{var Oe,fe,De,Le,Ne,de,X,ge,Q,me,pe;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let s=(fe=(Oe=n==null?void 0:n.features)==null?void 0:Oe.reasoningDisplay)!=null?fe:{},o=s.expandable!==!1,a=o&&Go.has(e.id),i=t.status!=="complete",p=zm(e,(De=s.previewMaxLines)!=null?De: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 u=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Le=n==null?void 0:n.reasoning)!=null?Le:{},v=String((Ne=t.startedAt)!=null?Ne:Date.now()),E=()=>{let oe=h("span","");return oe.setAttribute("data-tool-elapsed",v),oe.textContent=la(t),oe},w=(de=g.renderCollapsedSummary)==null?void 0:de.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:p,isActive:i,config:n!=null?n:{},elapsed:la(t),createElapsedElement:E});typeof w=="string"&&w.trim()?(d.textContent=w,u.appendChild(d)):w instanceof HTMLElement?u.appendChild(w):(d.textContent=f,u.appendChild(d));let A=h("span","persona-text-xs persona-text-persona-primary");A.textContent=qd(t),u.appendChild(A);let I=(X=s.loadingAnimation)!=null?X:"none",U=g.activeTextTemplate,k=g.completeTextTemplate,L=i?U:k,M=w instanceof HTMLElement,P=(oe,Ie,Pe)=>{let R=Pe;for(let z of Ie){let ne=h("span","persona-tool-char");ne.style.setProperty("--char-index",String(R)),ne.textContent=z===" "?"\xA0":z,oe.appendChild(ne),R++}return R},N=(oe,Ie)=>{d.textContent="";let Pe=ca(oe,""),R=0;for(let z of Pe){let ne=z.styles.length>0?(()=>{let _=h("span",z.styles.map(q=>`persona-tool-text-${q}`).join(" "));return d.appendChild(_),_})():d;if(z.isDuration&&i)ne.appendChild(E());else{let _=z.isDuration?la(t):z.text;Ie?R=P(ne,_,R):ne.appendChild(document.createTextNode(_))}}};if(!M&&L)if(A.style.display="none",d.style.display="",i&&I!=="none"){let oe=(ge=g.loadingAnimationDuration)!=null?ge:2e3;d.setAttribute("data-preserve-animation","true"),I==="pulse"?(d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),N(L,!1)):(d.classList.add(`persona-tool-loading-${I}`),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),I==="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)),N(L,!0))}else N(L,!1);else if(!M&&i&&I!=="none"){d.style.display="";let oe=(Q=g.loadingAnimationDuration)!=null?Q:2e3;if(d.setAttribute("data-preserve-animation","true"),I==="pulse")d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`);else{d.classList.add(`persona-tool-loading-${I}`),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),I==="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 Ie=d.textContent||f;d.textContent="",P(d,Ie,0)}t.status==="complete"&&(d.style.display="none")}else M||(t.status==="complete"?d.style.display="none":d.style.display="");let K=null;if(o){K=h("div","persona-flex persona-items-center");let Ie=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Ie?K.appendChild(Ie):K.textContent=a?"Hide":"Show";let Pe=h("div","persona-flex persona-items-center persona-ml-auto");Pe.append(K),c.append(u,Pe)}else c.append(u);let G=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(G.setAttribute("data-persona-collapsed-preview","reasoning"),G.style.display="none",G.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&p){let oe=(pe=(me=n==null?void 0:n.reasoning)==null?void 0:me.renderCollapsedPreview)==null?void 0:pe.call(me,{message:e,reasoning:t,defaultPreview:p,isActive:i,config:n!=null?n:{}});qm(G,oe)||(G.textContent=p),G.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(c,G),r;let j=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let ie=t.chunks.join(""),ve=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ve.textContent=ie||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(ve),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),K){K.innerHTML="";let Ie=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Ie?K.appendChild(Ie):K.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",G.style.display=a?"none":G.textContent||G.childNodes.length?"":"none"})(),r.append(c,G,j),r};var Qo=new Set,Vm=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Jm=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
18
- `);let s=jo(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
19
- `):""},Km=(e,n)=>{var u,d,f,g,v;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,s=(d=r==null?void 0:r.collapsedMode)!=null?d:"tool-call",o=Jm(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?zd(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",p=(g=n==null?void 0:n.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&&p.activeTextTemplate?c=si(t,p.activeTextTemplate,c):!i&&p.completeTextTemplate&&(c=si(t,p.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Rp=(e,n,t)=>{var u;let r=Qo.has(e),s=(u=t==null?void 0:t.toolCall)!=null?u:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let p=o.querySelector(".persona-ml-auto"),c=p==null?void 0:p.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=Ae(r?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Si=(e,n)=>{var ie,ve,ue,Oe,fe,De,Le,Ne,de;let t=e.toolCall,r=(ie=n==null?void 0:n.toolCall)!=null?ie:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(ue=(ve=n==null?void 0:n.features)==null?void 0:ve.toolCallDisplay)!=null?ue:{},a=o.expandable!==!1,i=a&&Qo.has(e.id),{summary:p,previewText:c,isActive:u}=Km(e,n),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"),r.headerBackgroundColor&&(d.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(d.style.paddingLeft=r.headerPaddingX,d.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(d.style.paddingTop=r.headerPaddingY,d.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let v=String((Oe=t.startedAt)!=null?Oe:Date.now()),E=()=>{let X=h("span","");return X.setAttribute("data-tool-elapsed",v),X.textContent=Cs(t),X},w=(De=r.renderCollapsedSummary)==null?void 0:De.call(r,{message:e,toolCall:t,defaultSummary:p,previewText:c,collapsedMode:(fe=o.collapsedMode)!=null?fe:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Cs(t),createElapsedElement:E});typeof w=="string"&&w.trim()?(g.textContent=w,f.appendChild(g)):w instanceof HTMLElement?f.appendChild(w):(g.textContent=p,f.appendChild(g));let A=(Le=o.loadingAnimation)!=null?Le:"none",I=r.activeTextTemplate,U=r.completeTextTemplate,k=u?I:U,L=w instanceof HTMLElement,M=(X,ge,Q)=>{let me=Q;for(let pe of ge){let oe=h("span","persona-tool-char");oe.style.setProperty("--char-index",String(me)),oe.textContent=pe===" "?"\xA0":pe,X.appendChild(oe),me++}return me},P=(X,ge)=>{var oe;g.textContent="";let Q=((oe=t.name)==null?void 0:oe.trim())||"tool",me=ca(X,Q),pe=0;for(let Ie of me){let Pe=Ie.styles.length>0?(()=>{let R=h("span",Ie.styles.map(z=>`persona-tool-text-${z}`).join(" "));return g.appendChild(R),R})():g;if(Ie.isDuration&&u)Pe.appendChild(E());else{let R=Ie.isDuration?Cs(t):Ie.text;ge?pe=M(Pe,R,pe):Pe.appendChild(document.createTextNode(R))}}};if(!L)if(u&&A!=="none"){let X=(Ne=r.loadingAnimationDuration)!=null?Ne:2e3;if(g.setAttribute("data-preserve-animation","true"),A==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${X}ms`),k&&P(k,!1);else if(g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${X}ms`),A==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)P(k,!0);else{let ge=g.textContent||p;g.textContent="",M(g,ge,0)}}else k&&P(k,!1);let N=null;if(a){N=h("div","persona-flex persona-items-center");let X=r.toggleTextColor||r.headerTextColor||"currentColor",ge=Ae(i?"chevron-up":"chevron-down",16,X,2);ge?N.appendChild(ge):N.textContent=i?"Hide":"Show";let Q=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(N),d.append(f,Q)}else d.append(f);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","tool"),K.style.display="none",K.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&c){let X=(de=r.renderCollapsedPreview)==null?void 0:de.call(r,{message:e,toolCall:t,defaultPreview:c,isActive:u,config:n!=null?n:{}});Vm(K,X)||(K.textContent=c),K.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,K),s;let G=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=i?"":"none",r.contentBackgroundColor&&(G.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(G.style.color=r.contentTextColor),r.contentPaddingX&&(G.style.paddingLeft=r.contentPaddingX,G.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(G.style.paddingTop=r.contentPaddingY,G.style.paddingBottom=r.contentPaddingY),t.name){let X=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?X.style.color=r.contentTextColor:r.headerTextColor&&(X.style.color=r.headerTextColor),X.textContent=t.name,G.appendChild(X)}if(t.args!==void 0){let X=h("div","persona-space-y-1"),ge=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ge.style.color=r.labelTextColor),ge.textContent="Arguments";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=jo(t.args),X.append(ge,Q),G.appendChild(X)}if(t.chunks&&t.chunks.length){let X=h("div","persona-space-y-1"),ge=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ge.style.color=r.labelTextColor),ge.textContent="Activity";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=t.chunks.join(""),X.append(ge,Q),G.appendChild(X)}if(t.status==="complete"&&t.result!==void 0){let X=h("div","persona-space-y-1"),ge=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ge.style.color=r.labelTextColor),ge.textContent="Result";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=jo(t.result),X.append(ge,Q),G.appendChild(X)}if(t.status==="complete"&&typeof t.duration=="number"){let X=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(X.style.color=r.contentTextColor),X.textContent=`Duration: ${t.duration}ms`,G.appendChild(X)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let X=r.toggleTextColor||r.headerTextColor||"currentColor",ge=Ae(i?"chevron-up":"chevron-down",16,X,2);ge?N.appendChild(ge):N.textContent=i?"Hide":"Show"}G.style.display=i?"":"none",K.style.display=i?"none":K.textContent||K.childNodes.length?"":"none"})(),s.append(d,K,G),s};var Yr=require("partial-json");var Ti="ask_user_question",Ei=8,Yo="data-persona-ask-sheet-for",Gm="Other",Qm="Other\u2026",Bp="Type your own answer here",Dp="Send",Ym="Next",Xm="Back",Zm="Submit all",eg="Skip",tg=3,Mi="data-ask-current-index",ki="data-ask-question-count",Np="data-ask-answers",Li="data-ask-grouped",Fp="data-ask-layout",ng=e=>e.layout==="pills"?"pills":"rows",rg=e=>e.getAttribute(Fp)==="pills"?"pills":"rows",Hp=!1,Op=e=>e.replace(/["\\]/g,"\\$&"),Lr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ti,Ha=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},Ir=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=(0,Yr.parse)(s,Yr.STR|Yr.OBJ|Yr.ARR);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},Fs=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>Ei&&!Hp&&(Hp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${Ei}.`)),n.slice(0,Ei)},og=e=>{var n;return(n=Fs(e)[0])!=null?n:null},sg=(e,n)=>{var t;return(t=Fs(e)[n])!=null?t:null},$p=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},_p=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},ag=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=h("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}o.appendChild(a);let p=_p(t,r,n);p&&o.appendChild(p)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},ig=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},lg=(e,n,t,r)=>{var u,d,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),p=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(p.length===0&&!t){for(let g=0;g<tg;g++)o.appendChild(ig(r));return o}if(p.forEach((g,v)=>{o.appendChild(ag(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Gm:Qm;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(p.length)),v.setAttribute("data-ask-other-row","true");let E=h("span","persona-ask-row-content"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(u=n.freeTextPlaceholder)!=null?u:Bp,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(d=n.freeTextLabel)!=null?d:g),E.appendChild(w),v.appendChild(E);let A=_p(r,a,p.length);A&&v.appendChild(A),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=n.freeTextLabel)!=null?f:g,o.appendChild(v)}}return o},jp=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:Bp,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Dp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},cg=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:Dp,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},dg=(e,n,t)=>{var c,u,d,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(c=t.backLabel)!=null?c:Xm,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:eg,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===n-1;return i.textContent=p?(d=t.submitAllLabel)!=null?d:Zm:(f=t.nextLabel)!=null?f:Ym,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Mo=e=>{let n=e.getAttribute(Np);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Up=(e,n)=>{e.setAttribute(Np,JSON.stringify(n))},er=e=>{var t;let n=Number((t=e.getAttribute(Mi))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},pg=(e,n)=>{e.setAttribute(Mi,String(Math.max(0,Math.floor(n))))},Xo=e=>{var t;let n=Number((t=e.getAttribute(ki))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},Xr=e=>e.getAttribute(Li)==="true",ug=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let p=t[i];(typeof p=="string"||Array.isArray(p))&&(r[a]=p)}}),r},mg=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},Ba=(e,n)=>{let{payload:t}=Ir(n),r=Fs(t),s=Mo(e),o={},a=new Set;return r.forEach((i,p)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(s,p)&&(o[c]=s[p]))}),o},qp=e=>{let n=Mo(e),t=er(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(p=>s.add(p));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(p=>{var d;let c=(d=p.getAttribute("data-option-label"))!=null?d:"",u=s.has(c);p.setAttribute("aria-pressed",u?"true":"false"),p.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(p=>{var c;return(c=p.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let p=i.closest('[data-ask-free-text-row="true"]');p==null||p.classList.remove("persona-hidden")}else i.value=""},zp=e=>{if(!Xr(e))return;let n=Mo(e),t=er(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ii=(e,n,t)=>{let r=Ha(t),s=rg(e),{payload:o,complete:a}=Ir(n),i=Xr(e),p=er(e),c=Xo(e),u=i?sg(o,p):og(o),d=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${p+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let I=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=I,v.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let E=e.querySelector('[data-ask-pill-list="true"]');if(E){let I=lg(u,r,a,s);E.replaceWith(I)}if(s!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(jp(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&d&&!w?e.appendChild(cg(r)):(!d||i)&&w&&w.remove(),e.setAttribute("data-multi-select",d?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=dg(p,c,r);A?A.replaceWith(I):e.appendChild(I)}else A&&A.remove();qp(e),zp(e)},gg=(e,n,t)=>{let r=Ha(n),s=ng(r),o=e.toolCall.id,a=Fs(t),i=Math.max(1,a.length),p=i>1,c=ug(e,a),u=p?mg(e,i):0,d=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));d.setAttribute(Yo,o),d.setAttribute("data-tool-call-id",o),d.setAttribute("data-message-id",e.id),d.setAttribute(ki,String(i)),d.setAttribute(Mi,String(u)),d.setAttribute(Li,p?"true":"false"),d.setAttribute(Fp,s),Up(d,c),d.setAttribute("role","group"),d.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&d.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),$p(d,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),d.appendChild(f);let w=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),d.appendChild(w),s!=="rows"&&d.appendChild(jp(r,s)),Ii(d,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove("persona-ask-sheet-enter"))}),d},fg=(e,n,t)=>{let{payload:r}=Ir(n),s=Math.max(1,Fs(r).length);s>Xo(e)&&(e.setAttribute(ki,String(s)),s>1&&!Xr(e)&&e.setAttribute(Li,"true")),Ii(e,n,t)},Vp=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=Ha(n);$p(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=Ir(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},Zo=(e,n,t)=>{if(!t||!Lr(e)||Ha(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Yo}]`).forEach(c=>{c.getAttribute(Yo)!==s&&c.remove()});let a=t.querySelector(`[${Yo}="${Op(s)}"]`);if(a){fg(a,e,n);return}let{payload:i}=Ir(e),p=gg(e,n,i);t.appendChild(p)},Zr=(e,n)=>{if(!e)return;let t=n?`[${Yo}="${Op(n)}"]`:`[${Yo}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Pi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),eo=(e,n)=>{let t=Mo(e),r=er(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Up(e,t),qp(e),zp(e)},Da=(e,n,t,r)=>{let s=Xo(e),o=Math.max(0,Math.min(s-1,r));pg(e,o),Ii(e,n,t)};var Wi=(e,n)=>{var E,w,A,I,U,k,L,M,P,N,K,G;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(E=r==null?void 0:r.backgroundColor)!=null?E:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(w=r==null?void 0:r.borderColor)!=null?w:"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 p=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)":(A=r==null?void 0:r.titleColor)!=null?A:"currentColor",u=Ae(p,20,c,2);u&&i.appendChild(u);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(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(I=r==null?void 0:r.title)!=null?I:"Approval Required",f.appendChild(g),!s){let j=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");j.setAttribute("data-approval-status",t.status),t.status==="approved"?(j.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",j.style.color="var(--persona-palette-colors-success-700, #15803d)",j.textContent="Approved"):t.status==="denied"?(j.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",j.style.color="var(--persona-palette-colors-error-700, #b91c1c)",j.textContent="Denied"):t.status==="timeout"&&(j.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",j.style.color="var(--persona-palette-colors-warning-700, #b45309)",j.textContent="Timeout"),f.appendChild(j)}d.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=t.description,d.appendChild(v),t.parameters){let j=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(j.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(j.style.color=r.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=jo(t.parameters),d.appendChild(j)}if(s){let j=h("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let ie=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");ie.type="button",ie.style.backgroundColor=(U=r==null?void 0:r.approveButtonColor)!=null?U:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(k=r==null?void 0:r.approveButtonTextColor)!=null?k:"#ffffff",ie.setAttribute("data-approval-action","approve");let ve=Ae("shield-check",14,(L=r==null?void 0:r.approveButtonTextColor)!=null?L:"#ffffff",2);ve&&(ve.style.marginRight="4px",ie.appendChild(ve));let ue=document.createTextNode((M=r==null?void 0:r.approveLabel)!=null?M:"Approve");ie.appendChild(ue);let Oe=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");Oe.type="button",Oe.style.backgroundColor=(P=r==null?void 0:r.denyButtonColor)!=null?P:"transparent",Oe.style.color=(N=r==null?void 0:r.denyButtonTextColor)!=null?N:"var(--persona-feedback-error, #dc2626)",Oe.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Oe.setAttribute("data-approval-action","deny");let fe=Ae("shield-x",14,(K=r==null?void 0:r.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);fe&&(fe.style.marginRight="4px",Oe.appendChild(fe));let De=document.createTextNode((G=r==null?void 0:r.denyLabel)!=null?G:"Deny");Oe.appendChild(De),j.append(ie,Oe),d.appendChild(j)}return a.append(i,d),o.appendChild(a),o};var Jp=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let u=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'}};r.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))}),u.appendChild(v),n.push(v)}),e.appendChild(u)}}};var Os=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var $s=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function es(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var hg={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)"}},yg={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},bg=["flowName","stepName","reasoningText","text","name","tool","toolName"],xg=100;function vg(e,n){let t={...hg,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return yg}function wg(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Cg(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Ag(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Sg(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Eg(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Tg(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=r,i.appendChild(p),i}}function Ri(e,n,t,r,s,o,a,i){var f;let p=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");es(c,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let g=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>d(),isExpanded:p,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var ie,ve;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 E=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=Ae(p?"chevron-down":"chevron-right","14px","currentColor",2);w&&E.appendChild(w);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(ie=r.timestampFormat)!=null?ie:"relative";A.textContent=I==="relative"?wg(e.timestamp,t):Cg(e.timestamp);let U=null;r.showSequenceNumbers!==!1&&(U=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),U.textContent=String(n+1));let k=vg(e.type,r.badgeColors),L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=k.bg,L.style.color=k.text,L.style.borderColor=k.text+"50",L.textContent=e.type;let M=(ve=r.descriptionFields)!=null?ve:bg,P=Ag(e.payload,M),N=null;P&&(N=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=P);let K=h("div","persona-flex-1 persona-min-w-0"),G=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),j=Ae("clipboard","12px","currentColor",1.5);return j&&G.appendChild(j),G.addEventListener("click",async ue=>{ue.stopPropagation(),await Sg(Eg(e)),G.innerHTML="";let Oe=Ae("check","12px","currentColor",1.5);Oe&&G.appendChild(Oe),setTimeout(()=>{G.innerHTML="";let fe=Ae("clipboard","12px","currentColor",1.5);fe&&G.appendChild(fe)},1500)}),v.appendChild(E),v.appendChild(A),U&&v.appendChild(U),v.appendChild(L),N&&v.appendChild(N),v.appendChild(K),v.appendChild(G),g.appendChild(v),p&&g.appendChild(Tg(e,a,i)),g}}function Kp(e){var g,v,E,w,A;let{buffer:n,getFullHistory:t,onClose:r,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,p=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(E=a==null?void 0:a.label)!=null?E:"",u=(A=(w=s==null?void 0:s.features)==null?void 0:w.eventStream)!=null?A:{},d=o.find(I=>I.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let I=d.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(I)return{element:I,update:()=>{},destroy:()=>{}}}return f();function f(){let I=u.classNames,U=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");es(U,I==null?void 0:I.panel);let k=[],L="",M="",P=null,N=[],K={},G=0,j=Ma(),ie=0,ve=0,ue=!1,Oe=null,fe=!1,De=0,Le=new Set,Ne=new Map,de="",X="",ge=null,Q,me,pe,oe,Ie;function Pe(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),re=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");es(re,I==null?void 0:I.headerBar);let qe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");qe.textContent="Events",Q=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"),Q.textContent="0";let dt=h("div","persona-flex-1");me=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 Nt=h("option","");Nt.value="",Nt.textContent="All events",me.appendChild(Nt),pe=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"),pe.type="button",pe.title="Copy All";let ht=Ae("clipboard-copy","12px","currentColor",1.5);ht&&pe.appendChild(ht);let ft=h("span","persona-text-xs");ft.textContent="Copy All",pe.appendChild(ft),re.appendChild(qe),re.appendChild(Q),re.appendChild(dt),re.appendChild(me),re.appendChild(pe);let it=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");es(it,I==null?void 0:I.searchBar);let Me=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),st=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");Me&&st.appendChild(Me),oe=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"),es(oe,I==null?void 0:I.searchInput),oe.type="text",oe.placeholder="Search event payloads...",Ie=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"),Ie.type="button",Ie.style.display="none";let ze=Ae("x","12px","currentColor",2);return ze&&Ie.appendChild(ze),it.appendChild(st),it.appendChild(oe),it.appendChild(Ie),Z.appendChild(re),Z.appendChild(it),Z}let R,z=o.find(Z=>Z.renderEventStreamToolbar);if(z!=null&&z.renderEventStreamToolbar&&s){let Z=z.renderEventStreamToolbar({config:s,defaultRenderer:()=>Pe(),eventCount:n.getSize(),filteredCount:0,onFilterChange:re=>{L=re,sn(),Ye()},onSearchChange:re=>{M=re,sn(),Ye()}});R=Z!=null?Z:Pe()}else R=Pe();let ne=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");ne.style.display="none";let _=h("div","persona-flex-1 persona-min-h-0 persona-relative"),q=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let le=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");es(le,I==null?void 0:I.scrollIndicator),le.style.display="none",le.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Ee=Ae(p,"14px","currentColor",2);Ee&&le.appendChild(Ee);let ee=h("span","");ee.textContent=c,le.appendChild(ee);let ae=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",_.appendChild(q),_.appendChild(ae),_.appendChild(le),U.setAttribute("tabindex","0"),U.appendChild(R),U.appendChild(ne),U.appendChild(_);function Lt(){let Z=n.getAll(),re={};for(let ft of Z)re[ft.type]=(re[ft.type]||0)+1;let qe=Object.keys(re).sort(),dt=qe.length!==N.length||!qe.every((ft,it)=>ft===N[it]),Nt=!dt&&qe.some(ft=>re[ft]!==K[ft]),an=Z.length!==Object.values(K).reduce((ft,it)=>ft+it,0);if(!dt&&!Nt&&!an||(N=qe,K=re,!me))return;let ht=me.value;if(me.options[0].textContent="All events",dt){for(;me.options.length>1;)me.remove(1);for(let ft of qe){let it=h("option","");it.value=ft,it.textContent=`${ft} (${re[ft]||0})`,me.appendChild(it)}ht&&qe.includes(ht)?me.value=ht:ht&&(me.value="",L="")}else for(let ft=1;ft<me.options.length;ft++){let it=me.options[ft];it.textContent=`${it.value} (${re[it.value]||0})`}}function xt(){let Z=n.getAll();if(L&&(Z=Z.filter(re=>re.type===L)),M){let re=M.toLowerCase();Z=Z.filter(qe=>qe.type.toLowerCase().includes(re)||qe.payload.toLowerCase().includes(re))}return Z}function Ke(){return L!==""||M!==""}function sn(){G=0,ie=0,j.resume(),le.style.display="none"}function nt(Z){Le.has(Z)?Le.delete(Z):Le.add(Z),ge=Z;let re=q.scrollTop,qe=j.isFollowing();fe=!0,j.pause(),Ye(),q.scrollTop=re,qe&&j.resume(),fe=!1}function he(){return Ps(q,50)}function Ye(){ve=Date.now(),ue=!1,Lt();let Z=n.getEvictedCount();Z>0?(ne.textContent=`${Z.toLocaleString()} older events truncated`,ne.style.display=""):ne.style.display="none",k=xt();let re=k.length,qe=n.getSize()>0;Q&&(Q.textContent=String(n.getSize())),re===0&&qe&&Ke()?(ae.textContent=M?`No events matching '${M}'`:"No events matching filter",ae.style.display="",q.style.display="none"):(ae.style.display="none",q.style.display=""),pe&&(pe.title=Ke()?`Copy Filtered (${re})`:"Copy All"),i&&!j.isFollowing()&&re>G&&(ie+=re-G,ee.textContent=c?`${c}${ie>0?` (${ie})`:""}`:"",le.style.display=""),G=re;let dt=n.getAll(),Nt=dt.length>0?dt[0].timestamp:0,an=new Set(k.map(it=>it.id));for(let it of Le)an.has(it)||Le.delete(it);let ht=L!==de||M!==X,ft=Ne.size===0&&k.length>0;if(ht||ft||k.length===0){q.innerHTML="",Ne.clear();let it=document.createDocumentFragment();for(let Me=0;Me<k.length;Me++){let st=Ri(k[Me],Me,Nt,u,Le,nt,o,s);Ne.set(k[Me].id,st),it.appendChild(st)}q.appendChild(it),de=L,X=M,ge=null}else{if(ge!==null){let Me=Ne.get(ge);if(Me&&Me.parentNode===q){let st=k.findIndex(ze=>ze.id===ge);if(st>=0){let ze=Ri(k[st],st,Nt,u,Le,nt,o,s);q.insertBefore(ze,Me),Me.remove(),Ne.set(ge,ze)}}ge=null}let it=new Set(k.map(Me=>Me.id));for(let[Me,st]of Ne)it.has(Me)||(st.remove(),Ne.delete(Me));for(let Me=0;Me<k.length;Me++){let st=k[Me];if(!Ne.has(st.id)){let ze=Ri(st,Me,Nt,u,Le,nt,o,s);Ne.set(st.id,ze),q.appendChild(ze)}}}j.isFollowing()&&(q.scrollTop=q.scrollHeight)}function Ot(){if(Date.now()-ve>=xg){Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),Ye();return}ue||(ue=!0,Oe=requestAnimationFrame(()=>{Oe=null,Ye()}))}let $t=(Z,re)=>{if(!pe)return;pe.innerHTML="";let qe=Ae(Z,"12px","currentColor",1.5);qe&&pe.appendChild(qe);let dt=h("span","persona-text-xs");dt.textContent="Copy All",pe.appendChild(dt),setTimeout(()=>{pe.innerHTML="";let Nt=Ae("clipboard-copy","12px","currentColor",1.5);Nt&&pe.appendChild(Nt);let an=h("span","persona-text-xs");an.textContent="Copy All",pe.appendChild(an),pe.disabled=!1},re)},D=async()=>{if(pe){pe.disabled=!0;try{let Z;Ke()?Z=k:t?(Z=await t(),Z.length===0&&(Z=n.getAll())):Z=n.getAll();let re=Z.map(qe=>{try{return JSON.parse(qe.payload)}catch{return qe.payload}});await navigator.clipboard.writeText(JSON.stringify(re,null,2)),$t("check",1500)}catch{$t("x",1500)}}},se=()=>{me&&(L=me.value,sn(),Ye())},Re=()=>{!oe||!Ie||(Ie.style.display=oe.value?"":"none",P&&clearTimeout(P),P=setTimeout(()=>{M=oe.value,sn(),Ye()},150))},Ue=()=>{!oe||!Ie||(oe.value="",M="",Ie.style.display="none",P&&clearTimeout(P),sn(),Ye())},Qe=()=>{if(fe)return;let Z=q.scrollTop,{action:re,nextLastScrollTop:qe}=ka({following:j.isFollowing(),currentScrollTop:Z,lastScrollTop:De,nearBottom:he(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});De=qe,re==="resume"?(j.resume(),ie=0,le.style.display="none"):re==="pause"&&(j.pause(),i&&(ee.textContent=c,le.style.display=""))},Ze=Z=>{let re=La({following:j.isFollowing(),deltaY:Z.deltaY,nearBottom:he(),resumeWhenNearBottom:!0});re==="pause"?(j.pause(),i&&(ee.textContent=c,le.style.display="")):re==="resume"&&(j.resume(),ie=0,le.style.display="none")},H=()=>{i&&(q.scrollTop=q.scrollHeight,j.resume(),ie=0,le.style.display="none")},Te=Z=>{let re=Z.target;if(!re||re.closest("button"))return;let qe=re.closest("[data-event-id]");if(!qe)return;let dt=qe.getAttribute("data-event-id");dt&&nt(dt)},Fe=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),oe==null||oe.focus(),oe==null||oe.select();return}Z.key==="Escape"&&(oe&&document.activeElement===oe?(Ue(),oe.blur(),U.focus()):r&&r())};pe&&pe.addEventListener("click",D),me&&me.addEventListener("change",se),oe&&oe.addEventListener("input",Re),Ie&&Ie.addEventListener("click",Ue),q.addEventListener("scroll",Qe),q.addEventListener("wheel",Ze,{passive:!0}),q.addEventListener("click",Te),le.addEventListener("click",H),U.addEventListener("keydown",Fe);function ct(){P&&clearTimeout(P),Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),ue=!1,Ne.clear(),pe&&pe.removeEventListener("click",D),me&&me.removeEventListener("change",se),oe&&oe.removeEventListener("input",Re),Ie&&Ie.removeEventListener("click",Ue),q.removeEventListener("scroll",Qe),q.removeEventListener("wheel",Ze),q.removeEventListener("click",Te),le.removeEventListener("click",H),U.removeEventListener("keydown",Fe)}return{element:U,update:Ot,destroy:ct}}}function Gp(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let p=document.createElement("div");p.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-muted, #9ca3af)",p.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 u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let 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(u,d),i.append(p,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",r),i.append(f)}return i}var Qp=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",p=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:p},config:n.config,defaultRenderer:()=>Gp(e,n)});if(u)return u}return Gp(e,n)};var Hi=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},Pr=new Hi;Pr.register("PersonaArtifactCard",Qp);function Mg(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function Yp(e,n){var pe,oe,Ie,Pe;let t=(oe=(pe=e.features)==null?void 0:pe.artifacts)==null?void 0:oe.layout,s=((Ie=t==null?void 0:t.toolbarPreset)!=null?Ie:"default")==="document",o=(Pe=t==null?void 0:t.panePadding)==null?void 0:Pe.trim(),a=e.markdown?bo(e.markdown):null,i=_o(e.sanitize),p=R=>{let z=a?a(R):$o(R);return i?i(z):z},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,u=()=>{c==null||c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var R;u(),(R=n.onDismiss)==null||R.call(n)});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 R;u(),(R=n.onDismiss)==null||R.call(n)});let E="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),A=s?Ft({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Ft({icon:"eye",label:"Rendered view"}),I=s?Ft({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Ft({icon:"code-2",label:"Source"}),U=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),k=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,M=t==null?void 0:t.documentToolbarCopyMenuItems,P=!!(L&&M&&M.length>0),N=null,K,G=null,j=null;if(s&&(k||L)&&!P){if(K=k?Ds({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let R=Ae("chevron-down",14,"currentColor",2);R&&K.appendChild(R)}}else s&&P?(N=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),K=k?Ds({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G=Ft({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),N.append(K,G)):s?K=Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):K=Ft({icon:"copy",label:"Copy"});let ie=s?Ft({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ft({icon:"refresh-cw",label:"Refresh"}),ve=s?Ft({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Ft({icon:"x",label:"Close"}),ue=()=>{var q,le,Ee;let R=(q=de.find(ee=>ee.id===X))!=null?q:de[de.length-1],z=(le=R==null?void 0:R.id)!=null?le:null,ne=(R==null?void 0:R.artifactType)==="markdown"&&(Ee=R.markdown)!=null?Ee:"",_=R?JSON.stringify({component:R.component,props:R.props},null,2):"";return{markdown:ne,jsonPayload:_,id:z}},Oe=async()=>{var q;let{markdown:R,jsonPayload:z}=ue(),ne=(q=de.find(le=>le.id===X))!=null?q:de[de.length-1],_=(ne==null?void 0:ne.artifactType)==="markdown"?R:ne?z:"";try{await navigator.clipboard.writeText(_)}catch{}};if(K.addEventListener("click",async()=>{let R=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(R&&P){let{markdown:z,jsonPayload:ne,id:_}=ue();try{await R({actionId:"primary",artifactId:_,markdown:z,jsonPayload:ne})}catch{}return}await Oe()}),G&&(M!=null&&M.length)){let R=()=>{var ne;return(ne=d.closest("[data-persona-root]"))!=null?ne:document.body},z=()=>{j=Qr({items:M.map(ne=>({id:ne.id,label:ne.label})),onSelect:async ne=>{let{markdown:_,jsonPayload:q,id:le}=ue(),Ee=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ee?await Ee({actionId:ne,artifactId:le,markdown:_,jsonPayload:q}):ne==="markdown"||ne==="md"?await navigator.clipboard.writeText(_):ne==="json"||ne==="source"?await navigator.clipboard.writeText(q):await navigator.clipboard.writeText(_||q)}catch{}},anchor:N!=null?N:G,position:"bottom-right",portal:R()})};d.isConnected?z():requestAnimationFrame(z),G.addEventListener("click",ne=>{ne.stopPropagation(),j==null||j.toggle()})}ie.addEventListener("click",async()=>{var R;try{await((R=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:R.call(t))}catch{}Q()}),ve.addEventListener("click",()=>{var R;u(),(R=n.onDismiss)==null||R.call(n)});let fe=()=>{s&&(A.setAttribute("aria-pressed",E==="rendered"?"true":"false"),I.setAttribute("aria-pressed",E==="source"?"true":"false"))};A.addEventListener("click",()=>{E="rendered",fe(),Q()}),I.addEventListener("click",()=>{E="source",fe(),Q()});let De=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(),w.append(A,I),N?U.append(N,ie,ve):U.append(K,ie,ve),f.append(w,De,U),fe()):(f.appendChild(g),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Le=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"),Ne=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Le.style.paddingLeft=o,Le.style.paddingRight=o,Ne.style.padding=o),d.appendChild(f),d.appendChild(Le),d.appendChild(Ne);let de=[],X=null,ge=!1,Q=()=>{var _,q,le,Ee;let R=s&&de.length<=1;Le.classList.toggle("persona-hidden",R),Le.replaceChildren();for(let ee of de){let ae=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");ae.type="button",ae.textContent=ee.title||ee.id.slice(0,8),ee.id===X&&ae.classList.add("persona-bg-persona-container","persona-border-persona-border"),ae.addEventListener("click",()=>n.onSelect(ee.id)),Le.appendChild(ae)}Ne.replaceChildren();let z=X&&de.find(ee=>ee.id===X)||de[de.length-1];if(!z)return;if(s){let ee=z.artifactType==="markdown"?"MD":(_=z.component)!=null?_:"Component",Lt=(z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";De.textContent=`${Lt} \xB7 ${ee}`}else g.textContent="Artifacts";if(z.artifactType==="markdown"){if(s&&E==="source"){let ae=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ae.textContent=(q=z.markdown)!=null?q:"",Ne.appendChild(ae);return}let ee=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ee.innerHTML=p((le=z.markdown)!=null?le:""),Ne.appendChild(ee);return}let ne=z.component?Pr.get(z.component):void 0;if(ne){let ae={message:{id:z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Lt=ne((Ee=z.props)!=null?Ee:{},ae);if(Lt){Ne.appendChild(Lt);return}}catch{}}Ne.appendChild(Mg(z))},me=()=>{var z;let R=de.length>0;if(d.classList.toggle("persona-hidden",!R),c){let ne=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,q=((z=ne==null?void 0:ne.classList.contains("persona-artifact-narrow-host"))!=null?z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;R&&q&&ge?(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(R){var z,ne,_;de=R.artifacts,X=(_=(ne=R.selectedId)!=null?ne:(z=R.artifacts[R.artifacts.length-1])==null?void 0:z.id)!=null?_:null,de.length>0&&(ge=!0),Q(),me()},setMobileOpen(R){ge=R,!R&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):me()}}}function tr(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Xp(e,n){var o,a,i,p;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"),!tr(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(p=t==null?void 0:t.paneBorderLeft)==null?void 0:p.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function kg(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 Na(e,n){var p,c,u,d,f,g,v,E,w,A;if(!tr(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),kg(e),Xp(e,n);return}let t=(c=(p=n.features)==null?void 0:p.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(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 r=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(E=t==null?void 0:t.documentToolbarIconColor)==null?void 0:E.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(w=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(A=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:A.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Xp(e,n)}var Zp=["panel","seamless"];function Fa(e,n){var i,p,c,u,d,f;for(let g of Zp)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"),!tr(n))return;let t=(p=(i=n.features)==null?void 0:i.artifacts)==null?void 0:p.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Zp.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(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 eu(e,n){var t,r,s;return!n||!tr(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Lg(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function Ig(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function Pg(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Wg(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function tu(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function nu(e,n,t,r,s,o){let a=Lg(s,200),i=Wg(n,t,r,200);i=Math.max(a,i);let p=Ig(o);return p!==null&&(i=Math.min(i,p)),Pg(e,a,i)}var ru={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"}},Bi=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,E,w;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(E=ru[a])!=null?E:ru.init;o.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,p.appendChild(c),i.description){let A=h("p","persona-text-sm persona-text-persona-muted");A.textContent=i.description,p.appendChild(A)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(A=>{var M,P;let I=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${n.id}-${a}-${A.name}`;let U=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");U.textContent=A.label,I.appendChild(U);let k=(M=A.type)!=null?M:"text",L;k==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=k),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${n.id}-${a}-${A.name}`,L.name=A.name,L.placeholder=(P=A.placeholder)!=null?P:"",A.required&&(L.required=!0),I.appendChild(L),u.appendChild(I)});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=(w=i.submitLabel)!=null?w:"Submit",d.appendChild(f),d.appendChild(g),u.appendChild(d),o.replaceChildren(p,u),u.addEventListener("submit",async A=>{var L,M;A.preventDefault();let I=(L=t.formEndpoint)!=null?L:"/form",U=new FormData(u),k={};U.forEach((P,N)=>{k[N]=P}),k.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let P=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let N=await P.json();f.textContent=(M=N.message)!=null?M:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(P){f.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Di=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,p;return((i=a.priority)!=null?i:0)-((p=o.priority)!=null?p:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},_s=new Di;var ou=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var Rg=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Hg=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},js=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Rg(e),t=Hg(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Ni=e=>typeof e=="string"?e:e==null?"":String(e),ko={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ni(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Ni(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Ni(t.text)}}},su=e=>Array.isArray(e)?e.map(n=>String(n)):[],Us=e=>{let n=new Set(su(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(su(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let p={action:i,message:o.message};e.emit("action:detected",p);for(let c of e.handlers)if(c)try{let u=()=>{e.emit("action:resubmit",p)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});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(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var Bg=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Dg=e=>e.map(n=>({...n,streaming:!1})),Ng=e=>e.map(n=>({...n,status:"complete"})),Oa=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?Bg(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?Dg(t.messages):void 0,artifacts:t.artifacts?Ng(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var ts=require("partial-json");function Fg(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Og(e,n){if(!Fg(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function $a(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=(0,ts.parse)(t,ts.STR|ts.OBJ),o=Og(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function au(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _a(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=Pr.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function iu(){let e=$a();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ja(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Ua(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var $g=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qa(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:c=$g}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let 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=r,g.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,g.appendChild(E),f.appendChild(g);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let M=1;M<=5;M++){let P=document.createElement("button");P.type="button",P.className="persona-feedback-rating-btn persona-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${M} star${M>1?"s":""}: ${c[M-1]}`),P.title=c[M-1],P.dataset.rating=String(M),P.innerHTML=`
16
+ `,t.addEventListener("click",n);let r=o=>{var N,R,T,L,$,q,_,B,O,G,re,Ee,Re,Ue;let a=(N=o.launcher)!=null?N:{},i=nn(o),d=t.querySelector("[data-role='launcher-title']");if(d){let he=(R=a.title)!=null?R:"Chat Assistant";d.textContent=he,d.setAttribute("title",he)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let he=(T=a.subtitle)!=null?T:"Get answers fast";l.textContent=he,l.setAttribute("title",he)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let he=(L=a.agentIconSize)!=null?L:"40px";if(p.style.height=he,p.style.width=he,p.innerHTML="",a.agentIconName){let ue=parseFloat(he)||24,ke=ge(a.agentIconName,ue*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(p.appendChild(ke),p.style.display=""):(p.textContent=($=a.agentIconText)!=null?$:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(q=a.agentIconText)!=null?q:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(_=a.agentIconSize)!=null?_:"40px";f.style.height=he,f.style.width=he,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 he=(B=a.callToActionIconSize)!=null?B:"32px";g.style.height=he,g.style.width=he,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 ue=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,ue=(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(he)||24,je=Math.max(ke-ue,8),te=ge(a.callToActionIconName,je,"currentColor",2);te?g.appendChild(te):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(G=a.callToActionIconText)!=null?G:"\u2197"}let w=a.position&&dr[a.position]?dr[a.position]:dr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="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?M:`${x} ${w}`,i||(t.style.zIndex=String((re=a.zIndex)!=null?re:yn));let A="1px solid var(--persona-border, #e5e7eb)",P="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=(Ee=a.border)!=null?Ee:A,t.style.boxShadow=(Re=a.shadow)!=null?Re:P,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ue=a.collapsedMaxWidth)!=null?Ue:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var fg="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Za=(e,n={})=>{var x,M,A,P,N,R;let{showClose:t=!0,wrapperClassName:r=fg,buttonSize:s,iconSize:o="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(M=s!=null?s:a.closeButtonSize)!=null?M:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(A=a.closeButtonTooltipText)!=null?A:"Close chat",p=(P=a.closeButtonShowTooltip)!=null?P:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(N=a.closeButtonIconName)!=null?N:"x",g=(R=a.closeButtonIconText)!=null?R:"\xD7";l.style.color=a.closeButtonColor||En.actionIconColor;let w=ge(f,o,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=g,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let T=a.closeButtonBorderWidth||"0px",L=a.closeButtonBorderColor||"transparent";l.style.border=`${T} solid ${L}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let T=null,L=()=>{if(T)return;let q=l.ownerDocument,_=q.body;if(!_)return;T=xr(q,"div","persona-clear-chat-tooltip"),T.textContent=u;let B=xr(q,"div");B.className="persona-clear-chat-tooltip-arrow",T.appendChild(B);let O=l.getBoundingClientRect();T.style.position="fixed",T.style.zIndex=String(oo),T.style.left=`${O.left+O.width/2}px`,T.style.top=`${O.top-8}px`,T.style.transform="translate(-50%, -100%)",_.appendChild(T)},$=()=>{T&&T.parentNode&&(T.parentNode.removeChild(T),T=null)};d.addEventListener("mouseenter",L),d.addEventListener("mouseleave",$),l.addEventListener("focus",L),l.addEventListener("blur",$),d._cleanupTooltip=()=>{$(),d.removeEventListener("mouseenter",L),d.removeEventListener("mouseleave",$),l.removeEventListener("focus",L),l.removeEventListener("blur",$)}}return{button:l,wrapper:d}},hg="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ei=(e,n={})=>{var T,L,$,q,_,B,O,G,re,Ee,Re,Ue,he;let{wrapperClassName:t=hg,buttonSize:r,iconSize:s="20px"}=n,a=(L=((T=e==null?void 0:e.launcher)!=null?T:{}).clearChat)!=null?L:{},i=($=r!=null?r:a.size)!=null?$:"32px",d=(q=a.iconName)!=null?q:"refresh-cw",l=(_=a.iconColor)!=null?_:"",u=(B=a.backgroundColor)!=null?B:"",p=(O=a.borderWidth)!=null?O:"",f=(G=a.borderColor)!=null?G:"",g=(re=a.borderRadius)!=null?re:"",w=(Ee=a.paddingX)!=null?Ee:"",x=(Re=a.paddingY)!=null?Re:"",M=(Ue=a.tooltipText)!=null?Ue:"Clear chat",A=(he=a.showTooltip)!=null?he:!0,P=h("div",t),N=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");N.style.height=i,N.style.width=i,N.type="button",N.setAttribute("aria-label",M),N.style.color=l||En.actionIconColor;let R=ge(d,s,"currentColor",1);if(R&&(R.style.display="block",N.appendChild(R)),u&&(N.style.backgroundColor=u,N.classList.remove("hover:persona-bg-gray-100")),p||f){let ue=p||"0px",ke=f||"transparent";N.style.border=`${ue} solid ${ke}`,N.classList.remove("persona-border-none")}if(g&&(N.style.borderRadius=g,N.classList.remove("persona-rounded-full")),w&&(N.style.paddingLeft=w,N.style.paddingRight=w),x&&(N.style.paddingTop=x,N.style.paddingBottom=x),P.appendChild(N),A&&M){let ue=null,ke=()=>{if(ue)return;let te=N.ownerDocument,ve=te.body;if(!ve)return;ue=xr(te,"div","persona-clear-chat-tooltip"),ue.textContent=M;let X=xr(te,"div");X.className="persona-clear-chat-tooltip-arrow",ue.appendChild(X);let oe=N.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(oo),ue.style.left=`${oe.left+oe.width/2}px`,ue.style.top=`${oe.top-8}px`,ue.style.transform="translate(-50%, -100%)",ve.appendChild(ue)},je=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};P.addEventListener("mouseenter",ke),P.addEventListener("mouseleave",je),N.addEventListener("focus",ke),N.addEventListener("blur",je),P._cleanupTooltip=()=>{je(),P.removeEventListener("mouseenter",ke),P.removeEventListener("mouseleave",je),N.removeEventListener("focus",ke),N.removeEventListener("blur",je)}}return{button:N,wrapper:P}};var En={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Nr=e=>{var T,L,$,q,_,B,O,G,re,Ee,Re,Ue,he,ue,ke,je;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(T=n==null?void 0:n.launcher)!=null?T:{},o=(L=s.headerIconSize)!=null?L:"48px",a=($=s.closeButtonPlacement)!=null?$:"inline",i=(q=s.headerIconHidden)!=null?q:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let te=parseFloat(o)||24,ve=ge(d,te*.6,"currentColor",1);ve?l.replaceChildren(ve):l.textContent=(B=(_=n==null?void 0:n.launcher)==null?void 0:_.agentIconText)!=null?B:"\u{1F4AC}"}else if((O=n==null?void 0:n.launcher)!=null&&O.iconUrl){let te=h("img");te.src=n.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=o,te.style.width=o,l.replaceChildren(te)}else l.textContent=(re=(G=n==null?void 0:n.launcher)==null?void 0:G.agentIconText)!=null?re:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=En.titleColor,p.textContent=(Re=(Ee=n==null?void 0:n.launcher)==null?void 0:Ee.title)!=null?Re:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=En.subtitleColor,f.textContent=(he=(Ue=n==null?void 0:n.launcher)==null?void 0:Ue.subtitle)!=null?he:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let g=(ue=s.clearChat)!=null?ue:{},w=(ke=g.enabled)!=null?ke:!0,x=(je=g.placement)!=null?je:"inline",M=null,A=null;if(w){let ve=ei(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=ve.button,A=ve.wrapper,x==="top-right"&&(A.style.right="48px"),x==="inline"&&r.appendChild(A)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:N,wrapper:R}=Za(n,{showClose:t,wrapperClassName:P});return a!=="top-right"&&r.appendChild(R),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:N,closeButtonWrapper:R,clearChatButton:M,clearChatButtonWrapper:A}},Do=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function io(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(oo)):(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 n){if(g.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",g.id),g.destructive&&w.setAttribute("data-destructive",""),g.icon){let M=ge(g.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let x=document.createElement("span");x.textContent=g.label,w.appendChild(x),w.addEventListener("click",M=>{M.stopPropagation(),u(),t(g.id)}),a.appendChild(w)}let i=null;function d(){if(!o)return;let g=r.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 l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=w=>{!a.contains(w.target)&&!r.contains(w.target)&&u()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function Ot(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=ge(n,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ks(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=ge(n,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))u.setAttribute(f,g);return u}function Gs(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=Ot({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function ti(e){var g,w;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let u=h("span","persona-combo-btn-label");u.textContent=n,l.appendChild(u);let p=ge(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",l.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,M;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=io({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var zi=e=>{var r;let n=Nr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function yg(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=ge(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=io({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Vi=e=>{var P,N,R,T,L,$,q,_,B;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(P=n==null?void 0:n.launcher)!=null?P:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=ti({label:(N=a.title)!=null?N:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=En.titleColor,u=(R=l.querySelector(".persona-combo-btn-label"))!=null?R:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=En.titleColor,u.textContent=(T=a.title)!=null?T:"Chat Assistant",l.appendChild(u),yg(l,s==null?void 0:s.trailingActions,(L=s==null?void 0:s.onAction)!=null?L:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let G=s.onTitleClick;l.addEventListener("click",re=>{re.target.closest("button")||G()}),l.addEventListener("keydown",re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),G())})}let O=s==null?void 0:s.titleRowHover;O&&(l.style.borderRadius=($=O.borderRadius)!=null?$:"10px",l.style.padding=(q=O.padding)!=null?q:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var G,re;l.style.backgroundColor=(G=O.background)!=null?G:"",l.style.borderColor=(re=O.border)!=null?re:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(_=a.closeButtonSize)!=null?_:"32px",f=h("div",""),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||En.actionIconColor;let w=(B=a.closeButtonIconName)!=null?B:"x",x=ge(w,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let M=h("div");M.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:A,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ni={default:zi,minimal:Vi},Ji=e=>{var n;return(n=ni[e])!=null?n:ni.default},rs=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),g=h("button");g.style.display="none";let w=h("div");return w.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:g,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Ji(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var ri=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},oi=e=>{var T,L,$,q,_,B,O,G,re,Ee,Re,Ue;let n=(T=e==null?void 0:e.sendButton)!=null?T:{},t=(L=n.useIcon)!=null?L:!1,r=($=n.iconText)!=null?$:"\u2191",s=n.iconName,o=(q=n.stopIconName)!=null?q:"square",a=(_=n.tooltipText)!=null?_:"Send message",i=(B=n.stopTooltipText)!=null?B:"Stop generating",d=(G=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?G:"Send",l=(Ee=(re=e==null?void 0:e.copy)==null?void 0:re.stopButtonLabel)!=null?Ee:"Stop",u=(Re=n.showTooltip)!=null?Re:!1,p=(Ue=n.size)!=null?Ue:"40px",f=n.backgroundColor,g=n.textColor,w=h("div","persona-send-button-wrapper"),x=h("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let M=null,A=null;if(t){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",g?x.style.color=g:x.style.color="var(--persona-button-primary-fg, #ffffff)";let he=parseFloat(p)||24,ue=(g==null?void 0:g.trim())||"currentColor";s?(M=ge(s,he,ue,2),M?x.appendChild(M):x.textContent=r):x.textContent=r,A=ge(o,he,ue,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,g?x.style.color=g:x.classList.add("persona-text-white");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let P=null;u&&a&&(P=h("div","persona-send-button-tooltip"),P.textContent=a,w.appendChild(P)),x.setAttribute("aria-label",a),w.appendChild(x);let N="send";return{button:x,wrapper:w,setMode:he=>{if(he===N)return;N=he;let ue=he==="stop"?i:a;if(x.setAttribute("aria-label",ue),P&&(P.textContent=ue),t){if(M&&A){let ke=he==="stop"?A:M,je=he==="stop"?M:A;je.parentNode===x?x.replaceChild(ke,je):x.appendChild(ke)}}else x.textContent=he==="stop"?l:d}}},si=e=>{var P,N,R,T,L,$,q,_,B,O,G,re;let n=(P=e==null?void 0:e.voiceRecognition)!=null?P:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((N=n.provider)==null?void 0:N.type)==="runtype";if(!(r||s))return null;let a=(T=(R=e==null?void 0:e.sendButton)==null?void 0:R.size)!=null?T:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(L=n.iconName)!=null?L:"mic",u=($=n.iconSize)!=null?$:a,p=parseFloat(u)||24,f=(_=n.backgroundColor)!=null?_:(q=e==null?void 0:e.sendButton)==null?void 0:q.backgroundColor,g=(O=n.iconColor)!=null?O:(B=e==null?void 0:e.sendButton)==null?void 0:B.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",g?d.style.color=g:d.style.color="var(--persona-text, #111827)";let x=ge(l,p,g||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let M=(G=n.tooltipText)!=null?G:"Start voice recognition";if(((re=n.showTooltip)!=null?re:!1)&&M){let Ee=h("div","persona-send-button-tooltip");Ee.textContent=M,i.appendChild(Ee)}return{button:d,wrapper:i}},ai=e=>{var w,x,M,A,P,N,R,T;let n=(w=e==null?void 0:e.attachments)!=null?w:{};if(n.enabled!==!0)return null;let t=(M=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?M:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((A=n.allowedTypes)!=null?A:Dr).join(","),s.multiple=((P=n.maxFiles)!=null?P:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(N=n.buttonTooltipText)!=null?N:"Attach file");let i=(R=n.buttonIconName)!=null?R:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=ge(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",L=>{L.preventDefault(),s.click()}),o.appendChild(a);let f=(T=n.buttonTooltipText)!=null?T:"Attach file",g=h("div","persona-send-button-tooltip");return g.textContent=f,o.appendChild(g),{button:a,wrapper:o,input:s,previewsContainer:r}},ii=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},li=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var os=e=>{var w,x,M,A,P,N;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=li(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=ri(n);a();let i=oi(n),d=si(n),l=ai(n),u=ii(n);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),p.append(f,g),s.append(p),s.addEventListener("click",R=>{R.target!==i.button&&R.target!==i.wrapper&&R.target!==(d==null?void 0:d.button)&&R.target!==(d==null?void 0:d.wrapper)&&R.target!==(l==null?void 0:l.button)&&R.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,u),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(P=l==null?void 0:l.input)!=null?P:null,attachmentPreviewsContainer:(N=l==null?void 0:l.previewsContainer)!=null?N:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var iu=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=ge("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=ge("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},lu=e=>{var w,x,M,A,P,N;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=li();r.style.display="none";let s=ii(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=ri(n);o.style.maxHeight="100px",a();let i=oi(n),d=si(n),l=ai(n);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",R=>{R.target!==i.button&&R.target!==i.wrapper&&R.target!==(d==null?void 0:d.button)&&R.target!==(d==null?void 0:d.wrapper)&&R.target!==(l==null?void 0:l.button)&&R.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&t.append(l.previewsContainer),t.append(u,r,s);let g=u;return{footer:t,suggestions:r,composerForm:u,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(P=l==null?void 0:l.input)!=null?P:null,attachmentPreviewsContainer:(N=l==null?void 0:l.previewsContainer)!=null?N:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var cu=e=>{var u,p,f,g,w,x,M,A,P,N,R,T,L,$,q,_,B;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=nn(e);if(ao(e)){let O=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},G=h("div","persona-widget-wrapper persona-fixed persona-transition");G.setAttribute("data-persona-composer-bar",""),G.dataset.state="collapsed",G.dataset.expandedSize=(w=O.expandedSize)!=null?w:"anchored",G.style.zIndex=String((M=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?M:yn);let re=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");re.style.width="100%",G.appendChild(re);let Ee=h("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(A=O.expandedSize)!=null?A:"anchored",Ee.style.zIndex=String((N=(P=e==null?void 0:e.launcher)==null?void 0:P.zIndex)!=null?N:yn),{wrapper:G,panel:re,pillRoot:Ee}}if(t){let O=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),G=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(G),{wrapper:O,panel:G}}if(!n){let O=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),G=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),re=(T=(R=e==null?void 0:e.launcher)==null?void 0:R.width)!=null?T:"100%";return O.style.width=re,G.style.width="100%",O.appendChild(G),{wrapper:O,panel:G}}let s=(L=e==null?void 0:e.launcher)!=null?L:{},o=s.position&&dr[s.position]?dr[s.position]:dr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((q=($=e==null?void 0:e.launcher)==null?void 0:$.zIndex)!=null?q:yn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(B=(_=e==null?void 0:e.launcher)==null?void 0:_.width)!=null?B:e==null?void 0:e.launcherWidth,l=d!=null?d:jn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},bg=(e,n)=>{var R,T,L,$,q,_,B,O,G;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Za(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(L=(T=(R=e==null?void 0:e.launcher)==null?void 0:R.clearChat)==null?void 0:T.enabled)!=null?L:!0,a=null,i=null;if(o){let re=ei(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=re.button,i=re.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(q=($=e==null?void 0:e.copy)==null?void 0:$.welcomeTitle)!=null?q:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(B=(_=e==null?void 0:e.copy)==null?void 0:_.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",u.append(p,f);let g=h("div","persona-flex persona-flex-col persona-gap-3"),w=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;w&&(g.style.maxWidth=w,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((G=e==null?void 0:e.copy)==null?void 0:G.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let M=h("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let A=lu({config:e}),{root:P,textNode:N}=iu();return t.append(d,s,l,M),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:g,composerOverlay:M,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:P,peekTextNode:N}},du=(e,n=!0)=>{var M,A,P,N,R,T,L,$,q;if(ao(e))return bg(e,n);let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(M=e==null?void 0:e.layout)==null?void 0:M.header,s=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,o=r?rs(e,r,{showClose:n}):Nr({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=nn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(N=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeTitle)!=null?N:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(T=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(L=e==null?void 0:e.layout)==null?void 0:L.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=os({config:e}),w=((q=e==null?void 0:e.layout)==null?void 0:q.showFooter)!==!1;s?Do(t,o,e):(o.header.style.display="none",Do(t,o,e)),t.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",w||(g.footer.style.display="none"),t.append(g.footer),t.append(x),{container:t,body:a,messagesWrapper:u,composerOverlay:x,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var xg=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},vg=(e,n)=>{if(!e)return null;let t=xg(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},wg=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},Cg=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Ag=320,Sg=320,Eg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Tg=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ag}px`,l.style.maxHeight=`${Sg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),Cg(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},No=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},Ki=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:No};if(n){let s=n(r);if(s!==null)return s}return No()},kg=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},pu=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Mg=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Gi=(e,n,t)=>{var g,w,x,M,A,P;let r=(g=n.showCopy)!=null?g:!0,s=(w=n.showUpvote)!=null?w:!0,o=(x=n.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let N=h("div");return N.style.display="none",N.id=`actions-${e.id}`,N.setAttribute("data-actions-for",e.id),N}let a=(M=n.visibility)!=null?M:"hover",i=(A=n.align)!=null?A:"right",d=(P=n.layout)!=null?P:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(N,R,T)=>{let L=Ot({icon:N,label:R,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",T),L};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},ss=(e,n,t,r,s,o)=>{var ue,ke,je,te,ve,X,oe,Le,ie,De,He,K,Ne,Be,Q,J,we;let a=t!=null?t:{},i=(ue=a.layout)!=null?ue:"bubble",d=a.avatar,l=a.timestamp,u=(ke=d==null?void 0:d.show)!=null?ke:!1,p=(je=l==null?void 0:l.show)!=null?je:!1,f=(te=d==null?void 0:d.position)!=null?te:"left",g=(ve=l==null?void 0:l.position)!=null?ve:"below",w=Mg(e.role,i),x=h("div",w.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Eg(e),A=(oe=(X=e.content)==null?void 0:X.trim())!=null?oe:"",N=M.length>0&&A===Ha,R=Ga((ie=(Le=o==null?void 0:o.widgetConfig)==null?void 0:Le.features)==null?void 0:ie.streamAnimation),T=(K=(He=(De=o==null?void 0:o.widgetConfig)==null?void 0:De.features)==null?void 0:He.streamAnimation)==null?void 0:K.plugins,L=e.role==="assistant"&&R.type!=="none"?js(R.type,T):null,$=e.role==="assistant"&&((Ne=L==null?void 0:L.isAnimating)==null?void 0:Ne.call(L,e))===!0,q=e.role==="assistant"&&L!==null&&(!!e.streaming||$);q&&(L!=null&&L.bubbleClass)&&x.classList.add(L.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),q&&L&&(L.containerClass&&_.classList.add(L.containerClass),_.style.setProperty("--persona-stream-step",`${R.speed}ms`),_.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let B=q?Qa((Be=e.content)!=null?Be:"",R.buffer,L,e,!!e.streaming):(Q=e.content)!=null?Q:"",O=n({text:B,message:e,streaming:!!e.streaming,raw:e.rawContent}),G=O;q&&(L==null?void 0:L.wrap)==="char"?G=qs(O,"char",e.id,{skipTags:L.skipTags}):q&&(L==null?void 0:L.wrap)==="word"&&(G=qs(O,"word",e.id,{skipTags:L.skipTags}));let re=null;if(N?(re=document.createElement("div"),re.innerHTML=G,re.style.display="none",_.appendChild(re)):_.innerHTML=G,q&&(L!=null&&L.useCaret)&&!N&&A){let de=Xa(),ne=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),fe=ne[ne.length-1];if(fe!=null&&fe.parentNode)fe.parentNode.insertBefore(de,fe.nextSibling);else{let Xe=_.lastElementChild;Xe?Xe.appendChild(de):_.appendChild(de)}}if(p&&g==="inline"&&e.createdAt){let de=pu(e,l);de.classList.add("persona-ml-2","persona-inline"),_.appendChild(de)}if(M.length>0){let de=Tg(M,!N&&!!A,()=>{N&&re&&(re.style.display="")});de?x.appendChild(de):N&&re&&(re.style.display="")}if(x.appendChild(_),p&&g==="below"&&e.createdAt){let de=pu(e,l);de.classList.add("persona-mt-1"),x.appendChild(de)}let Ee=e.role==="assistant"?vg(e.stopReason,(we=(J=o==null?void 0:o.widgetConfig)==null?void 0:J.copy)==null?void 0:we.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let de=!!(B&&B.trim()),ne=R.placeholder==="skeleton",fe=ne&&R.buffer==="line"&&de;if(de)fe&&x.appendChild(zs());else if(ne)x.appendChild(zs());else{let Xe=Ki("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Xe&&x.appendChild(Xe)}}if(Ee&&e.stopReason&&!e.streaming&&(A||(_.style.display="none"),x.appendChild(wg(e.stopReason,Ee))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let de=Gi(e,r,s);x.appendChild(de)}if(!u||e.role==="system")return x;let Ue=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),he=kg(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Ue.append(x,he):Ue.append(he,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ue},uu=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ss(e,n,t,r,s,o)};var as=new Set,Lg=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Pg=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
17
+ `):""},mu=(e,n)=>{let t=as.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Qi=(e,n)=>{var Re,Ue,he,ue,ke,je,te,ve,X,oe,Le;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let s=(Ue=(Re=n==null?void 0:n.features)==null?void 0:Re.reasoningDisplay)!=null?Ue:{},o=s.expandable!==!1,a=o&&as.has(e.id),i=t.status!=="complete",d=Pg(e,(he=s.previewMaxLines)!=null?he:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(ue=n==null?void 0:n.reasoning)!=null?ue:{},w=String((ke=t.startedAt)!=null?ke:Date.now()),x=()=>{let ie=h("span","");return ie.setAttribute("data-tool-elapsed",w),ie.textContent=Ta(t),ie},M=(je=g.renderCollapsedSummary)==null?void 0:je.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:Ta(t),createElapsedElement:x});typeof M=="string"&&M.trim()?(p.textContent=M,u.appendChild(p)):M instanceof HTMLElement?u.appendChild(M):(p.textContent=f,u.appendChild(p));let A=h("span","persona-text-xs persona-text-persona-primary");A.textContent=Mp(t),u.appendChild(A);let P=(te=s.loadingAnimation)!=null?te:"none",N=g.activeTextTemplate,R=g.completeTextTemplate,T=i?N:R,L=M instanceof HTMLElement,$=(ie,De,He)=>{let K=He;for(let Ne of De){let Be=h("span","persona-tool-char");Be.style.setProperty("--char-index",String(K)),Be.textContent=Ne===" "?"\xA0":Ne,ie.appendChild(Be),K++}return K},q=(ie,De)=>{p.textContent="";let He=ka(ie,""),K=0;for(let Ne of He){let Be=Ne.styles.length>0?(()=>{let Q=h("span",Ne.styles.map(J=>`persona-tool-text-${J}`).join(" "));return p.appendChild(Q),Q})():p;if(Ne.isDuration&&i)Be.appendChild(x());else{let Q=Ne.isDuration?Ta(t):Ne.text;De?K=$(Be,Q,K):Be.appendChild(document.createTextNode(Q))}}};if(!L&&T)if(A.style.display="none",p.style.display="",i&&P!=="none"){let ie=(ve=g.loadingAnimationDuration)!=null?ve:2e3;p.setAttribute("data-preserve-animation","true"),P==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),q(T,!1)):(p.classList.add(`persona-tool-loading-${P}`),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),P==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),q(T,!0))}else q(T,!1);else if(!L&&i&&P!=="none"){p.style.display="";let ie=(X=g.loadingAnimationDuration)!=null?X:2e3;if(p.setAttribute("data-preserve-animation","true"),P==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`);else{p.classList.add(`persona-tool-loading-${P}`),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),P==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let De=p.textContent||f;p.textContent="",$(p,De,0)}t.status==="complete"&&(p.style.display="none")}else L||(t.status==="complete"?p.style.display="none":p.style.display="");let _=null;if(o){_=h("div","persona-flex persona-items-center");let De=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);De?_.appendChild(De):_.textContent=a?"Hide":"Show";let He=h("div","persona-flex persona-items-center persona-ml-auto");He.append(_),l.append(u,He)}else l.append(u);let B=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","reasoning"),B.style.display="none",B.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let ie=(Le=(oe=n==null?void 0:n.reasoning)==null?void 0:oe.renderCollapsedPreview)==null?void 0:Le.call(oe,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});Lg(B,ie)||(B.textContent=d),B.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,B),r;let O=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let G=t.chunks.join(""),re=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return re.textContent=G||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(re),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),_){_.innerHTML="";let De=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);De?_.appendChild(De):_.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",B.style.display=a?"none":B.textContent||B.childNodes.length?"":"none"})(),r.append(l,B,O),r};var is=new Set,Ig=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Wg=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
18
+ `);let s=Xo(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
19
+ `):""},Rg=(e,n)=>{var u,p,f,g,w;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=Wg(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?Lp(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(g=n==null?void 0:n.toolCall)!=null?g:{},l=a;return s==="tool-name"?l=((w=t.name)==null?void 0:w.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Ri(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ri(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},gu=(e,n,t)=>{var u;let r=is.has(e),s=(u=t==null?void 0:t.toolCall)!=null?u:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=ge(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Xi=(e,n)=>{var G,re,Ee,Re,Ue,he,ue,ke,je;let t=e.toolCall,r=(G=n==null?void 0:n.toolCall)!=null?G:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(Ee=(re=n==null?void 0:n.features)==null?void 0:re.toolCallDisplay)!=null?Ee:{},a=o.expandable!==!1,i=a&&is.has(e.id),{summary:d,previewText:l,isActive:u}=Rg(e,n),p=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let w=String((Re=t.startedAt)!=null?Re:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",w),te.textContent=Rs(t),te},M=(he=r.renderCollapsedSummary)==null?void 0:he.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Ue=o.collapsedMode)!=null?Ue:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Rs(t),createElapsedElement:x});typeof M=="string"&&M.trim()?(g.textContent=M,f.appendChild(g)):M instanceof HTMLElement?f.appendChild(M):(g.textContent=d,f.appendChild(g));let A=(ue=o.loadingAnimation)!=null?ue:"none",P=r.activeTextTemplate,N=r.completeTextTemplate,R=u?P:N,T=M instanceof HTMLElement,L=(te,ve,X)=>{let oe=X;for(let Le of ve){let ie=h("span","persona-tool-char");ie.style.setProperty("--char-index",String(oe)),ie.textContent=Le===" "?"\xA0":Le,te.appendChild(ie),oe++}return oe},$=(te,ve)=>{var ie;g.textContent="";let X=((ie=t.name)==null?void 0:ie.trim())||"tool",oe=ka(te,X),Le=0;for(let De of oe){let He=De.styles.length>0?(()=>{let K=h("span",De.styles.map(Ne=>`persona-tool-text-${Ne}`).join(" "));return g.appendChild(K),K})():g;if(De.isDuration&&u)He.appendChild(x());else{let K=De.isDuration?Rs(t):De.text;ve?Le=L(He,K,Le):He.appendChild(document.createTextNode(K))}}};if(!T)if(u&&A!=="none"){let te=(ke=r.loadingAnimationDuration)!=null?ke:2e3;if(g.setAttribute("data-preserve-animation","true"),A==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),R&&$(R,!1);else if(g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),A==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),R)$(R,!0);else{let ve=g.textContent||d;g.textContent="",L(g,ve,0)}}else R&&$(R,!1);let q=null;if(a){q=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",ve=ge(i?"chevron-up":"chevron-down",16,te,2);ve?q.appendChild(ve):q.textContent=i?"Hide":"Show";let X=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(q),p.append(f,X)}else p.append(f);let _=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(_.setAttribute("data-persona-collapsed-preview","tool"),_.style.display="none",_.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let te=(je=r.renderCollapsedPreview)==null?void 0:je.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});Ig(_,te)||(_.textContent=l),_.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,_),s;let B=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(B.style.display=i?"":"none",r.contentBackgroundColor&&(B.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(B.style.color=r.contentTextColor),r.contentPaddingX&&(B.style.paddingLeft=r.contentPaddingX,B.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(B.style.paddingTop=r.contentPaddingY,B.style.paddingBottom=r.contentPaddingY),t.name){let te=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?te.style.color=r.contentTextColor:r.headerTextColor&&(te.style.color=r.headerTextColor),te.textContent=t.name,B.appendChild(te)}if(t.args!==void 0){let te=h("div","persona-space-y-1"),ve=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ve.style.color=r.labelTextColor),ve.textContent="Arguments";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(X.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(X.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(X.style.color=r.codeBlockTextColor),X.textContent=Xo(t.args),te.append(ve,X),B.appendChild(te)}if(t.chunks&&t.chunks.length){let te=h("div","persona-space-y-1"),ve=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ve.style.color=r.labelTextColor),ve.textContent="Activity";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(X.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(X.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(X.style.color=r.codeBlockTextColor),X.textContent=t.chunks.join(""),te.append(ve,X),B.appendChild(te)}if(t.status==="complete"&&t.result!==void 0){let te=h("div","persona-space-y-1"),ve=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ve.style.color=r.labelTextColor),ve.textContent="Result";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(X.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(X.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(X.style.color=r.codeBlockTextColor),X.textContent=Xo(t.result),te.append(ve,X),B.appendChild(te)}if(t.status==="complete"&&typeof t.duration=="number"){let te=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(te.style.color=r.contentTextColor),te.textContent=`Duration: ${t.duration}ms`,B.appendChild(te)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),q){q.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",ve=ge(i?"chevron-up":"chevron-down",16,te,2);ve?q.appendChild(ve):q.textContent=i?"Hide":"Show"}B.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),s.append(p,_,B),s};var lo=require("partial-json");var Zi="ask_user_question",Yi=8,ls="data-persona-ask-sheet-for",Hg="Other",Bg="Other\u2026",hu="Type your own answer here",yu="Send",Dg="Next",Ng="Back",Fg="Submit all",Og="Skip",$g=3,el="data-ask-current-index",tl="data-ask-question-count",bu="data-ask-answers",nl="data-ask-grouped",xu="data-ask-layout",_g=e=>e.layout==="pills"?"pills":"rows",Ug=e=>e.getAttribute(xu)==="pills"?"pills":"rows",fu=!1,vu=e=>e.replace(/["\\]/g,"\\$&"),Fr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Zi,ci=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},Or=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=(0,lo.parse)(s,lo.STR|lo.OBJ|lo.ARR);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},Qs=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>Yi&&!fu&&(fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${Yi}.`)),n.slice(0,Yi)},jg=e=>{var n;return(n=Qs(e)[0])!=null?n:null},qg=(e,n)=>{var t;return(t=Qs(e)[n])!=null?t:null},wu=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Cu=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},zg=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Cu(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Vg=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},Jg=(e,n,t,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!t){for(let g=0;g<$g;g++)o.appendChild(Vg(r));return o}if(d.forEach((g,w)=>{o.appendChild(zg(g,w,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Hg:Bg;if(r==="rows"){let w=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(u=n.freeTextPlaceholder)!=null?u:hu,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:g),x.appendChild(M),w.appendChild(x);let A=Cu(r,a,d.length);A&&w.appendChild(A),o.appendChild(w)}else{let w=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(f=n.freeTextLabel)!=null?f:g,o.appendChild(w)}}return o},Au=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:hu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:yu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Kg=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:yu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},Gg=(e,n,t)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=t.backLabel)!=null?l:Ng,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:Og,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:Fg:(f=t.nextLabel)!=null?f:Dg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Fo=e=>{let n=e.getAttribute(bu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Su=(e,n)=>{e.setAttribute(bu,JSON.stringify(n))},Yn=e=>{var t;let n=Number((t=e.getAttribute(el))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},Qg=(e,n)=>{e.setAttribute(el,String(Math.max(0,Math.floor(n))))},cs=e=>{var t;let n=Number((t=e.getAttribute(tl))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},co=e=>e.getAttribute(nl)==="true",Xg=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Yg=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},di=(e,n)=>{let{payload:t}=Or(n),r=Qs(t),s=Fo(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Eu=e=>{let n=Fo(e),t=Yn(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Tu=e=>{if(!co(e))return;let n=Fo(e),t=Yn(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},rl=(e,n,t)=>{let r=ci(t),s=Ug(e),{payload:o,complete:a}=Or(n),i=co(e),d=Yn(e),l=cs(e),u=i?qg(o,d):jg(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let P=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=P,w.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let P=Jg(u,r,a,s);x.replaceWith(P)}if(s!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Au(r,s))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!M?e.appendChild(Kg(r)):(!p||i)&&M&&M.remove(),e.setAttribute("data-multi-select",p?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=Gg(d,l,r);A?A.replaceWith(P):e.appendChild(P)}else A&&A.remove();Eu(e),Tu(e)},Zg=(e,n,t)=>{let r=ci(n),s=_g(r),o=e.toolCall.id,a=Qs(t),i=Math.max(1,a.length),d=i>1,l=Xg(e,a),u=d?Yg(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(ls,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(tl,String(i)),p.setAttribute(el,String(u)),p.setAttribute(nl,d?"true":"false"),p.setAttribute(xu,s),Su(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),wu(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let w=h("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",f.appendChild(w),p.appendChild(f);let M=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),p.appendChild(M),s!=="rows"&&p.appendChild(Au(r,s)),rl(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},ef=(e,n,t)=>{let{payload:r}=Or(n),s=Math.max(1,Qs(r).length);s>cs(e)&&(e.setAttribute(tl,String(s)),s>1&&!co(e)&&e.setAttribute(nl,"true")),rl(e,n,t)},ku=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=ci(n);wu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=Or(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},ds=(e,n,t)=>{if(!t||!Fr(e)||ci(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${ls}]`).forEach(l=>{l.getAttribute(ls)!==s&&l.remove()});let a=t.querySelector(`[${ls}="${vu(s)}"]`);if(a){ef(a,e,n);return}let{payload:i}=Or(e),d=Zg(e,n,i);t.appendChild(d)},po=(e,n)=>{if(!e)return;let t=n?`[${ls}="${vu(n)}"]`:`[${ls}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},ol=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),uo=(e,n)=>{let t=Fo(e),r=Yn(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Su(e,t),Eu(e),Tu(e)},pi=(e,n,t,r)=>{let s=cs(e),o=Math.max(0,Math.min(s-1,r));Qg(e,o),rl(e,n,t)};var sl=(e,n)=>{var x,M,A,P,N,R,T,L,$,q,_,B;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(M=r==null?void 0:r.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=r==null?void 0:r.titleColor)!=null?A:"currentColor",u=ge(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(P=r==null?void 0:r.title)!=null?P:"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 w=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(w.style.color=r.descriptionColor),w.textContent=t.description,p.appendChild(w),t.parameters){let O=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(O.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(O.style.color=r.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=Xo(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 G=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");G.type="button",G.style.backgroundColor=(N=r==null?void 0:r.approveButtonColor)!=null?N:"var(--persona-approval-approve-bg, #22c55e)",G.style.color=(R=r==null?void 0:r.approveButtonTextColor)!=null?R:"#ffffff",G.setAttribute("data-approval-action","approve");let re=ge("shield-check",14,(T=r==null?void 0:r.approveButtonTextColor)!=null?T:"#ffffff",2);re&&(re.style.marginRight="4px",G.appendChild(re));let Ee=document.createTextNode((L=r==null?void 0:r.approveLabel)!=null?L:"Approve");G.appendChild(Ee);let Re=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Re.type="button",Re.style.backgroundColor=($=r==null?void 0:r.denyButtonColor)!=null?$:"transparent",Re.style.color=(q=r==null?void 0:r.denyButtonTextColor)!=null?q:"var(--persona-feedback-error, #dc2626)",Re.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Re.setAttribute("data-approval-action","deny");let Ue=ge("shield-x",14,(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",2);Ue&&(Ue.style.marginRight="4px",Re.appendChild(Ue));let he=document.createTextNode((B=r==null?void 0:r.denyLabel)!=null?B:"Deny");Re.appendChild(he),O.append(G,Re),p.appendChild(O)}return a.append(i,p),o.appendChild(a),o};var Mu=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let u=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'}};r.forEach(g=>{let w=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");w.type="button",w.textContent=g,w.disabled=p,i!=null&&i.fontFamily&&(w.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),u.appendChild(w),n.push(w)}),e.appendChild(u)}}};var Xs=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ys=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function ps(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var tf={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)"}},nf={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},rf=["flowName","stepName","reasoningText","text","name","tool","toolName"],of=100;function sf(e,n){let t={...tf,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return nf}function af(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function lf(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function cf(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function df(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function pf(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function uf(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function al(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ps(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let g=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var G,re;let g=h("div",""),w=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");w.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&x.appendChild(M);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=(G=r.timestampFormat)!=null?G:"relative";A.textContent=P==="relative"?af(e.timestamp,t):lf(e.timestamp);let N=null;r.showSequenceNumbers!==!1&&(N=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),N.textContent=String(n+1));let R=sf(e.type,r.badgeColors),T=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");T.style.backgroundColor=R.bg,T.style.color=R.text,T.style.borderColor=R.text+"50",T.textContent=e.type;let L=(re=r.descriptionFields)!=null?re:rf,$=cf(e.payload,L),q=null;$&&(q=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),q.textContent=$);let _=h("div","persona-flex-1 persona-min-w-0"),B=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=ge("clipboard","12px","currentColor",1.5);return O&&B.appendChild(O),B.addEventListener("click",async Ee=>{Ee.stopPropagation(),await df(pf(e)),B.innerHTML="";let Re=ge("check","12px","currentColor",1.5);Re&&B.appendChild(Re),setTimeout(()=>{B.innerHTML="";let Ue=ge("clipboard","12px","currentColor",1.5);Ue&&B.appendChild(Ue)},1500)}),w.appendChild(x),w.appendChild(A),N&&w.appendChild(N),w.appendChild(T),q&&w.appendChild(q),w.appendChild(_),w.appendChild(B),g.appendChild(w),d&&g.appendChild(uf(e,a,i)),g}}function Lu(e){var g,w,x,M,A;let{buffer:n,getFullHistory:t,onClose:r,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,d=(w=a==null?void 0:a.iconName)!=null?w:"arrow-down",l=(x=a==null?void 0:a.label)!=null?x:"",u=(A=(M=s==null?void 0:s.features)==null?void 0:M.eventStream)!=null?A:{},p=o.find(P=>P.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let P=p.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return f();function f(){let P=u.classNames,N=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ps(N,P==null?void 0:P.panel);let R=[],T="",L="",$=null,q=[],_={},B=0,O=Va(),G=0,re=0,Ee=!1,Re=null,Ue=!1,he=0,ue=new Set,ke=new Map,je="",te="",ve=null,X,oe,Le,ie,De;function He(){let H=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ae=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");ps(ae,P==null?void 0:P.headerBar);let Ce=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ce.textContent="Events",X=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"),X.textContent="0";let ut=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 Ke=h("option","");Ke.value="",Ke.textContent="All events",oe.appendChild(Ke),Le=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"),Le.type="button",Le.title="Copy All";let cn=ge("clipboard-copy","12px","currentColor",1.5);cn&&Le.appendChild(cn);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",Le.appendChild(Ct),ae.appendChild(Ce),ae.appendChild(X),ae.appendChild(ut),ae.appendChild(oe),ae.appendChild(Le);let yt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ps(yt,P==null?void 0:P.searchBar);let Et=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),lt=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");Et&&lt.appendChild(Et),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"),ps(ie,P==null?void 0:P.searchInput),ie.type="text",ie.placeholder="Search event payloads...",De=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"),De.type="button",De.style.display="none";let Jt=ge("x","12px","currentColor",2);return Jt&&De.appendChild(Jt),yt.appendChild(lt),yt.appendChild(ie),yt.appendChild(De),H.appendChild(ae),H.appendChild(yt),H}let K,Ne=o.find(H=>H.renderEventStreamToolbar);if(Ne!=null&&Ne.renderEventStreamToolbar&&s){let H=Ne.renderEventStreamToolbar({config:s,defaultRenderer:()=>He(),eventCount:n.getSize(),filteredCount:0,onFilterChange:ae=>{T=ae,Fe(),zt()},onSearchChange:ae=>{L=ae,Fe(),zt()}});K=H!=null?H:He()}else K=He();let Be=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");Be.style.display="none";let Q=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 we=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ps(we,P==null?void 0:P.scrollIndicator),we.style.display="none",we.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let de=ge(d,"14px","currentColor",2);de&&we.appendChild(de);let ne=h("span","");ne.textContent=l,we.appendChild(ne);let fe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");fe.style.display="none",Q.appendChild(J),Q.appendChild(fe),Q.appendChild(we),N.setAttribute("tabindex","0"),N.appendChild(K),N.appendChild(Be),N.appendChild(Q);function Xe(){let H=n.getAll(),ae={};for(let Ct of H)ae[Ct.type]=(ae[Ct.type]||0)+1;let Ce=Object.keys(ae).sort(),ut=Ce.length!==q.length||!Ce.every((Ct,yt)=>Ct===q[yt]),Ke=!ut&&Ce.some(Ct=>ae[Ct]!==_[Ct]),Ft=H.length!==Object.values(_).reduce((Ct,yt)=>Ct+yt,0);if(!ut&&!Ke&&!Ft||(q=Ce,_=ae,!oe))return;let cn=oe.value;if(oe.options[0].textContent="All events",ut){for(;oe.options.length>1;)oe.remove(1);for(let Ct of Ce){let yt=h("option","");yt.value=Ct,yt.textContent=`${Ct} (${ae[Ct]||0})`,oe.appendChild(yt)}cn&&Ce.includes(cn)?oe.value=cn:cn&&(oe.value="",T="")}else for(let Ct=1;Ct<oe.options.length;Ct++){let yt=oe.options[Ct];yt.textContent=`${yt.value} (${ae[yt.value]||0})`}}function $t(){let H=n.getAll();if(T&&(H=H.filter(ae=>ae.type===T)),L){let ae=L.toLowerCase();H=H.filter(Ce=>Ce.type.toLowerCase().includes(ae)||Ce.payload.toLowerCase().includes(ae))}return H}function le(){return T!==""||L!==""}function Fe(){B=0,G=0,O.resume(),we.style.display="none"}function ln(H){ue.has(H)?ue.delete(H):ue.add(H),ve=H;let ae=J.scrollTop,Ce=O.isFollowing();Ue=!0,O.pause(),zt(),J.scrollTop=ae,Ce&&O.resume(),Ue=!1}function It(){return $s(J,50)}function zt(){re=Date.now(),Ee=!1,Xe();let H=n.getEvictedCount();H>0?(Be.textContent=`${H.toLocaleString()} older events truncated`,Be.style.display=""):Be.style.display="none",R=$t();let ae=R.length,Ce=n.getSize()>0;X&&(X.textContent=String(n.getSize())),ae===0&&Ce&&le()?(fe.textContent=L?`No events matching '${L}'`:"No events matching filter",fe.style.display="",J.style.display="none"):(fe.style.display="none",J.style.display=""),Le&&(Le.title=le()?`Copy Filtered (${ae})`:"Copy All"),i&&!O.isFollowing()&&ae>B&&(G+=ae-B,ne.textContent=l?`${l}${G>0?` (${G})`:""}`:"",we.style.display=""),B=ae;let ut=n.getAll(),Ke=ut.length>0?ut[0].timestamp:0,Ft=new Set(R.map(yt=>yt.id));for(let yt of ue)Ft.has(yt)||ue.delete(yt);let cn=T!==je||L!==te,Ct=ke.size===0&&R.length>0;if(cn||Ct||R.length===0){J.innerHTML="",ke.clear();let yt=document.createDocumentFragment();for(let Et=0;Et<R.length;Et++){let lt=al(R[Et],Et,Ke,u,ue,ln,o,s);ke.set(R[Et].id,lt),yt.appendChild(lt)}J.appendChild(yt),je=T,te=L,ve=null}else{if(ve!==null){let Et=ke.get(ve);if(Et&&Et.parentNode===J){let lt=R.findIndex(Jt=>Jt.id===ve);if(lt>=0){let Jt=al(R[lt],lt,Ke,u,ue,ln,o,s);J.insertBefore(Jt,Et),Et.remove(),ke.set(ve,Jt)}}ve=null}let yt=new Set(R.map(Et=>Et.id));for(let[Et,lt]of ke)yt.has(Et)||(lt.remove(),ke.delete(Et));for(let Et=0;Et<R.length;Et++){let lt=R[Et];if(!ke.has(lt.id)){let Jt=al(lt,Et,Ke,u,ue,ln,o,s);ke.set(lt.id,Jt),J.appendChild(Jt)}}}O.isFollowing()&&(J.scrollTop=J.scrollHeight)}function wr(){if(Date.now()-re>=of){Re!==null&&(cancelAnimationFrame(Re),Re=null),zt();return}Ee||(Ee=!0,Re=requestAnimationFrame(()=>{Re=null,zt()}))}let pr=(H,ae)=>{if(!Le)return;Le.innerHTML="";let Ce=ge(H,"12px","currentColor",1.5);Ce&&Le.appendChild(Ce);let ut=h("span","persona-text-xs");ut.textContent="Copy All",Le.appendChild(ut),setTimeout(()=>{Le.innerHTML="";let Ke=ge("clipboard-copy","12px","currentColor",1.5);Ke&&Le.appendChild(Ke);let Ft=h("span","persona-text-xs");Ft.textContent="Copy All",Le.appendChild(Ft),Le.disabled=!1},ae)},I=async()=>{if(Le){Le.disabled=!0;try{let H;le()?H=R:t?(H=await t(),H.length===0&&(H=n.getAll())):H=n.getAll();let ae=H.map(Ce=>{try{return JSON.parse(Ce.payload)}catch{return Ce.payload}});await navigator.clipboard.writeText(JSON.stringify(ae,null,2)),pr("check",1500)}catch{pr("x",1500)}}},se=()=>{oe&&(T=oe.value,Fe(),zt())},Ie=()=>{!ie||!De||(De.style.display=ie.value?"":"none",$&&clearTimeout($),$=setTimeout(()=>{L=ie.value,Fe(),zt()},150))},ze=()=>{!ie||!De||(ie.value="",L="",De.style.display="none",$&&clearTimeout($),Fe(),zt())},Oe=()=>{if(Ue)return;let H=J.scrollTop,{action:ae,nextLastScrollTop:Ce}=Ja({following:O.isFollowing(),currentScrollTop:H,lastScrollTop:he,nearBottom:It(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Ce,ae==="resume"?(O.resume(),G=0,we.style.display="none"):ae==="pause"&&(O.pause(),i&&(ne.textContent=l,we.style.display=""))},$e=H=>{let ae=Ka({following:O.isFollowing(),deltaY:H.deltaY,nearBottom:It(),resumeWhenNearBottom:!0});ae==="pause"?(O.pause(),i&&(ne.textContent=l,we.style.display="")):ae==="resume"&&(O.resume(),G=0,we.style.display="none")},et=()=>{i&&(J.scrollTop=J.scrollHeight,O.resume(),G=0,we.style.display="none")},wt=H=>{let ae=H.target;if(!ae||ae.closest("button"))return;let Ce=ae.closest("[data-event-id]");if(!Ce)return;let ut=Ce.getAttribute("data-event-id");ut&&ln(ut)},_t=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),ie==null||ie.focus(),ie==null||ie.select();return}H.key==="Escape"&&(ie&&document.activeElement===ie?(ze(),ie.blur(),N.focus()):r&&r())};Le&&Le.addEventListener("click",I),oe&&oe.addEventListener("change",se),ie&&ie.addEventListener("input",Ie),De&&De.addEventListener("click",ze),J.addEventListener("scroll",Oe),J.addEventListener("wheel",$e,{passive:!0}),J.addEventListener("click",wt),we.addEventListener("click",et),N.addEventListener("keydown",_t);function Vt(){$&&clearTimeout($),Re!==null&&(cancelAnimationFrame(Re),Re=null),Ee=!1,ke.clear(),Le&&Le.removeEventListener("click",I),oe&&oe.removeEventListener("change",se),ie&&ie.removeEventListener("input",Ie),De&&De.removeEventListener("click",ze),J.removeEventListener("scroll",Oe),J.removeEventListener("wheel",$e),J.removeEventListener("click",wt),we.removeEventListener("click",et),N.removeEventListener("keydown",_t)}return{element:N,update:wr,destroy:Vt}}}function Pu(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(g)}else p.textContent=a;if(l.append(u,p),i.append(d,l),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Iu=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>Pu(e,n)});if(u)return u}return Pu(e,n)};var il=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},$r=new il;$r.register("PersonaArtifactCard",Iu);function mf(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function Wu(e,n){var Le,ie,De,He;let t=(ie=(Le=e.features)==null?void 0:Le.artifacts)==null?void 0:ie.layout,s=((De=t==null?void 0:t.toolbarPreset)!=null?De:"default")==="document",o=(He=t==null?void 0:t.panePadding)==null?void 0:He.trim(),a=e.markdown?Mo(e.markdown):null,i=Qo(e.sanitize),d=K=>{let Ne=a?a(K):Lo(K);return i?i(Ne):Ne},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let w=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let x="rendered",M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),A=s?Ot({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Ot({icon:"eye",label:"Rendered view"}),P=s?Ot({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Ot({icon:"code-2",label:"Source"}),N=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),R=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,T=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,L=t==null?void 0:t.documentToolbarCopyMenuItems,$=!!(T&&L&&L.length>0),q=null,_,B=null,O=null;if(s&&(R||T)&&!$){if(_=R?Ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ot({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T){let K=ge("chevron-down",14,"currentColor",2);K&&_.appendChild(K)}}else s&&$?(q=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=R?Ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ot({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B=Ot({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"}}),q.append(_,B)):s?_=Ot({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):_=Ot({icon:"copy",label:"Copy"});let G=s?Ot({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ot({icon:"refresh-cw",label:"Refresh"}),re=s?Ot({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Ot({icon:"x",label:"Close"}),Ee=()=>{var J,we,de;let K=(J=je.find(ne=>ne.id===te))!=null?J:je[je.length-1],Ne=(we=K==null?void 0:K.id)!=null?we:null,Be=(K==null?void 0:K.artifactType)==="markdown"&&(de=K.markdown)!=null?de:"",Q=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Be,jsonPayload:Q,id:Ne}},Re=async()=>{var J;let{markdown:K,jsonPayload:Ne}=Ee(),Be=(J=je.find(we=>we.id===te))!=null?J:je[je.length-1],Q=(Be==null?void 0:Be.artifactType)==="markdown"?K:Be?Ne:"";try{await navigator.clipboard.writeText(Q)}catch{}};if(_.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&$){let{markdown:Ne,jsonPayload:Be,id:Q}=Ee();try{await K({actionId:"primary",artifactId:Q,markdown:Ne,jsonPayload:Be})}catch{}return}await Re()}),B&&(L!=null&&L.length)){let K=()=>{var Be;return(Be=p.closest("[data-persona-root]"))!=null?Be:document.body},Ne=()=>{O=io({items:L.map(Be=>({id:Be.id,label:Be.label})),onSelect:async Be=>{let{markdown:Q,jsonPayload:J,id:we}=Ee(),de=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{de?await de({actionId:Be,artifactId:we,markdown:Q,jsonPayload:J}):Be==="markdown"||Be==="md"?await navigator.clipboard.writeText(Q):Be==="json"||Be==="source"?await navigator.clipboard.writeText(J):await navigator.clipboard.writeText(Q||J)}catch{}},anchor:q!=null?q:B,position:"bottom-right",portal:K()})};p.isConnected?Ne():requestAnimationFrame(Ne),B.addEventListener("click",Be=>{Be.stopPropagation(),O==null||O.toggle()})}G.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}X()}),re.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let Ue=()=>{s&&(A.setAttribute("aria-pressed",x==="rendered"?"true":"false"),P.setAttribute("aria-pressed",x==="source"?"true":"false"))};A.addEventListener("click",()=>{x="rendered",Ue(),X()}),P.addEventListener("click",()=>{x="source",Ue(),X()});let he=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(),M.append(A,P),q?N.append(q,G,re):N.append(_,G,re),f.append(M,he,N),Ue()):(f.appendChild(g),f.appendChild(w)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ue=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&&(ue.style.paddingLeft=o,ue.style.paddingRight=o,ke.style.padding=o),p.appendChild(f),p.appendChild(ue),p.appendChild(ke);let je=[],te=null,ve=!1,X=()=>{var Q,J,we,de;let K=s&&je.length<=1;ue.classList.toggle("persona-hidden",K),ue.replaceChildren();for(let ne of je){let fe=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");fe.type="button",fe.textContent=ne.title||ne.id.slice(0,8),ne.id===te&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>n.onSelect(ne.id)),ue.appendChild(fe)}ke.replaceChildren();let Ne=te&&je.find(ne=>ne.id===te)||je[je.length-1];if(!Ne)return;if(s){let ne=Ne.artifactType==="markdown"?"MD":(Q=Ne.component)!=null?Q:"Component",Xe=(Ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${Xe} \xB7 ${ne}`}else g.textContent="Artifacts";if(Ne.artifactType==="markdown"){if(s&&x==="source"){let fe=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(J=Ne.markdown)!=null?J:"",ke.appendChild(fe);return}let ne=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ne.innerHTML=d((we=Ne.markdown)!=null?we:""),ke.appendChild(ne);return}let Be=Ne.component?$r.get(Ne.component):void 0;if(Be){let fe={message:{id:Ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Xe=Be((de=Ne.props)!=null?de:{},fe);if(Xe){ke.appendChild(Xe);return}}catch{}}ke.appendChild(mf(Ne))},oe=()=>{var Ne;let K=je.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Be=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,J=((Ne=Be==null?void 0:Be.classList.contains("persona-artifact-narrow-host"))!=null?Ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&J&&ve?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var Ne,Be,Q;je=K.artifacts,te=(Q=(Be=K.selectedId)!=null?Be:(Ne=K.artifacts[K.artifacts.length-1])==null?void 0:Ne.id)!=null?Q:null,je.length>0&&(ve=!0),X(),oe()},setMobileOpen(K){ve=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):oe()}}}function Zn(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Ru(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Zn(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function gf(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 ui(e,n){var d,l,u,p,f,g,w,x,M,A;if(!Zn(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),gf(e),Ru(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(w=t==null?void 0:t.panePadding)==null?void 0:w.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(A=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:A.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ru(e,n)}var Hu=["panel","seamless"];function mi(e,n){var i,d,l,u,p,f;for(let g of Hu)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"),!Zn(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=Hu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Bu(e,n){var t,r,s;return!n||!Zn(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function ff(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function hf(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function yf(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function bf(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function Du(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Nu(e,n,t,r,s,o){let a=ff(s,200),i=bf(n,t,r,200);i=Math.max(a,i);let d=hf(o);return d!==null&&(i=Math.min(i,d)),yf(e,a,i)}var Fu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},ll=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var w,x,M;if(o.dataset.enhanced==="true")return;let a=(w=o.dataset.tvForm)!=null?w:"init";o.dataset.enhanced="true";let i=(x=Fu[a])!=null?x:Fu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let A=h("p","persona-text-sm persona-text-persona-muted");A.textContent=i.description,d.appendChild(A)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(A=>{var L,$;let P=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");P.htmlFor=`${n.id}-${a}-${A.name}`;let N=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");N.textContent=A.label,P.appendChild(N);let R=(L=A.type)!=null?L:"text",T;R==="textarea"?(T=document.createElement("textarea"),T.rows=3):(T=document.createElement("input"),T.type=R),T.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",T.id=`${n.id}-${a}-${A.name}`,T.name=A.name,T.placeholder=($=A.placeholder)!=null?$:"",A.required&&(T.required=!0),P.appendChild(T),u.appendChild(P)});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=(M=i.submitLabel)!=null?M:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async A=>{var T,L;A.preventDefault();let P=(T=t.formEndpoint)!=null?T:"/form",N=new FormData(u),R={};N.forEach(($,q)=>{R[q]=$}),R.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let $=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(R)});if(!$.ok)throw new Error(`Form submission failed (${$.status})`);let q=await $.json();f.textContent=(L=q.message)!=null?L:"Thanks! We'll be in touch soon.",q.success&&q.nextPrompt&&await r.sendMessage(String(q.nextPrompt))}catch($){f.textContent=$ instanceof Error?$.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var cl=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},Zs=new cl;var Ou=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var xf=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},vf=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},ea=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=xf(e),t=vf(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},dl=e=>typeof e=="string"?e:e==null?"":String(e),Oo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:dl(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=dl(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:dl(t.text)}}},$u=e=>Array.isArray(e)?e.map(n=>String(n)):[],ta=e=>{let n=new Set($u(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set($u(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var wf=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Cf=e=>e.map(n=>({...n,streaming:!1})),Af=e=>e.map(n=>({...n,status:"complete"})),gi=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?wf(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?Cf(t.messages):void 0,artifacts:t.artifacts?Af(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var us=require("partial-json");function Sf(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Ef(e,n){if(!Sf(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function fi(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=(0,us.parse)(t,us.STR|us.OBJ),o=Ef(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function _u(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function hi(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=$r.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Uu(){let e=fi();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function yi(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function bi(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var Tf=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xi(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Tf}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=r,g.appendChild(w);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,g.appendChild(x),f.appendChild(g);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let L=1;L<=5;L++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-star-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${l[L-1]}`),$.title=l[L-1],$.dataset.rating=String(L),$.innerHTML=`
20
20
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
21
21
  <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>
22
22
  </svg>
23
- `,P.addEventListener("click",()=>{d=M,A.forEach((N,K)=>{let G=K<M;N.classList.toggle("selected",G),N.setAttribute("aria-checked",K===M-1?"true":"false")})}),A.push(P),w.appendChild(P)}f.appendChild(w);let I=null;if(p){let M=document.createElement("div");M.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),M.appendChild(I),f.appendChild(M)}let U=document.createElement("div");U.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=i,k.addEventListener("click",()=>{t==null||t(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(d===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let M=(I==null?void 0:I.value.trim())||void 0;await n(d,M),u.remove()}catch(M){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",M)}}),U.appendChild(k),U.appendChild(L),f.appendChild(U),u.appendChild(f),u}function za(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:u="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 E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=r,v.appendChild(E);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=s,v.appendChild(w),g.appendChild(v);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let U=document.createElement("span");U.className="persona-feedback-label-low",U.textContent=c;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=u,I.appendChild(U),I.appendChild(k);let L=document.createElement("div");L.className="persona-feedback-numbers";let M=[];for(let j=0;j<=10;j++){let ie=document.createElement("button");ie.type="button",ie.className="persona-feedback-rating-btn persona-feedback-number-btn",ie.setAttribute("role","radio"),ie.setAttribute("aria-checked","false"),ie.setAttribute("aria-label",`Rating ${j} out of 10`),ie.textContent=String(j),ie.dataset.rating=String(j),j<=6?ie.classList.add("persona-feedback-detractor"):j<=8?ie.classList.add("persona-feedback-passive"):ie.classList.add("persona-feedback-promoter"),ie.addEventListener("click",()=>{f=j,M.forEach((ve,ue)=>{ve.classList.toggle("selected",ue===j),ve.setAttribute("aria-checked",ue===j?"true":"false")})}),M.push(ie),L.appendChild(ie)}A.appendChild(I),A.appendChild(L),g.appendChild(A);let P=null;if(p){let j=document.createElement("div");j.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=o,P.rows=3,P.setAttribute("aria-label","Additional comments"),j.appendChild(P),g.appendChild(j)}let N=document.createElement("div");N.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=i,K.addEventListener("click",()=>{t==null||t(),d.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=a,G.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let j=(P==null?void 0:P.value.trim())||void 0;await n(f,j),d.remove()}catch(j){G.disabled=!1,G.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),N.appendChild(K),N.appendChild(G),g.appendChild(N),d.appendChild(g),d}var ns="persona-chat-history",_g=30*1e3,jg={"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 Ug(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let p=(s=jg[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${p}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function Va(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function qg(e){var n,t,r,s,o,a,i,p,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(p=(i=e.persist)==null?void 0:i.focusInput)!=null?p:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function zg(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Fi=e=>!e||typeof e!="object"?{}:{...e},lu=e=>e.map(n=>({...n,streaming:!1})),cu=(e,n,t)=>{let r=e!=null&&e.markdown?bo(e.markdown):null,s=_o(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,u,d;let a=(c=o.text)!=null?c:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let p;return e!=null&&e.postprocessMessage?p=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):r?p=r(a):p=$o(a),s?s(p):p}};function du(e){var i,p,c,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(p=e==null?void 0:e.iconSize)!=null?p:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=Ae(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,n.appendChild(d)}return n}var Ja=(e,n,t)=>{var bt,Mt,Ht,Xt,Ct,kt,Zt,un,pn,Jt,Gn,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,wl,Cl,Al,Sl,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Aa(n),s=_s.getForInstance(r.plugins);r.components&&Pr.registerAll(r.components);let o=ou(),a=(bt=r.storageAdapter)!=null?bt:Oa(),i={},p=null,c=!1,u=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:b}=m;return b&&(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")p=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return u(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=u(m);y.metadata&&(i=Fi(y.metadata)),(Mt=y.messages)!=null&&Mt.length&&(r={...r,initialMessages:y.messages}),(Ht=y.artifacts)!=null&&Ht.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Xt=y.selectedArtifactId)!=null?Xt:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=u({messages:[],metadata:{}});(Ct=l.messages)!=null&&Ct.length&&(r={...r,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:{},Wo()},g=r.actionParsers&&r.actionParsers.length?r.actionParsers:[js],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ko.message,ko.messageAndClick],E=Us({parsers:g,handlers:v,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let w=(Zt=(kt=r.launcher)==null?void 0:kt.enabled)!=null?Zt:!0,A=(pn=(un=r.launcher)==null?void 0:un.autoExpand)!=null?pn:!1,I=(Jt=r.autoFocusInput)!=null?Jt:!1,U=A,k=w,L=(nl=(Gn=r.layout)==null?void 0:Gn.header)==null?void 0:nl.layout,M=!1,P=w?A:!0,N=!1,K=null,G=()=>{N=!0,K&&clearTimeout(K),K=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},j=cu(r,E,G),ie=(ol=(rl=r.features)==null?void 0:rl.showReasoning)!=null?ol:!0,ve=(al=(sl=r.features)==null?void 0:sl.showToolCalls)!=null?al:!0,ue=(ll=(il=r.features)==null?void 0:il.showEventStreamToggle)!=null?ll:!1,Oe=(dl=(cl=r.features)==null?void 0:cl.scrollToBottom)!=null?dl:{},De=`${(ul=typeof r.persistState=="object"?(pl=r.persistState)==null?void 0:pl.keyPrefix:void 0)!=null?ul:"persona-"}event-stream`,Le=ue?new $s(De):null,Ne=(fl=(gl=(ml=r.features)==null?void 0:ml.eventStream)==null?void 0:gl.maxEvents)!=null?fl:2e3,de=ue?new Os(Ne,Le):null,X=null,ge=!1,Q=null,me=0;Le==null||Le.open().then(()=>de==null?void 0:de.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let pe={onCopy:l=>{var m,y;o.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(m=r.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(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},oe=(hl=r.statusIndicator)!=null?hl:{},Ie=l=>{var m,y,b,T;return l==="idle"?(m=oe.idleText)!=null?m:fn.idle:l==="connecting"?(y=oe.connectingText)!=null?y:fn.connecting:l==="connected"?(b=oe.connectedText)!=null?b:fn.connected:l==="error"?(T=oe.errorText)!=null?T:fn.error:fn[l]};function Pe(l,m,y,b){if(b==="idle"&&y.idleLink){l.textContent="";let T=document.createElement("a");T.href=y.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=m,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=m}let{wrapper:R,panel:z}=kp(r),ne=Lp(r,w),{container:_,body:q,messagesWrapper:le,suggestions:Ee,textarea:ee,sendButton:ae,sendButtonWrapper:Lt,composerForm:xt,statusText:Ke,introTitle:sn,introSubtitle:nt,closeButton:he,iconHolder:Ye,headerTitle:Ot,headerSubtitle:$t,header:D,footer:se,actionsRow:Re,leftActions:Ue,rightActions:Qe}=ne,Ze=ne.setSendButtonMode,H=ne.micButton,Te=ne.micButtonWrapper,Fe=ne.attachmentButton,ct=ne.attachmentButtonWrapper,Z=ne.attachmentInput,re=ne.attachmentPreviewsContainer;_.classList.add("persona-relative"),q.classList.add("persona-relative");let qe=12,dt=()=>{var l;return(l=Oe.label)!=null?l:""},Nt=()=>{var l;return(l=Oe.iconName)!=null?l:"arrow-down"},an=()=>Oe.enabled!==!1,ht=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");ht.type="button",ht.style.display="none",ht.setAttribute("data-persona-scroll-to-bottom","true");let ft=h("span","persona-flex persona-items-center"),it=h("span","");ht.append(ft,it),_.appendChild(ht);let Me=()=>{let m=se.style.display==="none"?0:se.offsetHeight;ht.style.bottom=`${m+qe}px`};Me();let st=()=>{let l=!!dt();ht.setAttribute("aria-label",dt()||"Jump to latest"),ht.title=dt(),ht.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),ft.innerHTML="";let m=Ae(Nt(),"14px","currentColor",2);m?(ft.appendChild(m),ft.style.display=""):ft.style.display="none",it.textContent=dt(),it.style.display=l?"":"none"};st();let ze=null,ln=null,cn=s.find(l=>l.renderHeader);if(cn!=null&&cn.renderHeader){let l=cn.renderHeader({config:r,defaultRenderer:()=>{let m=kr({config:r,showClose:w});return Eo(_,m,r),m.header},onClose:()=>_t(!1,"user")});if(l){let m=_.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),D=l)}}let $n=()=>{var m,y,b,T;if(!de)return;if(ge=!0,!X&&de&&(X=Kp({buffer:de,getFullHistory:()=>de.getAllFromStore(),onClose:()=>dn(),config:r,plugins:s})),X&&(q.style.display="none",(m=se.parentNode)==null||m.insertBefore(X.element,se),X.update()),rt){rt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let W=(T=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;W&&W.split(/\s+/).forEach(B=>B&&rt.classList.add(B))}let l=()=>{if(!ge)return;let W=Date.now();W-me>=200&&(X==null||X.update(),me=W),Q=requestAnimationFrame(l)};me=0,Q=requestAnimationFrame(l),wr(),o.emit("eventStream:opened",{timestamp:Date.now()})},dn=()=>{var l,m,y;if(ge){if(ge=!1,X&&X.element.remove(),q.style.display="",rt){rt.style.boxShadow="";let b=(y=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&rt.classList.remove(T))}Q!==null&&(cancelAnimationFrame(Q),Q=null),wr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},rt=null;if(ue){let l=(bl=(yl=r.features)==null?void 0:yl.eventStream)==null?void 0:bl.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:"");rt=h("button",m),rt.style.width="28px",rt.style.height="28px",rt.style.color=Mn.actionIconColor,rt.type="button",rt.setAttribute("aria-label","Event Stream"),rt.title="Event Stream";let y=Ae("activity","18px","currentColor",1.5);y&&rt.appendChild(y);let b=ne.clearChatButtonWrapper,T=ne.closeButtonWrapper,W=b||T;W&&W.parentNode===D?D.insertBefore(rt,W):D.appendChild(rt),rt.addEventListener("click",()=>{ge?dn():$n()})}let Rr=l=>{var b,T,W;let m=r.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=((b=m.allowedTypes)!=null?b:Mr).join(","),B.multiple=((T=m.maxFiles)!=null?T:4)>1,B.style.display="none",B.setAttribute("aria-label",(W=m.buttonTooltipText)!=null?W:"Attach files"),l.appendChild(B)}},kn=s.find(l=>l.renderComposer);if(kn!=null&&kn.renderComposer){let l=r.composer,m=kn.renderComposer({config:r,defaultRenderer:()=>Jo({config:r}).footer,onSubmit:y=>{var B;if(!F||F.isStreaming())return;let b=y.trim(),T=(B=ze==null?void 0:ze.hasAttachments())!=null?B:!1;if(!b&&!T)return;let W;T&&(W=[],W.push(...ze.getContentParts()),b&&W.push(As(b))),F.sendMessage(b,{contentParts:W}),T&&ze.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Z==null||Z.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((xl=r.voiceRecognition)==null?void 0:xl.enabled)===!0?()=>{ln==null||ln()}:void 0});m&&(se.replaceWith(m),se=m)}let no=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),b=l.querySelector("[data-persona-composer-submit]"),T=l.querySelector("[data-persona-composer-mic]"),W=l.querySelector("[data-persona-composer-status]");m&&(xt=m),y&&(ee=y),b&&(ae=b),T&&(H=T,Te=T.parentElement),W&&(Ke=W);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(Ee=B);let V=l.querySelector(".persona-attachment-button");V&&(Fe=V,ct=V.parentElement),Z=l.querySelector('input[type="file"]'),re=l.querySelector(".persona-attachment-previews");let $=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");$&&(Re=$)};Rr(se),no(se);let _n=(vl=r.layout)==null?void 0:vl.contentMaxWidth;if(_n&&xt&&(xt.style.maxWidth=_n,xt.style.marginLeft="auto",xt.style.marginRight="auto"),_n&&Ee&&(Ee.style.maxWidth=_n,Ee.style.marginLeft="auto",Ee.style.marginRight="auto"),_n&&re&&(re.style.maxWidth=_n,re.style.marginLeft="auto",re.style.marginRight="auto"),(wl=r.attachments)!=null&&wl.enabled&&Z&&re){ze=So.fromConfig(r.attachments),ze.setPreviewsContainer(re),Z.addEventListener("change",y=>{let b=y.target;ze==null||ze.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,m=du(l);_.appendChild(m)}(()=>{var b,T;let l=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},m=W=>{switch(W){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return le;case"footer-top":return Ee;case"composer":return xt;case"footer-bottom":return Ke;default:return null}},y=(W,B)=>{var V;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")D.insertBefore(B,D.firstChild);else if(W==="header-right")D.appendChild(B);else{let $=D.querySelector(".persona-flex-col");$?(V=$.parentNode)==null||V.insertBefore(B,$.nextSibling):D.appendChild(B)}break;case"body-top":{let $=q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");$?$.replaceWith(B):q.insertBefore(B,q.firstChild);break}case"body-bottom":q.appendChild(B);break;case"footer-top":Ee.replaceWith(B);break;case"footer-bottom":Ke.replaceWith(B);break;default:break}};for(let[W,B]of Object.entries(l))if(B)try{let V=B({config:r,defaultContent:()=>m(W)});V&&y(W,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,V)}})();let Hr=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=y.getAttribute("data-bubble-type");W==="reasoning"?(Go.has(T)?Go.delete(T):Go.add(T),Wp(T,b)):W==="tool"&&(Qo.has(T)?Qo.delete(T):Qo.add(T),Rp(T,b,r)),Vn.delete(T)};le.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Hr(l))}),le.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Hr(l))});let hr=new Map;le.addEventListener("click",l=>{var B;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let W=y.getAttribute("data-action");if(W==="copy"){let $=F.getMessages().find(Se=>Se.id===T);if($&&pe.onCopy){let Se=$.content||"";navigator.clipboard.writeText(Se).then(()=>{y.classList.add("persona-message-action-success");let ye=Ae("check",14,"currentColor",2);ye&&(y.innerHTML="",y.appendChild(ye)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ke=Ae("copy",14,"currentColor",2);ke&&(y.innerHTML="",y.appendChild(ke))},2e3)}).catch(ye=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ye)}),pe.onCopy($)}}else if(W==="upvote"||W==="downvote"){let $=((B=hr.get(T))!=null?B:null)===W,Se=W==="upvote"?"thumbs-up":"thumbs-down";if($){hr.delete(T),y.classList.remove("persona-message-action-active");let ye=Ae(Se,14,"currentColor",2);ye&&(y.innerHTML="",y.appendChild(ye))}else{let ye=W==="upvote"?"downvote":"upvote",ke=b.querySelector(`[data-action="${ye}"]`);if(ke){ke.classList.remove("persona-message-action-active");let tt=Ae(ye==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(ke.innerHTML="",ke.appendChild(tt))}hr.set(T,W),y.classList.add("persona-message-action-active");let be=Ae(Se,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(be)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Je=F.getMessages().find(ut=>ut.id===T);Je&&pe.onFeedback&&pe.onFeedback({type:W,messageId:Je.id,message:Je})}}}),le.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=y.getAttribute("data-approval-action");if(!W)return;let B=W==="approve"?"approved":"denied",$=F.getMessages().find(ye=>ye.id===T);if(!($!=null&&$.approval))return;let Se=b.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(ke=>{ke.disabled=!0,ke.style.opacity="0.5",ke.style.cursor="not-allowed"}),F.resolveApproval($.approval,B)});let yt=null,Ln=null,In={artifacts:[],selectedId:null},hn=!1,It={current:null};le.addEventListener("click",l=>{var ke,be,$e,Je,ut;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||(($e=(be=(ke=r.features)==null?void 0:ke.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:$e.call(be,{type:"download",artifactId:b}))===!0)return;let W=F.getArtifactById(b),B=W==null?void 0:W.markdown,V=(W==null?void 0:W.title)||"artifact";if(!B){let tt=y.closest("[data-open-artifact]"),St=tt==null?void 0:tt.closest("[data-message-id]"),Et=St==null?void 0:St.getAttribute("data-message-id");if(Et){let S=F.getMessages().find(xe=>xe.id===Et);if(S!=null&&S.rawContent)try{let xe=JSON.parse(S.rawContent);B=(Je=xe==null?void 0:xe.props)==null?void 0:Je.markdown,V=((ut=xe==null?void 0:xe.props)==null?void 0:ut.title)||V}catch{}}}if(!B)return;let $=new Blob([B],{type:"text/markdown"}),Se=URL.createObjectURL($),ye=document.createElement("a");ye.href=Se,ye.download=`${V}.md`,ye.click(),URL.revokeObjectURL(Se)}),le.addEventListener("click",l=>{var W,B,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((V=(B=(W=r.features)==null?void 0:W.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:V.call(B,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),hn=!1,F.selectArtifact(b),Rn())}),le.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let jn=ne.composerOverlay,Un=(l,m,y)=>{var V,$,Se,ye;let b=m.trim();if(!b||!It.current)return;let T=(V=l.getAttribute("data-tool-call-id"))!=null?V:"",W=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:y.structured,values:($=y.values)!=null?$:y.source==="multi"?b.split(", "):[b],isFreeText:W,source:y.source},bubbles:!0,composed:!0})),Zr(jn,T);let B=It.current.getMessages().find(ke=>{var be;return((be=ke.toolCall)==null?void 0:be.id)===T});(Se=B==null?void 0:B.agentMetadata)!=null&&Se.awaitingLocalTool?It.current.resolveAskUserQuestion(B,(ye=y.structured)!=null?ye:b):It.current.sendMessage(b)},Pn=l=>{var T;let m=It.current;if(!m)return;let y=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",b=m.getMessages().find(W=>{var B;return((B=W.toolCall)==null?void 0:B.id)===y});b&&m.persistAskUserQuestionProgress(b,{answers:Ba(l,b),currentIndex:er(l)})},Br=l=>Object.entries(l).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),yr=l=>{var T,W,B;if(((W=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let m=er(l),y=Xo(l);if(m>=y-1)return;let b=(B=It.current)==null?void 0:B.getMessages().find(V=>{var $;return(($=V.toolCall)==null?void 0:$.id)===l.getAttribute("data-tool-call-id")});b&&(Da(l,b,r,m+1),Pn(l))};jn.addEventListener("click",l=>{var W,B,V,$,Se,ye,ke,be,$e,Je,ut,tt,St,Et;let y=l.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=y.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let Be=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Zr(jn,Be);let S=(B=It.current)==null?void 0:B.getMessages().find(xe=>{var Ce;return((Ce=xe.toolCall)==null?void 0:Ce.id)===Be});(V=S==null?void 0:S.agentMetadata)!=null&&V.awaitingLocalTool&&(($=It.current)==null||$.markAskUserQuestionResolved(S),(Se=It.current)==null||Se.resolveAskUserQuestion(S,"(dismissed)"));return}if(T==="pick"){let Be=y.getAttribute("data-option-label");if(!Be)return;let S=b.getAttribute("data-multi-select")==="true",xe=Xr(b);if(xe&&S){let Ce=Mo(b)[er(b)],je=new Set(Array.isArray(Ce)?Ce:[]);je.has(Be)?je.delete(Be):je.add(Be),eo(b,Array.from(je)),Pn(b);return}if(xe){eo(b,Be),Pn(b),yr(b);return}if(S){let Ce=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",Ce?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!Ce);let je=b.querySelector('[data-ask-user-action="submit-multi"]');je&&(je.disabled=Pi(b).length===0);return}Un(b,Be,{source:"pick",values:[Be]});return}if(T==="submit-multi"){let Be=Pi(b);if(Be.length===0)return;Un(b,Be.join(", "),{source:"multi",values:Be});return}if(T==="open-free-text"){let Be=b.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let S=Be.querySelector('[data-ask-free-text-input="true"]');S==null||S.focus()}return}if(T==="focus-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(T==="submit-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]'),S=(ye=Be==null?void 0:Be.value)!=null?ye:"";if(!S.trim())return;if(Xr(b)){eo(b,S.trim()),Pn(b),yr(b);return}Un(b,S,{source:"free-text"});return}if(T==="next"||T==="back"){if(!It.current)return;let Be=(ke=b.getAttribute("data-tool-call-id"))!=null?ke:"",S=It.current.getMessages().find(_e=>{var we;return((we=_e.toolCall)==null?void 0:we.id)===Be});if(!S)return;let xe=b.querySelector('[data-ask-free-text-input="true"]'),Ce=($e=(be=xe==null?void 0:xe.value)==null?void 0:be.trim())!=null?$e:"";if(Ce){let _e=Mo(b)[er(b)];(typeof _e!="string"||_e!==Ce)&&eo(b,Ce)}let je=T==="next"?1:-1,vt=er(b)+je;Da(b,S,r,vt),Pn(b);return}if(T==="submit-all"){if(!It.current)return;let Be=(Je=b.getAttribute("data-tool-call-id"))!=null?Je:"",S=It.current.getMessages().find(_e=>{var we;return((we=_e.toolCall)==null?void 0:we.id)===Be});if(!S)return;let xe=b.querySelector('[data-ask-free-text-input="true"]'),Ce=(tt=(ut=xe==null?void 0:xe.value)==null?void 0:ut.trim())!=null?tt:"";Ce&&eo(b,Ce);let je=Ba(b,S);It.current.persistAskUserQuestionProgress(S,{answers:je,currentIndex:er(b)});let vt=Br(je);Un(b,vt||"(submitted)",{source:"submit-all",structured:je});return}if(T==="skip"){if(!It.current)return;let Be=(St=b.getAttribute("data-tool-call-id"))!=null?St:"",S=It.current.getMessages().find(we=>{var en;return((en=we.toolCall)==null?void 0:en.id)===Be});if(!S)return;let xe=Xr(b),Ce=er(b),je=Xo(b),vt=Ce>=je-1;if(!xe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Zr(jn,Be),(Et=S.agentMetadata)!=null&&Et.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(S),It.current.resolveAskUserQuestion(S,"(dismissed)"));return}eo(b,"");let _e=b.querySelector('[data-ask-free-text-input="true"]');if(_e&&(_e.value=""),vt){let we=Ba(b,S),en=Br(we);Un(b,en||"(skipped)",{source:"submit-all",structured:we});return}Da(b,S,r,Ce+1),Pn(b);return}}),jn.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let y=l.target;if(!((W=y.matches)!=null&&W.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let T=y.value;if(T.trim()){if(Xr(b)){eo(b,T.trim()),Pn(b),yr(b);return}Un(b,T,{source:"free-text"})}});let Dr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let y=jn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),W=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",Dr);let Wn=null,Pt=null,yn=null,qn=null,Nr=()=>{};function br(){qn==null||qn(),qn=null}let Fr=()=>{var B;if(!Wn||!Pt)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){Pt.style.removeProperty("position"),Pt.style.removeProperty("left"),Pt.style.removeProperty("top"),Pt.style.removeProperty("bottom"),Pt.style.removeProperty("width"),Pt.style.removeProperty("z-index");return}let b=Wn.firstElementChild;if(!b||b===Pt)return;let T=10;Pt.style.position="absolute",Pt.style.top="0",Pt.style.bottom="0",Pt.style.width=`${T}px`,Pt.style.zIndex="5";let W=b.offsetWidth-T/2;Pt.style.left=`${Math.max(0,W)}px`},lr=()=>{},Rn=()=>{var y,b,T,W,B;if(!yt||!tr(r))return;Na(e,r),Fa(e,r),lr();let l=(W=(T=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?W:520,m=z.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),yt.update(In),hn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(B=yt.backdrop)==null||B.classList.add("persona-hidden")):In.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),Nr()};if(tr(r)){z.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(_),yt=Yp(r,{onSelect:y=>{var b;return(b=It.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{hn=!0,Rn()}}),yt.element.classList.add("persona-hidden"),Wn=m,m.appendChild(l),m.appendChild(yt.element),yt.backdrop&&z.appendChild(yt.backdrop),z.appendChild(m),Nr=()=>{var b,T,W,B;if(!Wn||!yt)return;if(!(((W=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:W.resizable)===!0)){yn==null||yn(),yn=null,br(),Pt&&(Pt.remove(),Pt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Pt){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let $=e.ownerDocument,Se=(B=$.defaultView)!=null?B:window,ye=ke=>{var St,Et;if(!yt||ke.button!==0||e.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;ke.preventDefault(),br();let be=ke.clientX,$e=yt.element.getBoundingClientRect().width,Je=(Et=(St=r.features)==null?void 0:St.artifacts)==null?void 0:Et.layout,ut=Be=>{let S=Wn.getBoundingClientRect().width,xe=e.classList.contains("persona-artifact-appearance-seamless"),Ce=xe?0:tu(Wn,Se),je=xe?0:V.getBoundingClientRect().width||6,vt=$e-(Be.clientX-be),_e=nu(vt,S,Ce,je,Je==null?void 0:Je.resizableMinWidth,Je==null?void 0:Je.resizableMaxWidth);yt.element.style.width=`${_e}px`,yt.element.style.maxWidth="none",Fr()},tt=()=>{$.removeEventListener("pointermove",ut),$.removeEventListener("pointerup",tt),$.removeEventListener("pointercancel",tt),qn=null;try{V.releasePointerCapture(ke.pointerId)}catch{}};qn=tt,$.addEventListener("pointermove",ut),$.addEventListener("pointerup",tt),$.addEventListener("pointercancel",tt);try{V.setPointerCapture(ke.pointerId)}catch{}};V.addEventListener("pointerdown",ye),Pt=V,Wn.insertBefore(V,yt.element),yn=()=>{V.removeEventListener("pointerdown",ye)}}if(Pt){let V=In.artifacts.length>0&&!hn;Pt.classList.toggle("persona-hidden",!V),Fr()}},lr=()=>{var Se,ye,ke,be,$e,Je,ut,tt,St,Et,Be,S,xe,Ce;if(!w||!yt||((ye=(Se=r.launcher)==null?void 0:Se.sidebarMode)!=null?ye:!1)||Yt(r)&&Zn(r).reveal==="emerge")return;let b=(ke=e.ownerDocument.defaultView)!=null?ke:window,T=($e=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?$e:!0,W=(ut=(Je=r.launcher)==null?void 0:Je.mobileBreakpoint)!=null?ut:640;if(T&&b.innerWidth<=W||!eu(r,w))return;let B=(Et=(St=(tt=r.launcher)==null?void 0:tt.width)!=null?St:r.launcherWidth)!=null?Et:On,V=(Ce=(xe=(S=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:S.layout)==null?void 0:xe.expandedPanelWidth)!=null?Ce:"min(720px, calc(100vw - 24px))";In.artifacts.length>0&&!hn?(z.style.width=V,z.style.maxWidth=V):(z.style.width=B,z.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(Ln=new ResizeObserver(()=>{Rn()}),Ln.observe(z))}else z.appendChild(_);e.appendChild(R);let cr=()=>{var _e,we,en,tn,Qn,nn,Bt,An,Kt,Ge,mt,pr,ur,uo,mo,go,Fo,Oo,Xe,Yn,Xn,mr,qt;let l=Yt(r),m=(we=(_e=r.launcher)==null?void 0:_e.sidebarMode)!=null?we:!1,y=l||m||((tn=(en=r.launcher)==null?void 0:en.fullHeight)!=null?tn:!1),b=((Qn=r.launcher)==null?void 0:Qn.enabled)===!1,T=(Bt=(nn=r.theme)==null?void 0:nn.components)==null?void 0:Bt.panel,W=Ls(r),B=(Wt,rn)=>{var Sn;return Wt==null||Wt===""?rn:(Sn=Ms(W,Wt))!=null?Sn:Wt},V=(An=e.ownerDocument.defaultView)!=null?An:window,$=(Ge=(Kt=r.launcher)==null?void 0:Kt.mobileFullscreen)!=null?Ge:!0,Se=(pr=(mt=r.launcher)==null?void 0:mt.mobileBreakpoint)!=null?pr:640,ye=V.innerWidth<=Se,ke=$&&ye&&w,be=(uo=(ur=r.launcher)==null?void 0:ur.position)!=null?uo:"bottom-left",$e=be==="bottom-left"||be==="top-left",Je=(go=(mo=r.launcher)==null?void 0:mo.zIndex)!=null?go:Tn,ut=m||ke?"none":"1px solid var(--persona-border)",tt=ke?"none":m?$e?"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&&!ke&&(tt="none",ut="none");let St=m||ke?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Et=B(T==null?void 0:T.border,ut),Be=B(T==null?void 0:T.shadow,tt),S=B(T==null?void 0:T.borderRadius,St),xe=q.scrollTop;e.style.cssText="",R.style.cssText="",z.style.cssText="",_.style.cssText="",q.style.cssText="",se.style.cssText="";let Ce=()=>{var rn;if(xe<=0)return;((rn=q.ownerDocument.defaultView)!=null?rn:window).requestAnimationFrame(()=>{if(q.scrollTop===xe)return;let Sn=q.scrollHeight-q.clientHeight;Sn<=0||(q.scrollTop=Math.min(xe,Sn))})};if(ke){R.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"),R.style.cssText=`
23
+ `,$.addEventListener("click",()=>{p=L,A.forEach((q,_)=>{let B=_<L;q.classList.toggle("selected",B),q.setAttribute("aria-checked",_===L-1?"true":"false")})}),A.push($),M.appendChild($)}f.appendChild(M);let P=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=o,P.rows=3,P.setAttribute("aria-label","Additional comments"),L.appendChild(P),f.appendChild(L)}let N=document.createElement("div");N.className="persona-feedback-actions";let R=document.createElement("button");R.type="button",R.className="persona-feedback-btn persona-feedback-btn-skip",R.textContent=i,R.addEventListener("click",()=>{t==null||t(),u.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(p===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let L=(P==null?void 0:P.value.trim())||void 0;await n(p,L),u.remove()}catch(L){T.disabled=!1,T.textContent=a,console.error("[CSAT Feedback] Failed to submit:",L)}}),N.appendChild(R),N.appendChild(T),f.appendChild(N),u.appendChild(f),u}function vi(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,w.appendChild(x);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,w.appendChild(M),g.appendChild(w);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let N=document.createElement("span");N.className="persona-feedback-label-low",N.textContent=l;let R=document.createElement("span");R.className="persona-feedback-label-high",R.textContent=u,P.appendChild(N),P.appendChild(R);let T=document.createElement("div");T.className="persona-feedback-numbers";let L=[];for(let O=0;O<=10;O++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${O} out of 10`),G.textContent=String(O),G.dataset.rating=String(O),O<=6?G.classList.add("persona-feedback-detractor"):O<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{f=O,L.forEach((re,Ee)=>{re.classList.toggle("selected",Ee===O),re.setAttribute("aria-checked",Ee===O?"true":"false")})}),L.push(G),T.appendChild(G)}A.appendChild(P),A.appendChild(T),g.appendChild(A);let $=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=o,$.rows=3,$.setAttribute("aria-label","Additional comments"),O.appendChild($),g.appendChild(O)}let q=document.createElement("div");q.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{t==null||t(),p.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let O=($==null?void 0:$.value.trim())||void 0;await n(f,O),p.remove()}catch(O){B.disabled=!1,B.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),q.appendChild(_),q.appendChild(B),g.appendChild(q),p.appendChild(g),p}var ms="persona-chat-history",kf=30*1e3,Mf={"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 Lf(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=Mf[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function wi(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function Pf(e){var n,t,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function If(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var pl=e=>!e||typeof e!="object"?{}:{...e},ju=e=>e.map(n=>({...n,streaming:!1})),qu=(e,n,t)=>{let r=e!=null&&e.markdown?Mo(e.markdown):null,s=Qo(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=Lo(a),s?s(d):d}};function zu(e){var i,d,l,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=ge(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,n.appendChild(p)}return n}var Ci=(e,n,t)=>{var Il,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,Ul,jl,ql,zl,Vl,Jl,Kl,Gl,Ql,Xl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=_a(n),s=Zs.getForInstance(r.plugins);r.components&&$r.registerAll(r.components);let o=Ou(),i=r.persistState===!1?null:(Il=r.storageAdapter)!=null?Il:gi(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:b}=m;return b&&(u=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=c!=null?c:{messages:[],metadata:{}},y=p(m);y.metadata&&(d=pl(y.metadata)),(Wl=y.messages)!=null&&Wl.length&&(r={...r,initialMessages:y.messages}),(Rl=y.artifacts)!=null&&Rl.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Hl=y.selectedArtifactId)!=null?Hl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=p({messages:[],metadata:{}});(Bl=c.messages)!=null&&Bl.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,g=c=>{var y;d=(y=c({...d}))!=null?y:{},jo()},w=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ea],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Oo.message,Oo.messageAndClick],M=ta({parsers:w,handlers:x,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let A=(Nl=(Dl=r.launcher)==null?void 0:Dl.enabled)!=null?Nl:!0,P=(Ol=(Fl=r.launcher)==null?void 0:Fl.autoExpand)!=null?Ol:!1,N=($l=r.autoFocusInput)!=null?$l:!1,R=P,T=A,L=(Ul=(_l=r.layout)==null?void 0:_l.header)==null?void 0:Ul.layout,$=!1,q=()=>ao(r),_=()=>A||q(),B=q()?!1:A?P:!0,O=!1,G=null,re=()=>{O=!0,G&&clearTimeout(G),G=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},Ee=qu(r,M,re),Re=(ql=(jl=r.features)==null?void 0:jl.showReasoning)!=null?ql:!0,Ue=(Vl=(zl=r.features)==null?void 0:zl.showToolCalls)!=null?Vl:!0,he=(Kl=(Jl=r.features)==null?void 0:Jl.showEventStreamToggle)!=null?Kl:!1,ue=(Ql=(Gl=r.features)==null?void 0:Gl.scrollToBottom)!=null?Ql:{},je=`${(Yl=typeof r.persistState=="object"?(Xl=r.persistState)==null?void 0:Xl.keyPrefix:void 0)!=null?Yl:"persona-"}event-stream`,te=he?new Ys(je):null,ve=(tc=(ec=(Zl=r.features)==null?void 0:Zl.eventStream)==null?void 0:ec.maxEvents)!=null?tc:2e3,X=he?new Xs(ve,te):null,oe=null,Le=!1,ie=null,De=0;te==null||te.open().then(()=>X==null?void 0:X.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let He={onCopy:c=>{var m,y;o.emit("message:copy",c),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onCopy)==null||y.call(m,c)},onFeedback:c=>{var m,y;o.emit("message:feedback",c),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,c)}},K=(nc=r.statusIndicator)!=null?nc:{},Ne=c=>{var m,y,b,k;return c==="idle"?(m=K.idleText)!=null?m:hn.idle:c==="connecting"?(y=K.connectingText)!=null?y:hn.connecting:c==="connected"?(b=K.connectedText)!=null?b:hn.connected:c==="error"?(k=K.errorText)!=null?k:hn.error:hn[c]};function Be(c,m,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=m,k.style.color="inherit",k.style.textDecoration="none",c.appendChild(k)}else c.textContent=m}let{wrapper:Q,panel:J,pillRoot:we}=cu(r),de=du(r,_()),{container:ne,body:fe,messagesWrapper:Xe,suggestions:$t,textarea:le,sendButton:Fe,sendButtonWrapper:ln,composerForm:It,statusText:zt,introTitle:wr,introSubtitle:pr,closeButton:I,iconHolder:se,headerTitle:Ie,headerSubtitle:ze,header:Oe,footer:$e,actionsRow:et,leftActions:wt,rightActions:_t}=de,Vt=de.setSendButtonMode,H=de.micButton,ae=de.micButtonWrapper,Ce=de.attachmentButton,ut=de.attachmentButtonWrapper,Ke=de.attachmentInput,Ft=de.attachmentPreviewsContainer;ne.classList.add("persona-relative"),fe.classList.add("persona-relative");let cn=12,Ct=()=>{var c;return(c=ue.label)!=null?c:""},yt=()=>{var c;return(c=ue.iconName)!=null?c:"arrow-down"},Et=()=>ue.enabled!==!1,lt=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");lt.type="button",lt.style.display="none",lt.setAttribute("data-persona-scroll-to-bottom","true");let Jt=h("span","persona-flex persona-items-center"),Cr=h("span","");lt.append(Jt,Cr),ne.appendChild(lt);let qn=()=>{let m=$e.style.display==="none"?0:$e.offsetHeight;lt.style.bottom=`${m+cn}px`};qn();let Ur=()=>{let c=!!Ct();lt.setAttribute("aria-label",Ct()||"Jump to latest"),lt.title=Ct(),lt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Jt.innerHTML="";let m=ge(yt(),"14px","currentColor",2);m?(Jt.appendChild(m),Jt.style.display=""):Jt.style.display="none",Cr.textContent=Ct(),Cr.style.display=c?"":"none"};Ur();let vt=null,ur=null,mr=s.find(c=>c.renderHeader);if(mr!=null&&mr.renderHeader){let c=mr.renderHeader({config:r,defaultRenderer:()=>{let m=Nr({config:r,showClose:_()});return Do(ne,m,r),m.header},onClose:()=>Wt(!1,"user")});if(c){let m=ne.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Oe=c)}}let Ar=()=>{var m,y,b,k;if(!X)return;if(Le=!0,!oe&&X&&(oe=Lu({buffer:X,getFullHistory:()=>X.getAllFromStore(),onClose:()=>er(),config:r,plugins:s})),oe&&(fe.style.display="none",(m=$e.parentNode)==null||m.insertBefore(oe.element,$e),oe.update()),dt){dt.style.boxShadow=`inset 0 0 0 1.5px ${En.actionIconColor}`;let D=(k=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:k.toggleButtonActive;D&&D.split(/\s+/).forEach(F=>F&&dt.classList.add(F))}let c=()=>{if(!Le)return;let D=Date.now();D-De>=200&&(oe==null||oe.update(),De=D),ie=requestAnimationFrame(c)};De=0,ie=requestAnimationFrame(c),Lr(),o.emit("eventStream:opened",{timestamp:Date.now()})},er=()=>{var c,m,y;if(Le){if(Le=!1,oe&&oe.element.remove(),fe.style.display="",dt){dt.style.boxShadow="";let b=(y=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(k=>k&&dt.classList.remove(k))}ie!==null&&(cancelAnimationFrame(ie),ie=null),Lr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},dt=null;if(he){let c=(oc=(rc=r.features)==null?void 0:rc.eventStream)==null?void 0:oc.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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");dt=h("button",m),dt.style.width="28px",dt.style.height="28px",dt.style.color=En.actionIconColor,dt.type="button",dt.setAttribute("aria-label","Event Stream"),dt.title="Event Stream";let y=ge("activity","18px","currentColor",1.5);y&&dt.appendChild(y);let b=de.clearChatButtonWrapper,k=de.closeButtonWrapper,D=b||k;D&&D.parentNode===Oe?Oe.insertBefore(dt,D):Oe.appendChild(dt),dt.addEventListener("click",()=>{Le?er():Ar()})}let go=c=>{var b,k,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let F=c.querySelector("[data-persona-composer-form]");F!=null&&F.parentNode?F.parentNode.insertBefore(y,F):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let F=h("input");F.type="file",F.accept=((b=m.allowedTypes)!=null?b:Dr).join(","),F.multiple=((k=m.maxFiles)!=null?k:4)>1,F.style.display="none",F.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(F)}},gr=s.find(c=>c.renderComposer);if(gr!=null&&gr.renderComposer){let c=r.composer,m=gr.renderComposer({config:r,defaultRenderer:()=>os({config:r}).footer,onSubmit:y=>{var F;if(!U||U.isStreaming())return;let b=y.trim(),k=(F=vt==null?void 0:vt.hasAttachments())!=null?F:!1;if(!b&&!k)return;As();let D;k&&(D=[],D.push(...vt.getContentParts()),b&&D.push(Hs(b))),U.sendMessage(b,{contentParts:D}),k&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((sc=r.voiceRecognition)==null?void 0:sc.enabled)===!0?()=>{ur==null||ur()}:void 0});m&&($e.replaceWith(m),$e=m)}let fo=c=>{let m=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),k=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");m&&(It=m),y&&(le=y),b&&(Fe=b),k&&(H=k,ae=k.parentElement),D&&(zt=D);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&($t=F);let V=c.querySelector(".persona-attachment-button");V&&(Ce=V,ut=V.parentElement),Ke=c.querySelector('input[type="file"]'),Ft=c.querySelector(".persona-attachment-previews");let W=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");W&&(et=W)};go($e),fo($e);let Tn=(dc=(ac=r.layout)==null?void 0:ac.contentMaxWidth)!=null?dc:q()?(cc=(lc=(ic=r.launcher)==null?void 0:ic.composerBar)==null?void 0:lc.contentMaxWidth)!=null?cc:"720px":void 0;if(Tn&&(Xe.style.maxWidth=Tn,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%"),Tn&&It&&!q()&&(It.style.maxWidth=Tn,It.style.marginLeft="auto",It.style.marginRight="auto"),Tn&&$t&&!q()&&($t.style.maxWidth=Tn,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Tn&&Ft&&!q()&&(Ft.style.maxWidth=Tn,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),(pc=r.attachments)!=null&&pc.enabled&&Ke&&Ft){vt=Bo.fromConfig(r.attachments),vt.setPreviewsContainer(Ft),Ke.addEventListener("change",y=>{let b=y.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=zu(c);ne.appendChild(m)}(()=>{var b,k;let c=(k=(b=r.layout)==null?void 0:b.slots)!=null?k:{},m=D=>{switch(D){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Xe;case"footer-top":return $t;case"composer":return It;case"footer-bottom":return zt;default:return null}},y=(D,F)=>{var V;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Oe.insertBefore(F,Oe.firstChild);else if(D==="header-right")Oe.appendChild(F);else{let W=Oe.querySelector(".persona-flex-col");W?(V=W.parentNode)==null||V.insertBefore(F,W.nextSibling):Oe.appendChild(F)}break;case"body-top":{let W=fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");W?W.replaceWith(F):fe.insertBefore(F,fe.firstChild);break}case"body-bottom":fe.appendChild(F);break;case"footer-top":$t.replaceWith(F);break;case"footer-bottom":zt.replaceWith(F);break;default:break}};for(let[D,F]of Object.entries(c))if(F)try{let V=F({config:r,defaultContent:()=>m(D)});V&&y(D,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,V)}})();let jr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let D=y.getAttribute("data-bubble-type");D==="reasoning"?(as.has(k)?as.delete(k):as.add(k),mu(k,b)):D==="tool"&&(is.has(k)?is.delete(k):is.add(k),gu(k,b,r)),On.delete(k)};Xe.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jr(c))}),Xe.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jr(c))});let Sr=new Map;Xe.addEventListener("click",c=>{var F;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let k=b.getAttribute("data-actions-for");if(!k)return;let D=y.getAttribute("data-action");if(D==="copy"){let W=U.getMessages().find(be=>be.id===k);if(W&&He.onCopy){let be=W.content||"";navigator.clipboard.writeText(be).then(()=>{y.classList.add("persona-message-action-success");let ce=ge("check",14,"currentColor",2);ce&&(y.innerHTML="",y.appendChild(ce)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Z=ge("copy",14,"currentColor",2);Z&&(y.innerHTML="",y.appendChild(Z))},2e3)}).catch(ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ce)}),He.onCopy(W)}}else if(D==="upvote"||D==="downvote"){let W=((F=Sr.get(k))!=null?F:null)===D,be=D==="upvote"?"thumbs-up":"thumbs-down";if(W){Sr.delete(k),y.classList.remove("persona-message-action-active");let ce=ge(be,14,"currentColor",2);ce&&(y.innerHTML="",y.appendChild(ce))}else{let ce=D==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${ce}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Ve=ge(ce==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ve&&(Z.innerHTML="",Z.appendChild(Ve))}Sr.set(k,D),y.classList.add("persona-message-action-active");let me=ge(be,14,"currentColor",2);me&&(me.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(me)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let We=U.getMessages().find(Ze=>Ze.id===k);We&&He.onFeedback&&He.onFeedback({type:D,messageId:We.id,message:We})}}}),Xe.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let D=y.getAttribute("data-approval-action");if(!D)return;let F=D==="approve"?"approved":"denied",W=U.getMessages().find(ce=>ce.id===k);if(!(W!=null&&W.approval))return;let be=b.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),U.resolveApproval(W.approval,F)});let gt=null,Wn=null,Rn={artifacts:[],selectedId:null},bn=!1,Tt={current:null};Xe.addEventListener("click",c=>{var Z,me,xe,We,Ze;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((xe=(me=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:me.onArtifactAction)==null?void 0:xe.call(me,{type:"download",artifactId:b}))===!0)return;let D=U.getArtifactById(b),F=D==null?void 0:D.markdown,V=(D==null?void 0:D.title)||"artifact";if(!F){let Ve=y.closest("[data-open-artifact]"),rt=Ve==null?void 0:Ve.closest("[data-message-id]"),ot=rt==null?void 0:rt.getAttribute("data-message-id");if(ot){let Se=U.getMessages().find(_e=>_e.id===ot);if(Se!=null&&Se.rawContent)try{let _e=JSON.parse(Se.rawContent);F=(We=_e==null?void 0:_e.props)==null?void 0:We.markdown,V=((Ze=_e==null?void 0:_e.props)==null?void 0:Ze.title)||V}catch{}}}if(!F)return;let W=new Blob([F],{type:"text/markdown"}),be=URL.createObjectURL(W),ce=document.createElement("a");ce.href=be,ce.download=`${V}.md`,ce.click(),URL.revokeObjectURL(be)}),Xe.addEventListener("click",c=>{var D,F,V;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((V=(F=(D=r.features)==null?void 0:D.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:V.call(F,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),bn=!1,U.selectArtifact(b),Dn())}),Xe.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let zn=de.composerOverlay,Vn=(c,m,y)=>{var V,W,be,ce;let b=m.trim();if(!b||!Tt.current)return;let k=(V=c.getAttribute("data-tool-call-id"))!=null?V:"",D=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:b,answers:y.structured,values:(W=y.values)!=null?W:y.source==="multi"?b.split(", "):[b],isFreeText:D,source:y.source},bubbles:!0,composed:!0})),po(zn,k);let F=Tt.current.getMessages().find(Z=>{var me;return((me=Z.toolCall)==null?void 0:me.id)===k});(be=F==null?void 0:F.agentMetadata)!=null&&be.awaitingLocalTool?Tt.current.resolveAskUserQuestion(F,(ce=y.structured)!=null?ce:b):Tt.current.sendMessage(b)},Hn=c=>{var k;let m=Tt.current;if(!m)return;let y=(k=c.getAttribute("data-tool-call-id"))!=null?k:"",b=m.getMessages().find(D=>{var F;return((F=D.toolCall)==null?void 0:F.id)===y});b&&m.persistAskUserQuestionProgress(b,{answers:di(c,b),currentIndex:Yn(c)})},qr=c=>Object.entries(c).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Er=c=>{var k,D,F;if(((D=(k=r.features)==null?void 0:k.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let m=Yn(c),y=cs(c);if(m>=y-1)return;let b=(F=Tt.current)==null?void 0:F.getMessages().find(V=>{var W;return((W=V.toolCall)==null?void 0:W.id)===c.getAttribute("data-tool-call-id")});b&&(pi(c,b,r,m+1),Hn(c))};zn.addEventListener("click",c=>{var D,F,V,W,be,ce,Z,me,xe,We,Ze,Ve,rt,ot;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let k=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),k==="dismiss"){let Te=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Te},bubbles:!0,composed:!0})),po(zn,Te);let Se=(F=Tt.current)==null?void 0:F.getMessages().find(_e=>{var E;return((E=_e.toolCall)==null?void 0:E.id)===Te});(V=Se==null?void 0:Se.agentMetadata)!=null&&V.awaitingLocalTool&&((W=Tt.current)==null||W.markAskUserQuestionResolved(Se),(be=Tt.current)==null||be.resolveAskUserQuestion(Se,"(dismissed)"));return}if(k==="pick"){let Te=y.getAttribute("data-option-label");if(!Te)return;let Se=b.getAttribute("data-multi-select")==="true",_e=co(b);if(_e&&Se){let E=Fo(b)[Yn(b)],Ae=new Set(Array.isArray(E)?E:[]);Ae.has(Te)?Ae.delete(Te):Ae.add(Te),uo(b,Array.from(Ae)),Hn(b);return}if(_e){uo(b,Te),Hn(b),Er(b);return}if(Se){let E=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",E?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!E);let Ae=b.querySelector('[data-ask-user-action="submit-multi"]');Ae&&(Ae.disabled=ol(b).length===0);return}Vn(b,Te,{source:"pick",values:[Te]});return}if(k==="submit-multi"){let Te=ol(b);if(Te.length===0)return;Vn(b,Te.join(", "),{source:"multi",values:Te});return}if(k==="open-free-text"){let Te=b.querySelector('[data-ask-free-text-row="true"]');if(Te){Te.classList.remove("persona-hidden");let Se=Te.querySelector('[data-ask-free-text-input="true"]');Se==null||Se.focus()}return}if(k==="focus-free-text"){let Te=b.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus();return}if(k==="submit-free-text"){let Te=b.querySelector('[data-ask-free-text-input="true"]'),Se=(ce=Te==null?void 0:Te.value)!=null?ce:"";if(!Se.trim())return;if(co(b)){uo(b,Se.trim()),Hn(b),Er(b);return}Vn(b,Se,{source:"free-text"});return}if(k==="next"||k==="back"){if(!Tt.current)return;let Te=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Se=Tt.current.getMessages().find(qe=>{var ye;return((ye=qe.toolCall)==null?void 0:ye.id)===Te});if(!Se)return;let _e=b.querySelector('[data-ask-free-text-input="true"]'),E=(xe=(me=_e==null?void 0:_e.value)==null?void 0:me.trim())!=null?xe:"";if(E){let qe=Fo(b)[Yn(b)];(typeof qe!="string"||qe!==E)&&uo(b,E)}let Ae=k==="next"?1:-1,Pe=Yn(b)+Ae;pi(b,Se,r,Pe),Hn(b);return}if(k==="submit-all"){if(!Tt.current)return;let Te=(We=b.getAttribute("data-tool-call-id"))!=null?We:"",Se=Tt.current.getMessages().find(qe=>{var ye;return((ye=qe.toolCall)==null?void 0:ye.id)===Te});if(!Se)return;let _e=b.querySelector('[data-ask-free-text-input="true"]'),E=(Ve=(Ze=_e==null?void 0:_e.value)==null?void 0:Ze.trim())!=null?Ve:"";E&&uo(b,E);let Ae=di(b,Se);Tt.current.persistAskUserQuestionProgress(Se,{answers:Ae,currentIndex:Yn(b)});let Pe=qr(Ae);Vn(b,Pe||"(submitted)",{source:"submit-all",structured:Ae});return}if(k==="skip"){if(!Tt.current)return;let Te=(rt=b.getAttribute("data-tool-call-id"))!=null?rt:"",Se=Tt.current.getMessages().find(ye=>{var St;return((St=ye.toolCall)==null?void 0:St.id)===Te});if(!Se)return;let _e=co(b),E=Yn(b),Ae=cs(b),Pe=E>=Ae-1;if(!_e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Te},bubbles:!0,composed:!0})),po(zn,Te),(ot=Se.agentMetadata)!=null&&ot.awaitingLocalTool&&(Tt.current.markAskUserQuestionResolved(Se),Tt.current.resolveAskUserQuestion(Se,"(dismissed)"));return}uo(b,"");let qe=b.querySelector('[data-ask-free-text-input="true"]');if(qe&&(qe.value=""),Pe){let ye=di(b,Se),St=qr(ye);Vn(b,St||"(skipped)",{source:"submit-all",structured:ye});return}pi(b,Se,r,E+1),Hn(b);return}}),zn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let y=c.target;if(!((D=y.matches)!=null&&D.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let k=y.value;if(k.trim()){if(co(b)){uo(b,k.trim()),Hn(b),Er(b);return}Vn(b,k,{source:"free-text"})}});let zr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let y=zn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",zr);let Bn=null,Mt=null,xn=null,Jn=null,Vr=()=>{};function Tr(){Jn==null||Jn(),Jn=null}let Jr=()=>{var F;if(!Bn||!Mt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((F=e.ownerDocument.defaultView)!=null?F:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Mt.style.removeProperty("position"),Mt.style.removeProperty("left"),Mt.style.removeProperty("top"),Mt.style.removeProperty("bottom"),Mt.style.removeProperty("width"),Mt.style.removeProperty("z-index");return}let b=Bn.firstElementChild;if(!b||b===Mt)return;let k=10;Mt.style.position="absolute",Mt.style.top="0",Mt.style.bottom="0",Mt.style.width=`${k}px`,Mt.style.zIndex="5";let D=b.offsetWidth-k/2;Mt.style.left=`${Math.max(0,D)}px`},fr=()=>{},Dn=()=>{var y,b,k,D,F;if(!gt||!Zn(r))return;ui(e,r),mi(e,r),fr();let c=(D=(k=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:k.narrowHostMaxWidth)!=null?D:520,m=J.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),gt.update(Rn),bn?(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),(F=gt.backdrop)==null||F.classList.add("persona-hidden")):Rn.artifacts.length>0&&(gt.element.classList.remove("persona-hidden"),gt.setMobileOpen(!0)),Vr()};if(Zn(r)){J.style.position="relative";let c=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");c.appendChild(ne),gt=Wu(r,{onSelect:y=>{var b;return(b=Tt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{bn=!0,Dn()}}),gt.element.classList.add("persona-hidden"),Bn=m,m.appendChild(c),m.appendChild(gt.element),gt.backdrop&&J.appendChild(gt.backdrop),J.appendChild(m),Vr=()=>{var b,k,D,F;if(!Bn||!gt)return;if(!(((D=(k=(b=r.features)==null?void 0:b.artifacts)==null?void 0:k.layout)==null?void 0:D.resizable)===!0)){xn==null||xn(),xn=null,Tr(),Mt&&(Mt.remove(),Mt=null),gt.element.style.removeProperty("width"),gt.element.style.removeProperty("maxWidth");return}if(!Mt){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let W=e.ownerDocument,be=(F=W.defaultView)!=null?F:window,ce=Z=>{var rt,ot;if(!gt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||be.innerWidth<=640)return;Z.preventDefault(),Tr();let me=Z.clientX,xe=gt.element.getBoundingClientRect().width,We=(ot=(rt=r.features)==null?void 0:rt.artifacts)==null?void 0:ot.layout,Ze=Te=>{let Se=Bn.getBoundingClientRect().width,_e=e.classList.contains("persona-artifact-appearance-seamless"),E=_e?0:Du(Bn,be),Ae=_e?0:V.getBoundingClientRect().width||6,Pe=xe-(Te.clientX-me),qe=Nu(Pe,Se,E,Ae,We==null?void 0:We.resizableMinWidth,We==null?void 0:We.resizableMaxWidth);gt.element.style.width=`${qe}px`,gt.element.style.maxWidth="none",Jr()},Ve=()=>{W.removeEventListener("pointermove",Ze),W.removeEventListener("pointerup",Ve),W.removeEventListener("pointercancel",Ve),Jn=null;try{V.releasePointerCapture(Z.pointerId)}catch{}};Jn=Ve,W.addEventListener("pointermove",Ze),W.addEventListener("pointerup",Ve),W.addEventListener("pointercancel",Ve);try{V.setPointerCapture(Z.pointerId)}catch{}};V.addEventListener("pointerdown",ce),Mt=V,Bn.insertBefore(V,gt.element),xn=()=>{V.removeEventListener("pointerdown",ce)}}if(Mt){let V=Rn.artifacts.length>0&&!bn;Mt.classList.toggle("persona-hidden",!V),Jr()}},fr=()=>{var be,ce,Z,me,xe,We,Ze,Ve,rt,ot,Te,Se,_e,E;if(!A||!gt||((ce=(be=r.launcher)==null?void 0:be.sidebarMode)!=null?ce:!1)||nn(r)&&Xn(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,k=(xe=(me=r.launcher)==null?void 0:me.mobileFullscreen)!=null?xe:!0,D=(Ze=(We=r.launcher)==null?void 0:We.mobileBreakpoint)!=null?Ze:640;if(k&&b.innerWidth<=D||!Bu(r,A))return;let F=(ot=(rt=(Ve=r.launcher)==null?void 0:Ve.width)!=null?rt:r.launcherWidth)!=null?ot:jn,V=(E=(_e=(Se=(Te=r.features)==null?void 0:Te.artifacts)==null?void 0:Se.layout)==null?void 0:_e.expandedPanelWidth)!=null?E:"min(720px, calc(100vw - 24px))";Rn.artifacts.length>0&&!bn?(J.style.width=V,J.style.maxWidth=V):(J.style.width=F,J.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Wn=new ResizeObserver(()=>{Dn()}),Wn.observe(J))}else J.appendChild(ne),q()&&we&&(de.peekBanner&&we.appendChild(de.peekBanner),we.appendChild($e));e.appendChild(Q),we&&e.appendChild(we);let tr=()=>{var qe,ye,St,nt,Yt,pn,kt,wn,un,Qe,st,Cn,gn,wo,Co,Ao,Ko,Go,jt,So,no,mt,Mn,Rr,An,Ln,Rt,Ut;if(q()){J.style.width="100%",J.style.maxWidth="100%";let Ht=(ye=(qe=r.launcher)==null?void 0:qe.composerBar)!=null?ye:{},qt=Q.dataset.state==="expanded",Pn=(St=Ht.expandedSize)!=null?St:"anchored";if(!(qt&&Pn!=="fullscreen")){ne.style.background="",ne.style.border="",ne.style.borderRadius="",ne.style.overflow="",ne.style.boxShadow="";return}let tn=(Yt=(nt=r.theme)==null?void 0:nt.components)==null?void 0:Yt.panel,br=ns(r),Hr=(Eo,Ca)=>{var Ms;return Eo==null||Eo===""?Ca:(Ms=es(br,Eo))!=null?Ms:Eo},xa="1px solid var(--persona-border)",va="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",wa="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ne.style.background="var(--persona-surface, #ffffff)",ne.style.border=Hr(tn==null?void 0:tn.border,xa),ne.style.borderRadius=Hr(tn==null?void 0:tn.borderRadius,wa),ne.style.boxShadow=Hr(tn==null?void 0:tn.shadow,va),ne.style.overflow="hidden";return}let c=nn(r),m=(kt=(pn=r.launcher)==null?void 0:pn.sidebarMode)!=null?kt:!1,y=c||m||((un=(wn=r.launcher)==null?void 0:wn.fullHeight)!=null?un:!1),b=((Qe=r.launcher)==null?void 0:Qe.enabled)===!1,k=(Cn=(st=r.theme)==null?void 0:st.components)==null?void 0:Cn.panel,D=ns(r),F=(Ht,qt)=>{var Pn;return Ht==null||Ht===""?qt:(Pn=es(D,Ht))!=null?Pn:Ht},V=(gn=e.ownerDocument.defaultView)!=null?gn:window,W=(Co=(wo=r.launcher)==null?void 0:wo.mobileFullscreen)!=null?Co:!0,be=(Ko=(Ao=r.launcher)==null?void 0:Ao.mobileBreakpoint)!=null?Ko:640,ce=V.innerWidth<=be,Z=W&&ce&&A,me=(jt=(Go=r.launcher)==null?void 0:Go.position)!=null?jt:"bottom-left",xe=me==="bottom-left"||me==="top-left",We=(no=(So=r.launcher)==null?void 0:So.zIndex)!=null?no:yn,Ze=m||Z?"none":"1px solid var(--persona-border)",Ve=Z?"none":m?xe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(Ve="none",Ze="none");let rt=m||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ot=F(k==null?void 0:k.border,Ze),Te=F(k==null?void 0:k.shadow,Ve),Se=F(k==null?void 0:k.borderRadius,rt),_e=fe.scrollTop;e.style.cssText="",Q.style.cssText="",J.style.cssText="",ne.style.cssText="",fe.style.cssText="",$e.style.cssText="";let E=()=>{var qt;if(_e<=0)return;((qt=fe.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(fe.scrollTop===_e)return;let Pn=fe.scrollHeight-fe.clientHeight;Pn<=0||(fe.scrollTop=Math.min(_e,Pn))})};if(Z){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=`
24
24
  position: fixed !important;
25
25
  inset: 0 !important;
26
26
  width: 100% !important;
@@ -30,9 +30,9 @@
30
30
  padding: 0 !important;
31
31
  display: flex !important;
32
32
  flex-direction: column !important;
33
- z-index: ${Je} !important;
33
+ z-index: ${We} !important;
34
34
  background-color: var(--persona-surface, #ffffff) !important;
35
- `,z.style.cssText=`
35
+ `,J.style.cssText=`
36
36
  position: relative !important;
37
37
  display: flex !important;
38
38
  flex-direction: column !important;
@@ -45,7 +45,7 @@
45
45
  padding: 0 !important;
46
46
  box-shadow: none !important;
47
47
  border-radius: 0 !important;
48
- `,_.style.cssText=`
48
+ `,ne.style.cssText=`
49
49
  display: flex !important;
50
50
  flex-direction: column !important;
51
51
  flex: 1 1 0% !important;
@@ -56,20 +56,20 @@
56
56
  overflow: hidden !important;
57
57
  border-radius: 0 !important;
58
58
  border: none !important;
59
- `,q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",se.style.flexShrink="0",M=!0,Ce();return}let je=(Oo=(Fo=r==null?void 0:r.launcher)==null?void 0:Fo.width)!=null?Oo:r==null?void 0:r.launcherWidth,vt=je!=null?je:On;if(!m&&!l)b&&y?(z.style.width="100%",z.style.maxWidth="100%"):(z.style.width=vt,z.style.maxWidth=vt);else if(l)if(Zn(r).reveal==="emerge"){let rn=Zn(r).width;z.style.width=rn,z.style.maxWidth=rn}else z.style.width="100%",z.style.maxWidth="100%";if(lr(),z.style.boxShadow=Be,z.style.borderRadius=S,_.style.border=Et,_.style.borderRadius=S,l&&!ke&&(T==null?void 0:T.border)===void 0&&(_.style.border="none",Zn(r).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",b&&(e.style.width="100%"),R.style.display="flex",R.style.flexDirection="column",R.style.flex="1 1 0%",R.style.minHeight="0",R.style.maxHeight="100%",R.style.height="100%",b&&(R.style.overflow="hidden"),z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",z.style.overflow="hidden",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.overflow="hidden",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",se.style.flexShrink="0"),R.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&&!b&&!l&&((Xe=ir[be])!=null?Xe:ir["bottom-right"]).split(" ").forEach(rn=>R.classList.add(rn)),m){let Wt=(Xn=(Yn=r.launcher)==null?void 0:Yn.sidebarWidth)!=null?Xn:"420px";R.style.cssText=`
59
+ `,fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.overflowY="auto",$e.style.flexShrink="0",$=!0,E();return}let Ae=(Mn=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?Mn:r==null?void 0:r.launcherWidth,Pe=Ae!=null?Ae:jn;if(!m&&!c)b&&y?(J.style.width="100%",J.style.maxWidth="100%"):(J.style.width=Pe,J.style.maxWidth=Pe);else if(c)if(Xn(r).reveal==="emerge"){let qt=Xn(r).width;J.style.width=qt,J.style.maxWidth=qt}else J.style.width="100%",J.style.maxWidth="100%";if(fr(),J.style.boxShadow=Te,J.style.borderRadius=Se,ne.style.border=ot,ne.style.borderRadius=Se,c&&!Z&&(k==null?void 0:k.border)===void 0&&(ne.style.border="none",Xn(r).side==="right"?ne.style.borderLeft="1px solid var(--persona-border)":ne.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),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%",b&&(Q.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.height="100%",J.style.overflow="hidden",ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.overflow="hidden",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.overflowY="auto",$e.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&&!b&&!c&&((Rr=dr[me])!=null?Rr:dr["bottom-right"]).split(" ").forEach(qt=>Q.classList.add(qt)),m){let Ht=(Ln=(An=r.launcher)==null?void 0:An.sidebarWidth)!=null?Ln:"420px";Q.style.cssText=`
60
60
  position: fixed !important;
61
61
  top: 0 !important;
62
62
  bottom: 0 !important;
63
- width: ${Wt} !important;
63
+ width: ${Ht} !important;
64
64
  height: 100vh !important;
65
65
  max-height: 100vh !important;
66
66
  margin: 0 !important;
67
67
  padding: 0 !important;
68
68
  display: flex !important;
69
69
  flex-direction: column !important;
70
- z-index: ${Je} !important;
71
- ${$e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
72
- `,z.style.cssText=`
70
+ z-index: ${We} !important;
71
+ ${xe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
72
+ `,J.style.cssText=`
73
73
  position: relative !important;
74
74
  display: flex !important;
75
75
  flex-direction: column !important;
@@ -80,9 +80,9 @@
80
80
  min-height: 0 !important;
81
81
  margin: 0 !important;
82
82
  padding: 0 !important;
83
- box-shadow: ${Be} !important;
84
- border-radius: ${S} !important;
85
- `,z.style.setProperty("width","100%","important"),z.style.setProperty("max-width","100%","important"),_.style.cssText=`
83
+ box-shadow: ${Te} !important;
84
+ border-radius: ${Se} !important;
85
+ `,J.style.setProperty("width","100%","important"),J.style.setProperty("max-width","100%","important"),ne.style.cssText=`
86
86
  display: flex !important;
87
87
  flex-direction: column !important;
88
88
  flex: 1 1 0% !important;
@@ -91,29 +91,29 @@
91
91
  min-height: 0 !important;
92
92
  max-height: 100% !important;
93
93
  overflow: hidden !important;
94
- border-radius: ${S} !important;
95
- border: ${Et} !important;
96
- `,se.style.cssText=`
94
+ border-radius: ${Se} !important;
95
+ border: ${ot} !important;
96
+ `,$e.style.cssText=`
97
97
  flex-shrink: 0 !important;
98
98
  border-top: none !important;
99
99
  padding: 8px 16px 12px 16px !important;
100
- `}if(!b&&!l){let Wt="max-height: -moz-available !important; max-height: stretch !important;",rn=m?"":"padding-top: 1.25em !important;",Sn=m?"":`z-index: ${(qt=(mr=r.launcher)==null?void 0:mr.zIndex)!=null?qt:Tn} !important;`;R.style.cssText+=Wt+rn+Sn}Ce()};cr(),Jr(e,r),Na(e,r),Fa(e,r);let At=[];At.push(()=>{document.removeEventListener("keydown",Dr)});let zt=null,Vt=null;At.push(()=>{zt==null||zt(),zt=null,Vt==null||Vt(),Vt=null}),Ln&&At.push(()=>{Ln==null||Ln.disconnect(),Ln=null}),At.push(()=>{yn==null||yn(),yn=null,br(),Pt&&(Pt.remove(),Pt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ue&&At.push(()=>{Q!==null&&(cancelAnimationFrame(Q),Q=null),X==null||X.destroy(),X=null,de==null||de.destroy(),de=null,Le=null});let Hn=null,Or=()=>{Hn&&(Hn(),Hn=null),r.colorScheme==="auto"&&(Hn=Ta(()=>{Jr(e,r)}))};Or(),At.push(()=>{Hn&&(Hn(),Hn=null)});let zn=(Cl=r.features)==null?void 0:Cl.streamAnimation;if(zn!=null&&zn.type&&zn.type!=="none"){let l=Ia(zn.type,zn.plugins);l&&(Mp(l,e),At.push(()=>Tp(e)))}let nr=Jp(Ee),Bn=null,F,rr=!1,Vn=gp(),Jn=new Map,$r=0,ce=Ma(),bn=0,Dn=null,xr=!1,ro=!1,zs=4,rs=24,Vs=80,Po=new Map,pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},os=(Sl=(Al=r.voiceRecognition)==null?void 0:Al.autoResume)!=null?Sl:!1,Kn=l=>{o.emit("voice:state",{active:pt.active,source:l,timestamp:Date.now()})},Cn=()=>{f(l=>({...l,voiceState:{active:pt.active,timestamp:Date.now(),manuallyDeactivated:pt.manuallyDeactivated}}))},Js=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=Fi(i.voiceState),m=!!l.active,y=Number((T=l.timestamp)!=null?T:0);pt.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<_g&&setTimeout(()=>{var W,B;pt.active||(pt.manuallyDeactivated=!1,((B=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:B.type)==="runtype"?F.toggleVoice().then(()=>{pt.active=F.isVoiceActive(),Kn("restore"),F.isVoiceActive()&&Ur()}):io("restore"))},1e3)},Ks=()=>F?lu(F.getMessages()).filter(l=>!l.__skipPersist):[];function Wo(l){if(!(a!=null&&a.save))return;let y={messages:l?lu(l):F?Ks():[],metadata:i,artifacts:In.artifacts,selectedArtifactId:In.selectedId};try{let b=a.save(y);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let vr=null,Gs=()=>R.querySelector("#persona-scroll-container")||q,oo=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null),xr=!1},ss=()=>{Dn!==null&&(cancelAnimationFrame(Dn),Dn=null),ro=!1,oo()},wr=()=>{if(!an()||ge){ht.parentNode&&ht.remove(),ht.style.display="none";return}ht.parentNode!==_&&_.appendChild(ht),Me();let l=Is(q)>0;ht.style.display=ce.isFollowing()||!l?"none":""},as=()=>{ce.pause()&&(ss(),wr())},_r=()=>{ce.resume(),wr()},jr=(l=!1)=>{ce.isFollowing()&&(!l&&!rr||(Dn!==null&&(cancelAnimationFrame(Dn),Dn=null),ro=!0,Dn=requestAnimationFrame(()=>{Dn=null,ro=!1,ce.isFollowing()&&Qs(Gs(),l?220:140)})))},Qs=(l,m=500)=>{let y=l.scrollTop,b=Is(l),T=b-y;if(Math.abs(T)<1){bn=l.scrollTop;return}if(Math.abs(T)>=Vs){oo(),xr=!0,l.scrollTop=b,bn=l.scrollTop,xr=!1;return}oo();let W=performance.now();xr=!0;let B=$=>1-Math.pow(1-$,3),V=$=>{if(!ce.isFollowing()){oo();return}let Se=Is(l);Se!==b&&(b=Se,T=b-y);let ye=$-W,ke=Math.min(ye/m,1),be=B(ke),$e=y+T*be;l.scrollTop=$e,bn=l.scrollTop,ke<1?vr=requestAnimationFrame(V):(l.scrollTop=b,bn=l.scrollTop,vr=null,xr=!1)};vr=requestAnimationFrame(V)},Ys=l=>{let m=new Map;l.forEach(y=>{let b=Po.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Po.clear(),m.forEach((y,b)=>{Po.set(b,y)})},so=(l,m,y)=>{var Je,ut,tt,St,Et,Be;let b=document.createElement("div"),W=(()=>{var xe;let S=s.find(Ce=>Ce.renderLoadingIndicator);if(S!=null&&S.renderLoadingIndicator)return S.renderLoadingIndicator;if((xe=r.loadingIndicator)!=null&&xe.render)return r.loadingIndicator.render})(),B=(S,xe)=>xe==null?!1:typeof xe=="string"?(S.textContent=xe,!0):(S.appendChild(xe),!0),V=new Set,$=new Set,Se=s.some(S=>S.renderAskUserQuestion),ye=[];if(m.forEach(S=>{var Qn,nn,Bt,An,Kt,Ge,mt,pr,ur,uo,mo,go,Fo,Oo;V.add(S.id);let xe=Se&&Lr(S),Ce=Lr(S)?`:${(Qn=S.agentMetadata)!=null&&Qn.askUserQuestionAnswered?"a":"u"}:${(nn=S.agentMetadata)!=null&&nn.askUserQuestionAnswers?Object.keys(S.agentMetadata.askUserQuestionAnswers).length:0}`:"",je=mp(S,$r)+Ce,vt=xe?null:fp(Vn,S.id,je);if(vt){b.appendChild(vt.cloneNode(!0)),Lr(S)&&((Bt=S.toolCall)!=null&&Bt.id)&&((An=S.agentMetadata)==null?void 0:An.awaitingLocalTool)===!0&&!((Kt=S.agentMetadata)!=null&&Kt.askUserQuestionAnswered)&&($.add(S.toolCall.id),Zo(S,r,ne.composerOverlay));return}let _e=null,we=s.find(Xe=>!!(S.variant==="reasoning"&&Xe.renderReasoning||S.variant==="tool"&&Xe.renderToolCall||S.variant==="approval"&&Xe.renderApproval||!S.variant&&Xe.renderMessage)),en=(Ge=r.layout)==null?void 0:Ge.messages;if(Lr(S)&&((mt=S.agentMetadata)==null?void 0:mt.askUserQuestionAnswered)===!0){Jn.delete(S.id);let Xe=l.querySelector(`#wrapper-${S.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime");return}if(Lr(S)&&((ur=(pr=r.features)==null?void 0:pr.askUserQuestion)==null?void 0:ur.enabled)!==!1){let Xe=s.find(Yn=>typeof Yn.renderAskUserQuestion=="function");if(Xe&&It.current){let Yn=Jn.get(S.id),Xn=Yn!==je,mr=null;if(Xn){let{payload:rn,complete:Sn}=Ir(S),Er=S.id,Vr=()=>{var vn;return(vn=It.current)==null?void 0:vn.getMessages().find(mn=>mn.id===Er)};mr=Xe.renderAskUserQuestion({message:S,payload:rn,complete:Sn,resolve:vn=>{var fo;let mn=Vr();mn&&((fo=It.current)==null||fo.resolveAskUserQuestion(mn,vn))},dismiss:()=>{var mn,fo,oa;let vn=Vr();(mn=vn==null?void 0:vn.agentMetadata)!=null&&mn.awaitingLocalTool&&((fo=It.current)==null||fo.markAskUserQuestionResolved(vn),(oa=It.current)==null||oa.resolveAskUserQuestion(vn,"(dismissed)"))},config:r})}let qt=Yn!=null;if(Xn&&mr===null&&!qt){((uo=S.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((mo=S.agentMetadata)!=null&&mo.askUserQuestionAnswered)&&($.add(S.toolCall.id),Zo(S,r,ne.composerOverlay));return}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${S.id}`,Wt.setAttribute("data-wrapper-id",S.id),Wt.setAttribute("data-ask-plugin-stub","true"),Wt.setAttribute("data-preserve-runtime","true"),b.appendChild(Wt),ye.push({messageId:S.id,fingerprint:je,bubble:mr});return}else{((go=S.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((Fo=S.agentMetadata)!=null&&Fo.askUserQuestionAnswered)&&($.add(S.toolCall.id),Zo(S,r,ne.composerOverlay));return}}else if(we)if(S.variant==="reasoning"&&S.reasoning&&we.renderReasoning){if(!ie)return;_e=we.renderReasoning({message:S,defaultRenderer:()=>Ai(S,r),config:r})}else if(S.variant==="tool"&&S.toolCall&&we.renderToolCall){if(!ve)return;_e=we.renderToolCall({message:S,defaultRenderer:()=>Si(S,r),config:r})}else if(S.variant==="approval"&&S.approval&&we.renderApproval){if(r.approval===!1)return;_e=we.renderApproval({message:S,defaultRenderer:()=>Wi(S,r),config:r})}else we.renderMessage&&(_e=we.renderMessage({message:S,defaultRenderer:()=>{let Xe=Ko(S,y,en,r.messageActions,pe,{loadingIndicatorRenderer:W,widgetConfig:r});return S.role!=="user"&&Bi(Xe,S,r,F),Xe},config:r}));if(!_e&&S.role==="assistant"&&!S.variant&&r.enableComponentStreaming!==!1&&ja(S)){let Yn=Ua(S);if(Yn){let Xn=_a(Yn,{config:r,message:S,transform:y});if(Xn)if(r.wrapComponentDirectiveInBubble!==!1){let qt=document.createElement("div");if(qt.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(" "),qt.id=`bubble-${S.id}`,qt.setAttribute("data-message-id",S.id),S.content&&S.content.trim()){let Wt=document.createElement("div");Wt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Wt.innerHTML=y({text:S.content,message:S,streaming:!!S.streaming,raw:S.rawContent}),qt.appendChild(Wt)}qt.appendChild(Xn),_e=qt}else{let qt=document.createElement("div");if(qt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",qt.id=`bubble-${S.id}`,qt.setAttribute("data-message-id",S.id),qt.setAttribute("data-persona-component-directive","true"),S.content&&S.content.trim()){let Wt=document.createElement("div");Wt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Wt.innerHTML=y({text:S.content,message:S,streaming:!!S.streaming,raw:S.rawContent}),qt.appendChild(Wt)}qt.appendChild(Xn),_e=qt}}}if(!_e)if(S.variant==="reasoning"&&S.reasoning){if(!ie)return;_e=Ai(S,r)}else if(S.variant==="tool"&&S.toolCall){if(!ve)return;_e=Si(S,r)}else if(S.variant==="approval"&&S.approval){if(r.approval===!1)return;_e=Wi(S,r)}else{let Xe=(Oo=r.layout)==null?void 0:Oo.messages;Xe!=null&&Xe.renderUserMessage&&S.role==="user"?_e=Xe.renderUserMessage({message:S,config:r,streaming:!!S.streaming}):Xe!=null&&Xe.renderAssistantMessage&&S.role==="assistant"?_e=Xe.renderAssistantMessage({message:S,config:r,streaming:!!S.streaming}):_e=Ko(S,y,Xe,r.messageActions,pe,{loadingIndicatorRenderer:W,widgetConfig:r}),S.role!=="user"&&_e&&Bi(_e,S,r,F)}let tn=document.createElement("div");tn.className="persona-flex",tn.id=`wrapper-${S.id}`,tn.setAttribute("data-wrapper-id",S.id),S.role==="user"&&tn.classList.add("persona-justify-end"),(_e==null?void 0:_e.getAttribute("data-persona-component-directive"))==="true"&&tn.classList.add("persona-w-full"),tn.appendChild(_e),hp(Vn,S.id,je,tn),b.appendChild(tn)}),ne.composerOverlay&&ne.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(xe=>{let Ce=xe.getAttribute("data-persona-ask-sheet-for");Ce&&!$.has(Ce)&&Zr(ne.composerOverlay,Ce)}),(ut=(Je=r.features)==null?void 0:Je.toolCallDisplay)!=null&&ut.grouped){let S=[],xe=[];m.forEach(Ce=>{if(Ce.variant==="tool"&&Ce.toolCall&&ve){xe.push(Ce);return}xe.length>1&&S.push(xe),xe=[]}),xe.length>1&&S.push(xe),S.forEach((Ce,je)=>{var Bt,An;let vt=Ce.map(Kt=>Array.from(b.children).find(Ge=>Ge instanceof HTMLElement&&Ge.getAttribute("data-wrapper-id")===Kt.id)).filter(Kt=>!!Kt);if(vt.length<2)return;let _e=document.createElement("div");_e.className="persona-flex",_e.id=`wrapper-tool-group-${je}-${Ce[0].id}`,_e.setAttribute("data-wrapper-id",`tool-group-${je}-${Ce[0].id}`);let we=document.createElement("div");we.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",we.setAttribute("data-persona-tool-group","true");let en=document.createElement("div");en.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let tn=`Called ${Ce.length} tools`,Qn=(An=(Bt=r.toolCall)==null?void 0:Bt.renderGroupedSummary)==null?void 0:An.call(Bt,{messages:Ce,toolCalls:Ce.map(Kt=>Kt.toolCall).filter(Kt=>!!Kt),defaultSummary:tn,config:r});B(en,Qn)||(en.textContent=tn);let nn=document.createElement("div");nn.className="persona-tool-group-stack persona-flex persona-flex-col",we.append(en,nn),_e.appendChild(we),vt[0].before(_e),vt.forEach((Kt,Ge)=>{let mt=document.createElement("div");mt.className="persona-tool-group-item persona-relative",mt.setAttribute("data-persona-tool-group-item","true"),Ge<vt.length-1&&mt.setAttribute("data-persona-tool-group-connector","true"),mt.appendChild(Kt),nn.appendChild(mt)})})}yp(Vn,V);let ke=m.some(S=>S.role==="assistant"&&S.streaming),be=m[m.length-1],$e=(be==null?void 0:be.role)==="assistant"&&!be.streaming&&be.variant!=="approval";if(rr&&m.some(S=>S.role==="user")&&!ke&&!$e){let S={config:r,streaming:!0,location:"standalone",defaultRenderer:To},xe=s.find(je=>je.renderLoadingIndicator),Ce=null;if(xe!=null&&xe.renderLoadingIndicator&&(Ce=xe.renderLoadingIndicator(S)),Ce===null&&((tt=r.loadingIndicator)!=null&&tt.render)&&(Ce=r.loadingIndicator.render(S)),Ce===null&&(Ce=To()),Ce){let je=document.createElement("div"),vt=((St=r.loadingIndicator)==null?void 0:St.showBubble)!==!1;je.className=vt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),je.setAttribute("data-typing-indicator","true"),je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",je.appendChild(Ce);let _e=document.createElement("div");_e.className="persona-flex",_e.id="wrapper-typing-indicator",_e.setAttribute("data-wrapper-id","typing-indicator"),_e.appendChild(je),b.appendChild(_e)}}if(!rr&&m.length>0){let S=m[m.length-1],xe={config:r,lastMessage:S,messageCount:m.length},Ce=s.find(vt=>vt.renderIdleIndicator),je=null;if(Ce!=null&&Ce.renderIdleIndicator&&(je=Ce.renderIdleIndicator(xe)),je===null&&((Et=r.loadingIndicator)!=null&&Et.renderIdle)&&(je=r.loadingIndicator.renderIdle(xe)),je){let vt=document.createElement("div"),_e=((Be=r.loadingIndicator)==null?void 0:Be.showBubble)!==!1;vt.className=_e?["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(" "),vt.setAttribute("data-idle-indicator","true"),vt.appendChild(je);let we=document.createElement("div");we.className="persona-flex",we.id="wrapper-idle-indicator",we.setAttribute("data-wrapper-id","idle-indicator"),we.appendChild(vt),b.appendChild(we)}}if(up(l,b),ye.length>0)for(let{messageId:S,fingerprint:xe,bubble:Ce}of ye){let je=l.querySelector(`#wrapper-${S}`);je&&Ce!==null&&(je.replaceChildren(Ce),je.setAttribute("data-bubble-fp",xe),Jn.set(S,xe))}if(Jn.size>0)for(let S of Jn.keys())V.has(S)||Jn.delete(S)},ao=()=>{var $,Se,ye,ke,be;if(!w)return;let l=Yt(r),m=($=e.ownerDocument.defaultView)!=null?$:window,y=(ye=(Se=r.launcher)==null?void 0:Se.mobileBreakpoint)!=null?ye:640,b=(be=(ke=r.launcher)==null?void 0:ke.mobileFullscreen)!=null?be:!0,T=m.innerWidth<=y,W=b&&T&&w,B=Zn(r).reveal;P?(R.style.removeProperty("display"),R.style.display=l?"flex":"",R.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-95","persona-opacity-0"),z.classList.add("persona-scale-100","persona-opacity-100"),jt?jt.element.style.display="none":Ut&&(Ut.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!W?(R.style.removeProperty("display"),R.style.display="flex",R.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(R.style.setProperty("display","none","important"),R.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(R.style.display="",R.classList.add("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100"),z.classList.add("persona-scale-95","persona-opacity-0")),jt?jt.element.style.display=l?"none":"":Ut&&(Ut.style.display=l?"none":""))},_t=(l,m="user")=>{var W,B;if(!w||P===l)return;let y=P;P=l,ao();let b=(()=>{var $e,Je,ut,tt,St,Et,Be;let V=(Je=($e=r.launcher)==null?void 0:$e.sidebarMode)!=null?Je:!1,$=(ut=e.ownerDocument.defaultView)!=null?ut:window,Se=(St=(tt=r.launcher)==null?void 0:tt.mobileFullscreen)!=null?St:!0,ye=(Be=(Et=r.launcher)==null?void 0:Et.mobileBreakpoint)!=null?Be:640,ke=$.innerWidth<=ye,be=Yt(r)&&Se&&ke;return V||Se&&ke&&w||be})();if(P&&b){if(!zt){let V=e.getRootNode(),$=V instanceof ShadowRoot?V.host:e.closest(".persona-host");$&&(zt=hi($,(B=(W=r.launcher)==null?void 0:W.zIndex)!=null?B:Tn))}Vt||(Vt=yi(e.ownerDocument))}else P||(zt==null||zt(),zt=null,Vt==null||Vt(),Vt=null);P&&(qr(),jr(!0));let T={open:P,source:m,timestamp:Date.now()};P&&!y?o.emit("widget:opened",T):!P&&y&&o.emit("widget:closed",T),o.emit("widget:state",{open:P,launcherEnabled:w,voiceActive:pt.active,streaming:F.isStreaming()})},Ro=l=>{Ze(l?"stop":"send"),H&&(H.disabled=l),nr.buttons.forEach(m=>{m.disabled=l}),se.dataset.personaComposerStreaming=l?"true":"false",se.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Ho=()=>{pt.active||ee&&ee.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Ho(),200)});let is=()=>{var y,b,T,W,B,V,$,Se,ye,ke,be;sn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",nt.textContent=(W=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",ee.placeholder=(V=(B=r.copy)==null?void 0:B.inputPlaceholder)!=null?V:"How can I help...";let l=q.querySelector("[data-persona-intro-card]");if(l){let $e=(($=r.copy)==null?void 0:$.showWelcomeCard)!==!1;l.style.display=$e?"":"none",$e?(q.classList.remove("persona-gap-3"),q.classList.add("persona-gap-6")):(q.classList.remove("persona-gap-6"),q.classList.add("persona-gap-3"))}!((ye=(Se=r.sendButton)==null?void 0:Se.useIcon)!=null&&ye)&&!(F!=null&&F.isStreaming())&&(ae.textContent=(be=(ke=r.copy)==null?void 0:ke.sendButtonLabel)!=null?be:"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))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let dr=null,Xs=()=>{dr==null&&(dr=setInterval(()=>{let l=le.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(dr),dr=null;return}let m=Date.now();l.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=ia(m-b))})},100))};if(F=new qo(r,{onMessagesChanged(l){so(le,l,j),Xs(),F&&(l.some(T=>T.role==="user")?nr.render([],F,ee,l):nr.render(r.suggestionChips,F,ee,l,r.suggestionChipsConfig)),jr(!rr),Ys(l);let m=[...l].reverse().find(b=>b.role==="user"),y=pt.lastUserMessageId;m&&m.id!==y&&(pt.lastUserMessageId=m.id,o.emit("user:message",m)),pt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Wo(l)},onStatusChanged(l){var b;let m=(b=r.statusIndicator)!=null?b:{};Pe(Ke,(T=>{var W,B,V,$;return T==="idle"?(W=m.idleText)!=null?W:fn.idle:T==="connecting"?(B=m.connectingText)!=null?B:fn.connecting:T==="connected"?(V=m.connectedText)!=null?V:fn.connected:T==="error"?($=m.errorText)!=null?$:fn.error:fn[T]})(l),m,l)},onStreamingChanged(l){rr=l,Ro(l),F&&so(le,F.getMessages(),j),l||jr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":sr(),ea();break;case"speaking":sr(),ta();break;default:l==="idle"&&F.isBargeInActive()?(sr(),Ur(),H==null||H.setAttribute("aria-label","End voice session")):(pt.active=!1,sr(),Kn("system"),Cn());break}},onArtifactsState(l){In=l,Rn(),Wo()}}),It.current=F,((Tl=(El=r.voiceRecognition)==null?void 0:El.provider)==null?void 0:Tl.type)==="runtype")try{F.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&F.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(de||r.onSSEEvent)&&F.setSSEEventCallback((l,m)=>{var y;(y=r.onSSEEvent)==null||y.call(r,l,m),de==null||de.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),p&&p.then(l=>{var m,y,b;l&&(l.metadata&&(i=Fi(l.metadata),E.syncFromMetadata()),(m=l.messages)!=null&&m.length&&F.hydrateMessages(l.messages),(y=l.artifacts)!=null&&y.length&&F.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ls=l=>{var T;if(l.preventDefault(),F.isStreaming()){F.cancel();return}let m=ee.value.trim(),y=(T=ze==null?void 0:ze.hasAttachments())!=null?T:!1;if(!m&&!y)return;let b;y&&(b=[],b.push(...ze.getContentParts()),m&&b.push(As(m))),ee.value="",ee.style.height="auto",F.sendMessage(m,{contentParts:b}),y&&ze.clearAttachments()},cs=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),ae.click())},ds=async l=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!ze)return;let m=Ug(l.clipboardData);m.length!==0&&(l.preventDefault(),await ze.handleFiles(m))},xn=null,Nn=!1,Cr=null,ot=null,ps=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,io=(l="user")=>{var W,B,V,$,Se,ye,ke;if(Nn||F.isStreaming())return;let m=ps();if(!m)return;xn=new m;let b=(B=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?B:2e3;xn.continuous=!0,xn.interimResults=!0,xn.lang="en-US";let T=ee.value;xn.onresult=be=>{let $e="",Je="";for(let tt=0;tt<be.results.length;tt++){let St=be.results[tt],Et=St[0].transcript;St.isFinal?$e+=Et+" ":Je=Et}let ut=T+$e+Je;ee.value=ut,Cr&&clearTimeout(Cr),($e||Je)&&(Cr=window.setTimeout(()=>{let tt=ee.value.trim();tt&&xn&&Nn&&(or(),ee.value="",ee.style.height="auto",F.sendMessage(tt,{viaVoice:!0}))},b))},xn.onerror=be=>{be.error!=="no-speech"&&or()},xn.onend=()=>{if(Nn){let be=ee.value.trim();be&&be!==T.trim()&&(ee.value="",ee.style.height="auto",F.sendMessage(be,{viaVoice:!0})),or()}};try{if(xn.start(),Nn=!0,pt.active=!0,l!=="system"&&(pt.manuallyDeactivated=!1),Kn(l),Cn(),H){let be=(V=r.voiceRecognition)!=null?V:{};ot={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:($=be.iconName)!=null?$:"mic",iconSize:parseFloat((ke=(ye=be.iconSize)!=null?ye:(Se=r.sendButton)==null?void 0:Se.size)!=null?ke:"40")||24};let $e=be.recordingBackgroundColor,Je=be.recordingIconColor,ut=be.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=$e!=null?$e:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=Je!=null?Je:"var(--persona-voice-recording-indicator, #ffffff)",Je){let tt=H.querySelector("svg");tt&&tt.setAttribute("stroke",Je)}ut&&(H.style.borderColor=ut),H.setAttribute("aria-label","Stop voice recognition")}}catch{or("system")}},or=(l="user")=>{if(Nn){if(Nn=!1,Cr&&(clearTimeout(Cr),Cr=null),xn){try{xn.stop()}catch{}xn=null}if(pt.active=!1,Kn(l),Cn(),H){if(H.classList.remove("persona-voice-recording"),ot){H.style.backgroundColor=ot.backgroundColor,H.style.color=ot.color,H.style.borderColor=ot.borderColor;let m=H.querySelector("svg");m&&m.setAttribute("stroke",ot.color||"currentColor"),ot=null}H.setAttribute("aria-label","Start voice recognition")}}},Zs=(l,m)=>{var St,Et,Be,S,xe,Ce,je,vt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((St=l==null?void 0:l.provider)==null?void 0:St.type)==="runtype";if(!(y||b))return null;let W=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 V=(Et=l==null?void 0:l.iconName)!=null?Et:"mic",$=(Be=m==null?void 0:m.size)!=null?Be:"40px",Se=(S=l==null?void 0:l.iconSize)!=null?S:$,ye=parseFloat(Se)||24,ke=(xe=l==null?void 0:l.backgroundColor)!=null?xe:m==null?void 0:m.backgroundColor,be=(Ce=l==null?void 0:l.iconColor)!=null?Ce:m==null?void 0:m.textColor;B.style.width=Se,B.style.height=Se,B.style.minWidth=Se,B.style.minHeight=Se,B.style.fontSize="18px",B.style.lineHeight="1",be?B.style.color=be:B.style.color="var(--persona-text, #111827)";let Je=Ae(V,ye,be||"currentColor",1.5);Je?B.appendChild(Je):B.textContent="\u{1F3A4}",ke?B.style.backgroundColor=ke: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),W.appendChild(B);let ut=(je=l==null?void 0:l.tooltipText)!=null?je:"Start voice recognition";if(((vt=l==null?void 0:l.showTooltip)!=null?vt:!1)&&ut){let _e=h("div","persona-send-button-tooltip");_e.textContent=ut,W.appendChild(_e)}return{micButton:B,micButtonWrapper:W}},Bo=()=>{var m,y,b,T,W;if(!H||ot)return;let l=(m=r.voiceRecognition)!=null?m:{};ot={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((W=(T=l.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},Do=(l,m)=>{var W,B,V,$,Se;if(!H)return;let y=H.querySelector("svg");y&&y.remove();let b=(Se=ot==null?void 0:ot.iconSize)!=null?Se:parseFloat(($=(V=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?V:(B=r.sendButton)==null?void 0:B.size)!=null?$:"40")||24,T=Ae(l,b,m,1.5);T&&H.appendChild(T)},lo=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ur=()=>{var T;if(!H)return;Bo();let l=(T=r.voiceRecognition)!=null?T:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,b=l.recordingBorderColor;if(lo(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let W=H.querySelector("svg");W&&W.setAttribute("stroke",y)}b&&(H.style.borderColor=b),H.setAttribute("aria-label","Stop voice recognition")},ea=()=>{var V,$,Se,ye,ke,be,$e,Je;if(!H)return;Bo();let l=(V=r.voiceRecognition)!=null?V:{},m=F.getVoiceInterruptionMode(),y=($=l.processingIconName)!=null?$:"loader",b=(ye=(Se=l.processingIconColor)!=null?Se:ot==null?void 0:ot.color)!=null?ye:"",T=(be=(ke=l.processingBackgroundColor)!=null?ke:ot==null?void 0:ot.backgroundColor)!=null?be:"",W=(Je=($e=l.processingBorderColor)!=null?$e:ot==null?void 0:ot.borderColor)!=null?Je:"";lo(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=T,H.style.borderColor=W;let B=b||"currentColor";H.style.color=B,Do(y,B),H.setAttribute("aria-label","Processing voice input"),m==="none"&&(H.style.cursor="default")},ta=()=>{var Se,ye,ke,be,$e,Je,ut,tt,St,Et,Be,S;if(!H)return;Bo();let l=(Se=r.voiceRecognition)!=null?Se:{},m=F.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(ye=l.speakingIconName)!=null?ye:y,T=(Je=l.speakingIconColor)!=null?Je:m==="barge-in"?(be=(ke=l.recordingIconColor)!=null?ke:ot==null?void 0:ot.color)!=null?be:"":($e=ot==null?void 0:ot.color)!=null?$e:"",W=(St=l.speakingBackgroundColor)!=null?St:m==="barge-in"?(ut=l.recordingBackgroundColor)!=null?ut:"var(--persona-voice-recording-bg, #ef4444)":(tt=ot==null?void 0:ot.backgroundColor)!=null?tt:"",B=(S=l.speakingBorderColor)!=null?S:m==="barge-in"?(Et=l.recordingBorderColor)!=null?Et:"":(Be=ot==null?void 0:ot.borderColor)!=null?Be:"";lo(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=W,H.style.borderColor=B;let V=T||"currentColor";H.style.color=V,Do(b,V);let $=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",$),m==="none"&&(H.style.cursor="default"),m==="barge-in"&&H.classList.add("persona-voice-recording")},sr=()=>{var l,m,y;H&&(lo(),ot&&(H.style.backgroundColor=(l=ot.backgroundColor)!=null?l:"",H.style.color=(m=ot.color)!=null?m:"",H.style.borderColor=(y=ot.borderColor)!=null?y:"",Do(ot.iconName,ot.color||"currentColor"),ot=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},co=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=F.getVoiceStatus(),b=F.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Cn(),Kn("user"),sr()});return}F.toggleVoice().then(()=>{pt.active=F.isVoiceActive(),pt.manuallyDeactivated=!F.isVoiceActive(),Cn(),Kn("user"),F.isVoiceActive()?Ur():sr()});return}if(Nn){let y=ee.value.trim();pt.manuallyDeactivated=!0,Cn(),or("user"),y&&(ee.value="",ee.style.height="auto",F.sendMessage(y))}else pt.manuallyDeactivated=!1,Cn(),io("user")};ln=co,H&&(H.addEventListener("click",co),At.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),sr()):or("system"),H&&H.removeEventListener("click",co)}));let na=o.on("assistant:complete",()=>{os&&(pt.active||pt.manuallyDeactivated||os==="assistant"&&!pt.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!pt.active&&!pt.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.toggleVoice().then(()=>{pt.active=F.isVoiceActive(),Kn("auto"),F.isVoiceActive()&&Ur()}):io("auto"))},600))});At.push(na);let ra=o.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});At.push(ra);let Ar=()=>{_t(!P,"user")},jt=null,Ut=null;if(w){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:r,defaultRenderer:()=>Bs(r,Ar).element,onToggle:Ar});m&&(Ut=m)}Ut||(jt=Bs(r,Ar))}jt?e.appendChild(jt.element):Ut&&e.appendChild(Ut),ao(),nr.render(r.suggestionChips,F,ee,void 0,r.suggestionChipsConfig),is(),Ro(F.isStreaming()),jr(!0),Js(),I&&(w?P&&setTimeout(()=>Ho(),200):setTimeout(()=>Ho(),0));let qr=()=>{var $,Se,ye,ke,be,$e,Je,ut,tt,St,Et,Be,S,xe,Ce,je,vt,_e,we,en,tn,Qn;let l=Yt(r),m=(Se=($=r.launcher)==null?void 0:$.sidebarMode)!=null?Se:!1,y=l||m||((ke=(ye=r.launcher)==null?void 0:ye.fullHeight)!=null?ke:!1),b=(be=e.ownerDocument.defaultView)!=null?be:window,T=(Je=($e=r.launcher)==null?void 0:$e.mobileFullscreen)!=null?Je:!0,W=(tt=(ut=r.launcher)==null?void 0:ut.mobileBreakpoint)!=null?tt:640,B=b.innerWidth<=W,V=T&&B&&w;try{if(V){cr(),Jr(e,r);return}if(M&&(M=!1,cr(),Jr(e,r)),!w&&!l){z.style.height="",z.style.width="";return}if(!m&&!l){let nn=(Et=(St=r==null?void 0:r.launcher)==null?void 0:St.width)!=null?Et:r==null?void 0:r.launcherWidth,Bt=nn!=null?nn:On;z.style.width=Bt,z.style.maxWidth=Bt}if(lr(),!y){let nn=b.innerHeight,Bt=64,An=(S=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?S:0,Kt=Math.max(200,nn-Bt),Ge=Math.min(640,Kt),mt=Math.max(200,Ge-An);z.style.height=`${mt}px`}}finally{if(Me(),ao(),P&&w){let Bt=((xe=e.ownerDocument.defaultView)!=null?xe:window).innerWidth<=((je=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?je:640),An=(_e=(vt=r.launcher)==null?void 0:vt.sidebarMode)!=null?_e:!1,Kt=(en=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?en:!0,Ge=Yt(r)&&Kt&&Bt,mt=An||Kt&&Bt&&w||Ge;if(mt&&!Vt){let pr=e.getRootNode(),ur=pr instanceof ShadowRoot?pr.host:e.closest(".persona-host");ur&&!zt&&(zt=hi(ur,(Qn=(tn=r.launcher)==null?void 0:tn.zIndex)!=null?Qn:Tn)),Vt=yi(e.ownerDocument)}else mt||(zt==null||zt(),zt=null,Vt==null||Vt(),Vt=null)}}};qr();let us=(Ml=e.ownerDocument.defaultView)!=null?Ml:window;if(us.addEventListener("resize",qr),At.push(()=>us.removeEventListener("resize",qr)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Me()});l.observe(se),At.push(()=>l.disconnect())}bn=q.scrollTop;let ms=q.scrollHeight,gs=()=>{let l=q.scrollTop,m=q.scrollHeight,y=m<ms;ms=m;let{action:b,nextLastScrollTop:T}=ka({following:ce.isFollowing(),currentScrollTop:l,lastScrollTop:bn,nearBottom:Ps(q,rs),userScrollThreshold:zs,isAutoScrolling:xr||ro||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(bn=T,b==="resume"){_r();return}b==="pause"&&as()};q.addEventListener("scroll",gs,{passive:!0}),At.push(()=>q.removeEventListener("scroll",gs));let fs=l=>{let m=La({following:ce.isFollowing(),deltaY:l.deltaY,nearBottom:Ps(q,rs),resumeWhenNearBottom:!0});m==="pause"?as():m==="resume"&&_r()};q.addEventListener("wheel",fs,{passive:!0}),At.push(()=>q.removeEventListener("wheel",fs)),ht.addEventListener("click",()=>{q.scrollTop=q.scrollHeight,bn=q.scrollTop,_r(),jr(!0)}),At.push(()=>ht.remove()),At.push(()=>{ss()});let hs=()=>{he&&(Bn&&(he.removeEventListener("click",Bn),Bn=null),w?(he.style.display="",Bn=()=>{_t(!1,"user")},he.addEventListener("click",Bn)):he.style.display="none")};hs(),(()=>{let{clearChatButton:l}=ne;l&&l.addEventListener("click",()=>{F.clearMessages(),Vn.clear(),_r(),Zr(ne.composerOverlay);try{localStorage.removeItem(ns),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ns}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ns)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let 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(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},E.syncFromMetadata(),de==null||de.clear(),X==null||X.update()})})(),xt&&xt.addEventListener("submit",ls),ee==null||ee.addEventListener("keydown",cs),ee==null||ee.addEventListener("paste",ds);let ys="persona-attachment-drop-active",zr=0,No=()=>{zr=0,_.classList.remove(ys)},Sr=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&ze!==null},po=l=>{!Va(l.dataTransfer)||!Sr()||(zr++,zr===1&&_.classList.add(ys))},Ve=l=>{!Va(l.dataTransfer)||!Sr()||(zr--,zr<=0&&No())},x=l=>{!Va(l.dataTransfer)||!Sr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},O=l=>{var y;if(!Va(l.dataTransfer)||!Sr())return;l.preventDefault(),l.stopPropagation(),No();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&ze.handleFiles(m)},C=!0;_.addEventListener("dragenter",po,C),_.addEventListener("dragleave",Ve,C),e.addEventListener("dragover",x,C),e.addEventListener("drop",O,C);let J=e.ownerDocument,He=l=>{Sr()&&l.preventDefault()},te=l=>{Sr()&&l.preventDefault()};J.addEventListener("dragover",He),J.addEventListener("drop",te),At.push(()=>{xt&&xt.removeEventListener("submit",ls),ee==null||ee.removeEventListener("keydown",cs),ee==null||ee.removeEventListener("paste",ds)}),At.push(()=>{_.removeEventListener("dragenter",po,C),_.removeEventListener("dragleave",Ve,C),e.removeEventListener("dragover",x,C),e.removeEventListener("drop",O,C),J.removeEventListener("dragover",He),J.removeEventListener("drop",te),No()}),At.push(()=>{F.cancel()}),jt?At.push(()=>{jt==null||jt.destroy()}):Ut&&At.push(()=>{Ut==null||Ut.remove()});let We={update(l){var Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,Ul,ql,zl,Vl,Jl,Kl,Gl,Ql,Yl,Xl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac,Sc,Ec,Tc,Mc,kc,Lc,Ic,Pc,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,qc,zc,Vc,Jc,Kc,Gc,Qc,Yc,Xc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,Md,kd,Ld,Id,Pd,Wd,Rd,Hd;let m=r.toolCall,y=r.messageActions,b=(Hl=r.layout)==null?void 0:Hl.messages,T=r.colorScheme,W=r.loadingIndicator,B=r.iterationDisplay,V=(Bl=r.features)==null?void 0:Bl.showReasoning,$=(Dl=r.features)==null?void 0:Dl.showToolCalls,Se=(Nl=r.features)==null?void 0:Nl.toolCallDisplay,ye=(Fl=r.features)==null?void 0:Fl.reasoningDisplay;r={...r,...l},cr(),Jr(e,r),Na(e,r),Fa(e,r),Rn(),r.colorScheme!==T&&Or();let ke=_s.getForInstance(r.plugins);s.length=0,s.push(...ke),w=($l=(Ol=r.launcher)==null?void 0:Ol.enabled)!=null?$l:!0,A=(jl=(_l=r.launcher)==null?void 0:_l.autoExpand)!=null?jl:!1,ie=(ql=(Ul=r.features)==null?void 0:Ul.showReasoning)!=null?ql:!0,ve=(Vl=(zl=r.features)==null?void 0:zl.showToolCalls)!=null?Vl:!0,Oe=(Kl=(Jl=r.features)==null?void 0:Jl.scrollToBottom)!=null?Kl:{},st(),wr();let be=ue;if(ue=(Ql=(Gl=r.features)==null?void 0:Gl.showEventStreamToggle)!=null?Ql:!1,ue&&!be){if(de||(Le=new $s(De),de=new Os(Ne,Le),Le.open().then(()=>de==null?void 0:de.restore()).catch(()=>{}),F.setSSEEventCallback((Y,wt)=>{var Dt;(Dt=r.onSSEEvent)==null||Dt.call(r,Y,wt),de.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(wt)})})),!rt&&D){let Y=(Xl=(Yl=r.features)==null?void 0:Yl.eventStream)==null?void 0:Xl.classNames,wt="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:"");rt=h("button",wt),rt.style.width="28px",rt.style.height="28px",rt.style.color=Mn.actionIconColor,rt.type="button",rt.setAttribute("aria-label","Event Stream"),rt.title="Event Stream";let Dt=Ae("activity","18px","currentColor",1.5);Dt&&rt.appendChild(Dt);let at=ne.clearChatButtonWrapper,Tt=ne.closeButtonWrapper,Qt=at||Tt;Qt&&Qt.parentNode===D?D.insertBefore(rt,Qt):D.appendChild(rt),rt.addEventListener("click",()=>{ge?dn():$n()})}}else!ue&&be&&(dn(),rt&&(rt.remove(),rt=null),de==null||de.clear(),Le==null||Le.destroy(),de=null,Le=null);if(((Zl=r.launcher)==null?void 0:Zl.enabled)===!1&&jt&&(jt.destroy(),jt=null),((ec=r.launcher)==null?void 0:ec.enabled)===!1&&Ut&&(Ut.remove(),Ut=null),((tc=r.launcher)==null?void 0:tc.enabled)!==!1&&!jt&&!Ut){let Y=s.find(wt=>wt.renderLauncher);if(Y!=null&&Y.renderLauncher){let wt=Y.renderLauncher({config:r,defaultRenderer:()=>Bs(r,Ar).element,onToggle:Ar});wt&&(Ut=wt,e.appendChild(Ut))}Ut||(jt=Bs(r,Ar),e.appendChild(jt.element))}jt&&jt.update(r),Ot&&((nc=r.launcher)==null?void 0:nc.title)!==void 0&&(Ot.textContent=r.launcher.title),$t&&((rc=r.launcher)==null?void 0:rc.subtitle)!==void 0&&($t.textContent=r.launcher.subtitle);let $e=(oc=r.layout)==null?void 0:oc.header;if(($e==null?void 0:$e.layout)!==L&&D){let Y=$e?Vo(r,$e,{showClose:w,onClose:()=>_t(!1,"user")}):kr({config:r,showClose:w,onClose:()=>_t(!1,"user")});D.replaceWith(Y.header),D=Y.header,Ye=Y.iconHolder,Ot=Y.headerTitle,$t=Y.headerSubtitle,he=Y.closeButton,L=$e==null?void 0:$e.layout}else if($e&&(Ye&&(Ye.style.display=$e.showIcon===!1?"none":""),Ot&&(Ot.style.display=$e.showTitle===!1?"none":""),$t&&($t.style.display=$e.showSubtitle===!1?"none":""),he&&(he.style.display=$e.showCloseButton===!1?"none":""),ne.clearChatButtonWrapper)){let Y=$e.showClearChat;if(Y!==void 0){ne.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:wt}=ne;wt&&!wt.classList.contains("persona-absolute")&&(Y?wt.classList.remove("persona-ml-auto"):wt.classList.add("persona-ml-auto"))}}let ut=((sc=r.layout)==null?void 0:sc.showHeader)!==!1;D&&(D.style.display=ut?"":"none");let tt=((ac=r.layout)==null?void 0:ac.showFooter)!==!1;se&&(se.style.display=tt?"":"none"),Me(),wr(),w!==k?w?_t(A,"auto"):(P=!0,ao()):A!==U&&_t(A,"auto"),U=A,k=w,qr(),hs();let Be=JSON.stringify(l.toolCall)!==JSON.stringify(m),S=JSON.stringify(r.messageActions)!==JSON.stringify(y),xe=JSON.stringify((ic=r.layout)==null?void 0:ic.messages)!==JSON.stringify(b),Ce=((lc=r.loadingIndicator)==null?void 0:lc.render)!==(W==null?void 0:W.render)||((cc=r.loadingIndicator)==null?void 0:cc.renderIdle)!==(W==null?void 0:W.renderIdle)||((dc=r.loadingIndicator)==null?void 0:dc.showBubble)!==(W==null?void 0:W.showBubble),je=r.iterationDisplay!==B,vt=((uc=(pc=r.features)==null?void 0:pc.showReasoning)!=null?uc:!0)!==(V!=null?V:!0)||((gc=(mc=r.features)==null?void 0:mc.showToolCalls)!=null?gc:!0)!==($!=null?$:!0)||JSON.stringify((fc=r.features)==null?void 0:fc.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((hc=r.features)==null?void 0:hc.reasoningDisplay)!==JSON.stringify(ye);(Be||S||xe||Ce||je||vt)&&F&&($r++,so(le,F.getMessages(),j));let we=(yc=r.launcher)!=null?yc:{},en=(bc=we.headerIconHidden)!=null?bc:!1,tn=(vc=(xc=r.layout)==null?void 0:xc.header)==null?void 0:vc.showIcon,Qn=en||tn===!1,nn=we.headerIconName,Bt=(wc=we.headerIconSize)!=null?wc:"48px";if(Ye){let Y=_.querySelector(".persona-border-b-persona-divider"),wt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(Qn)Ye.style.display="none",Y&&wt&&!Y.contains(wt)&&Y.insertBefore(wt,Y.firstChild);else{if(Ye.style.display="",Ye.style.height=Bt,Ye.style.width=Bt,Y&&wt&&(Y.contains(Ye)?Ye.nextSibling!==wt&&(Ye.remove(),Y.insertBefore(Ye,wt)):Y.insertBefore(Ye,wt)),nn){let at=parseFloat(Bt)||24,Tt=Ae(nn,at*.6,"#ffffff",2);Tt?Ye.replaceChildren(Tt):Ye.textContent=(Cc=we.agentIconText)!=null?Cc:"\u{1F4AC}"}else if(we.iconUrl){let at=Ye.querySelector("img");if(at)at.src=we.iconUrl,at.style.height=Bt,at.style.width=Bt;else{let Tt=document.createElement("img");Tt.src=we.iconUrl,Tt.alt="",Tt.className="persona-rounded-xl persona-object-cover",Tt.style.height=Bt,Tt.style.width=Bt,Ye.replaceChildren(Tt)}}else{let at=Ye.querySelector("svg"),Tt=Ye.querySelector("img");(at||Tt)&&Ye.replaceChildren(),Ye.textContent=(Ac=we.agentIconText)!=null?Ac:"\u{1F4AC}"}let Dt=Ye.querySelector("img");Dt&&(Dt.style.height=Bt,Dt.style.width=Bt)}}let An=(Ec=(Sc=r.layout)==null?void 0:Sc.header)==null?void 0:Ec.showTitle,Kt=(Mc=(Tc=r.layout)==null?void 0:Tc.header)==null?void 0:Mc.showSubtitle;if(Ot&&(Ot.style.display=An===!1?"none":""),$t&&($t.style.display=Kt===!1?"none":""),he){((Lc=(kc=r.layout)==null?void 0:kc.header)==null?void 0:Lc.showCloseButton)===!1?he.style.display="none":he.style.display="";let wt=(Ic=we.closeButtonSize)!=null?Ic:"32px",Dt=(Pc=we.closeButtonPlacement)!=null?Pc:"inline";he.style.height=wt,he.style.width=wt;let{closeButtonWrapper:at}=ne,Tt=Dt==="top-right",Qt=at==null?void 0:at.classList.contains("persona-absolute");if(at&&Tt!==Qt)if(at.remove(),Tt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(at);else{let gt=(Rc=(Wc=we.clearChat)==null?void 0:Wc.placement)!=null?Rc:"inline",on=(Bc=(Hc=we.clearChat)==null?void 0:Hc.enabled)!=null?Bc:!0;at.className=on&&gt==="inline"?"":"persona-ml-auto";let En=_.querySelector(".persona-border-b-persona-divider");En&&En.appendChild(at)}if(he.style.color=we.closeButtonColor||Mn.actionIconColor,we.closeButtonBackgroundColor?(he.style.backgroundColor=we.closeButtonBackgroundColor,he.classList.remove("hover:persona-bg-gray-100")):(he.style.backgroundColor="",he.classList.add("hover:persona-bg-gray-100")),we.closeButtonBorderWidth||we.closeButtonBorderColor){let gt=we.closeButtonBorderWidth||"0px",on=we.closeButtonBorderColor||"transparent";he.style.border=`${gt} solid ${on}`,he.classList.remove("persona-border-none")}else he.style.border="",he.classList.add("persona-border-none");we.closeButtonBorderRadius?(he.style.borderRadius=we.closeButtonBorderRadius,he.classList.remove("persona-rounded-full")):(he.style.borderRadius="",he.classList.add("persona-rounded-full")),we.closeButtonPaddingX?(he.style.paddingLeft=we.closeButtonPaddingX,he.style.paddingRight=we.closeButtonPaddingX):(he.style.paddingLeft="",he.style.paddingRight=""),we.closeButtonPaddingY?(he.style.paddingTop=we.closeButtonPaddingY,he.style.paddingBottom=we.closeButtonPaddingY):(he.style.paddingTop="",he.style.paddingBottom="");let gn=(Dc=we.closeButtonIconName)!=null?Dc:"x",ar=(Nc=we.closeButtonIconText)!=null?Nc:"\xD7";he.innerHTML="";let wn=Ae(gn,"28px","currentColor",1);wn?he.appendChild(wn):he.textContent=ar;let Gt=(Fc=we.closeButtonTooltipText)!=null?Fc:"Close chat",Fn=(Oc=we.closeButtonShowTooltip)!=null?Oc:!0;if(he.setAttribute("aria-label",Gt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Fn&&Gt)){let gt=null,on=()=>{if(gt||!he)return;let ho=he.ownerDocument,bs=ho.body;if(!bs)return;gt=gr(ho,"div","persona-clear-chat-tooltip"),gt.textContent=Gt;let xs=gr(ho,"div");xs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(xs);let yo=he.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(Kr),gt.style.left=`${yo.left+yo.width/2}px`,gt.style.top=`${yo.top-8}px`,gt.style.transform="translate(-50%, -100%)",bs.appendChild(gt)},En=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};at.addEventListener("mouseenter",on),at.addEventListener("mouseleave",En),he.addEventListener("focus",on),he.addEventListener("blur",En),at._cleanupTooltip=()=>{En(),at&&(at.removeEventListener("mouseenter",on),at.removeEventListener("mouseleave",En)),he&&(he.removeEventListener("focus",on),he.removeEventListener("blur",En))}}}let{clearChatButton:Ge,clearChatButtonWrapper:mt}=ne;if(Ge){let Y=($c=we.clearChat)!=null?$c:{},wt=(_c=Y.enabled)!=null?_c:!0,Dt=(Uc=(jc=r.layout)==null?void 0:jc.header)==null?void 0:Uc.showClearChat,at=Dt!==void 0?Dt:wt,Tt=(qc=Y.placement)!=null?qc:"inline";if(mt){mt.style.display=at?"":"none";let{closeButtonWrapper:Qt}=ne;Qt&&!Qt.classList.contains("persona-absolute")&&(at?Qt.classList.remove("persona-ml-auto"):Qt.classList.add("persona-ml-auto"));let gn=Tt==="top-right",ar=mt.classList.contains("persona-absolute");if(gn!==ar&&at){if(mt.remove(),gn)mt.className="persona-absolute persona-top-4 persona-z-50",mt.style.right="48px",_.style.position="relative",_.appendChild(mt);else{mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mt.style.right="";let Gt=_.querySelector(".persona-border-b-persona-divider"),Fn=ne.closeButtonWrapper;Gt&&Fn&&Fn.parentElement===Gt?Gt.insertBefore(mt,Fn):Gt&&Gt.appendChild(mt)}let wn=ne.closeButtonWrapper;wn&&!wn.classList.contains("persona-absolute")&&(gn?wn.classList.add("persona-ml-auto"):wn.classList.remove("persona-ml-auto"))}}if(at){let Qt=(zc=Y.size)!=null?zc:"32px";Ge.style.height=Qt,Ge.style.width=Qt;let gn=(Vc=Y.iconName)!=null?Vc:"refresh-cw",ar=(Jc=Y.iconColor)!=null?Jc:"";Ge.style.color=ar||Mn.actionIconColor,Ge.innerHTML="";let wn=Ae(gn,"20px","currentColor",2);if(wn&&Ge.appendChild(wn),Y.backgroundColor?(Ge.style.backgroundColor=Y.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let gt=Y.borderWidth||"0px",on=Y.borderColor||"transparent";Ge.style.border=`${gt} solid ${on}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");Y.borderRadius?(Ge.style.borderRadius=Y.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),Y.paddingX?(Ge.style.paddingLeft=Y.paddingX,Ge.style.paddingRight=Y.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),Y.paddingY?(Ge.style.paddingTop=Y.paddingY,Ge.style.paddingBottom=Y.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Gt=(Kc=Y.tooltipText)!=null?Kc:"Clear chat",Fn=(Gc=Y.showTooltip)!=null?Gc:!0;if(Ge.setAttribute("aria-label",Gt),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),Fn&&Gt)){let gt=null,on=()=>{if(gt||!Ge)return;let ho=Ge.ownerDocument,bs=ho.body;if(!bs)return;gt=gr(ho,"div","persona-clear-chat-tooltip"),gt.textContent=Gt;let xs=gr(ho,"div");xs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(xs);let yo=Ge.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(Kr),gt.style.left=`${yo.left+yo.width/2}px`,gt.style.top=`${yo.top-8}px`,gt.style.transform="translate(-50%, -100%)",bs.appendChild(gt)},En=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};mt.addEventListener("mouseenter",on),mt.addEventListener("mouseleave",En),Ge.addEventListener("focus",on),Ge.addEventListener("blur",En),mt._cleanupTooltip=()=>{En(),mt&&(mt.removeEventListener("mouseenter",on),mt.removeEventListener("mouseleave",En)),Ge&&(Ge.removeEventListener("focus",on),Ge.removeEventListener("blur",En))}}}}let pr=r.actionParsers&&r.actionParsers.length?r.actionParsers:[js],ur=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ko.message,ko.messageAndClick];E=Us({parsers:pr,handlers:ur,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),j=cu(r,E,G),F.updateConfig(r),so(le,F.getMessages(),j),nr.render(r.suggestionChips,F,ee,void 0,r.suggestionChipsConfig),is(),Ro(F.isStreaming());let uo=((Qc=r.voiceRecognition)==null?void 0:Qc.enabled)===!0,mo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),go=((Xc=(Yc=r.voiceRecognition)==null?void 0:Yc.provider)==null?void 0:Xc.type)==="runtype";if(uo&&(mo||go))if(!H||!Te){let Y=Zs(r.voiceRecognition,r.sendButton);Y&&(H=Y.micButton,Te=Y.micButtonWrapper,Qe.insertBefore(Te,Lt),H.addEventListener("click",co),H.disabled=F.isStreaming())}else{let Y=(Zc=r.voiceRecognition)!=null?Zc:{},wt=(ed=r.sendButton)!=null?ed:{},Dt=(td=Y.iconName)!=null?td:"mic",at=(nd=wt.size)!=null?nd:"40px",Tt=(rd=Y.iconSize)!=null?rd:at,Qt=parseFloat(Tt)||24;H.style.width=Tt,H.style.height=Tt,H.style.minWidth=Tt,H.style.minHeight=Tt;let gn=(sd=(od=Y.iconColor)!=null?od:wt.textColor)!=null?sd:"currentColor";H.innerHTML="";let ar=Ae(Dt,Qt,gn,2);ar?H.appendChild(ar):H.textContent="\u{1F3A4}";let wn=(ad=Y.backgroundColor)!=null?ad:wt.backgroundColor;wn?H.style.backgroundColor=wn:H.style.backgroundColor="",gn?H.style.color=gn:H.style.color="var(--persona-text, #111827)",Y.borderWidth?(H.style.borderWidth=Y.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),Y.borderColor?H.style.borderColor=Y.borderColor:H.style.borderColor="",Y.paddingX?(H.style.paddingLeft=Y.paddingX,H.style.paddingRight=Y.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),Y.paddingY?(H.style.paddingTop=Y.paddingY,H.style.paddingBottom=Y.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Gt=Te==null?void 0:Te.querySelector(".persona-send-button-tooltip"),Fn=(id=Y.tooltipText)!=null?id:"Start voice recognition";if(((ld=Y.showTooltip)!=null?ld:!1)&&Fn)if(Gt)Gt.textContent=Fn,Gt.style.display="";else{let on=document.createElement("div");on.className="persona-send-button-tooltip",on.textContent=Fn,Te==null||Te.insertBefore(on,H)}else Gt&&(Gt.style.display="none");Te.style.display="",H.disabled=F.isStreaming()}else H&&Te&&(Te.style.display="none",((dd=(cd=r.voiceRecognition)==null?void 0:cd.provider)==null?void 0:dd.type)==="runtype"?F.isVoiceActive()&&F.toggleVoice():Nn&&or());if(((pd=r.attachments)==null?void 0:pd.enabled)===!0)if(!ct||!Fe){let Y=(ud=r.attachments)!=null?ud:{},Dt=(gd=((md=r.sendButton)!=null?md:{}).size)!=null?gd:"40px";re||(re=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),re.style.display="none",xt.insertBefore(re,ee)),Z||(Z=document.createElement("input"),Z.type="file",Z.accept=((fd=Y.allowedTypes)!=null?fd:Mr).join(","),Z.multiple=((hd=Y.maxFiles)!=null?hd:4)>1,Z.style.display="none",Z.setAttribute("aria-label","Attach files"),xt.insertBefore(Z,ee)),ct=h("div","persona-send-button-wrapper"),Fe=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Fe.type="button",Fe.setAttribute("aria-label",(yd=Y.buttonTooltipText)!=null?yd:"Attach file");let at=(bd=Y.buttonIconName)!=null?bd:"paperclip",Tt=Dt,Qt=parseFloat(Tt)||40,gn=Math.round(Qt*.6);Fe.style.width=Tt,Fe.style.height=Tt,Fe.style.minWidth=Tt,Fe.style.minHeight=Tt,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.style.backgroundColor="transparent",Fe.style.color="var(--persona-primary, #111827)",Fe.style.border="none",Fe.style.borderRadius="6px",Fe.style.transition="background-color 0.15s ease",Fe.addEventListener("mouseenter",()=>{Fe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Fe.addEventListener("mouseleave",()=>{Fe.style.backgroundColor="transparent"});let ar=Ae(at,gn,"currentColor",1.5);ar?Fe.appendChild(ar):Fe.textContent="\u{1F4CE}",Fe.addEventListener("click",Fn=>{Fn.preventDefault(),Z==null||Z.click()}),ct.appendChild(Fe);let wn=(xd=Y.buttonTooltipText)!=null?xd:"Attach file",Gt=h("div","persona-send-button-tooltip");Gt.textContent=wn,ct.appendChild(Gt),Ue.append(ct),!ze&&Z&&re&&(ze=So.fromConfig(Y),ze.setPreviewsContainer(re),Z.addEventListener("change",async()=>{ze&&(Z!=null&&Z.files)&&(await ze.handleFileSelect(Z.files),Z.value="")})),_.querySelector(".persona-attachment-drop-overlay")||_.appendChild(du(Y.dropOverlay))}else{ct.style.display="";let Y=(vd=r.attachments)!=null?vd:{};Z&&(Z.accept=((wd=Y.allowedTypes)!=null?wd:Mr).join(","),Z.multiple=((Cd=Y.maxFiles)!=null?Cd:4)>1),ze&&ze.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else ct&&(ct.style.display="none"),ze&&ze.clearAttachments(),(Ad=_.querySelector(".persona-attachment-drop-overlay"))==null||Ad.remove();let Xe=(Sd=r.sendButton)!=null?Sd:{},Yn=(Ed=Xe.useIcon)!=null?Ed:!1,Xn=(Td=Xe.iconText)!=null?Td:"\u2191",mr=Xe.iconName,qt=(Md=Xe.tooltipText)!=null?Md:"Send message",Wt=(kd=Xe.showTooltip)!=null?kd:!1,rn=(Ld=Xe.size)!=null?Ld:"40px",Sn=Xe.backgroundColor,Er=Xe.textColor;if(Yn){if(ae.style.width=rn,ae.style.height=rn,ae.style.minWidth=rn,ae.style.minHeight=rn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Er?ae.style.color=Er:ae.style.color="var(--persona-button-primary-fg, #ffffff)",mr){let Y=parseFloat(rn)||24,wt=(Er==null?void 0:Er.trim())||"currentColor",Dt=Ae(mr,Y,wt,2);Dt?ae.appendChild(Dt):ae.textContent=Xn}else ae.textContent=Xn;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Sn?(ae.style.backgroundColor=Sn,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=(Pd=(Id=r.copy)==null?void 0:Id.sendButtonLabel)!=null?Pd:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.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",Sn?(ae.style.backgroundColor=Sn,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Er?ae.style.color=Er:ae.classList.add("persona-text-white");Xe.borderWidth?(ae.style.borderWidth=Xe.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),Xe.borderColor?ae.style.borderColor=Xe.borderColor:ae.style.borderColor="",Xe.paddingX?(ae.style.paddingLeft=Xe.paddingX,ae.style.paddingRight=Xe.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),Xe.paddingY?(ae.style.paddingTop=Xe.paddingY,ae.style.paddingBottom=Xe.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Vr=Lt==null?void 0:Lt.querySelector(".persona-send-button-tooltip");if(Wt&&qt)if(Vr)Vr.textContent=qt,Vr.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=qt,Lt==null||Lt.insertBefore(Y,ae)}else Vr&&(Vr.style.display="none");let vn=(Wd=r.layout)==null?void 0:Wd.contentMaxWidth;vn?(le.style.maxWidth=vn,le.style.marginLeft="auto",le.style.marginRight="auto",le.style.width="100%",xt&&(xt.style.maxWidth=vn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Ee&&(Ee.style.maxWidth=vn,Ee.style.marginLeft="auto",Ee.style.marginRight="auto")):(le.style.maxWidth="",le.style.marginLeft="",le.style.marginRight="",le.style.width="",xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""),Ee&&(Ee.style.maxWidth="",Ee.style.marginLeft="",Ee.style.marginRight=""));let mn=(Rd=r.statusIndicator)!=null?Rd:{},fo=(Hd=mn.visible)!=null?Hd:!0;if(Ke.style.display=fo?"":"none",F){let Y=F.getStatus();Pe(Ke,(Dt=>{var at,Tt,Qt,gn;return Dt==="idle"?(at=mn.idleText)!=null?at:fn.idle:Dt==="connecting"?(Tt=mn.connectingText)!=null?Tt:fn.connecting:Dt==="connected"?(Qt=mn.connectedText)!=null?Qt:fn.connected:Dt==="error"?(gn=mn.errorText)!=null?gn:fn.error:fn[Dt]})(Y),mn,Y)}Ke.classList.remove("persona-text-left","persona-text-center","persona-text-right");let oa=mn.align==="left"?"persona-text-left":mn.align==="center"?"persona-text-center":"persona-text-right";Ke.classList.add(oa)},open(){w&&_t(!0,"api")},close(){w&&_t(!1,"api")},toggle(){w&&_t(!P,"api")},clearChat(){hn=!1,F.clearMessages(),Vn.clear(),_r();try{localStorage.removeItem(ns),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ns}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ns)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.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={},E.syncFromMetadata(),de==null||de.clear(),X==null||X.update()},setMessage(l){return!ee||F.isStreaming()?!1:(!P&&w&&_t(!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?(!P&&w&&_t(!0,"system"),ee.value="",ee.style.height="auto",F.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return F.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(F.isVoiceActive()||(!P&&w&&_t(!0,"system"),pt.manuallyDeactivated=!1,Cn(),F.toggleVoice().then(()=>{pt.active=F.isVoiceActive(),Kn("user"),F.isVoiceActive()&&Ur()})),!0):Nn?!0:ps()?(!P&&w&&_t(!0,"system"),pt.manuallyDeactivated=!1,Cn(),io("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Cn(),Kn("user"),sr()}),!0):!1:Nn?(pt.manuallyDeactivated=!0,Cn(),or("user"),!0):!1},injectMessage(l){return!P&&w&&_t(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!P&&w&&_t(!0,"system");let m=F.injectAssistantMessage(l);return N&&(N=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),m},injectUserMessage(l){return!P&&w&&_t(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!P&&w&&_t(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!P&&w&&_t(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!P&&w&&_t(!0,"system"),F.injectTestEvent(l)},async connectStream(l,m){return F.connectStream(l,m)},__pushEventStreamEvent(l){de&&de.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ue||!de||$n()},hideEventStream(){ge&&dn()},isEventStreamVisible(){return ge},showArtifacts(){tr(r)&&(hn=!1,Rn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){tr(r)&&(hn=!0,Rn())},upsertArtifact(l){return tr(r)?(hn=!1,F.upsertArtifact(l)):null},selectArtifact(l){tr(r)&&F.selectArtifact(l)},clearArtifacts(){tr(r)&&F.clearArtifacts()},getArtifacts(){var l;return(l=F==null?void 0:F.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=F==null?void 0:F.getSelectedArtifactId())!=null?l:null},focusInput(){return w&&!P||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,m){let b=F.getMessages().find(T=>{var W;return T.variant==="approval"&&((W=T.approval)==null?void 0:W.id)===l});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${l}`);return F.resolveApproval(b.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 w&&P},isVoiceActive(){return pt.active},getState(){return{open:w&&P,launcherEnabled:w,voiceActive:pt.active,streaming:F.isStreaming()}},showCSATFeedback(l){!P&&w&&_t(!0,"system");let m=le.querySelector(".persona-feedback-container");m&&m.remove();let y=qa({onSubmit:async(b,T)=>{var W;F.isClientTokenMode()&&await F.submitCSATFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!P&&w&&_t(!0,"system");let m=le.querySelector(".persona-feedback-container");m&&m.remove();let y=za({onSubmit:async(b,T)=>{var W;F.isClientTokenMode()&&await F.submitNPSFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});le.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(){dr!=null&&(clearInterval(dr),dr=null),At.forEach(l=>l()),R.remove(),jt==null||jt.destroy(),Ut==null||Ut.remove(),Bn&&he.removeEventListener("click",Bn)}};if((((kl=t==null?void 0:t.debugTools)!=null?kl:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:We,getMessages:We.getMessages,getStatus:We.getStatus,getMetadata:We.getPersistentMetadata,updateMetadata:We.updatePersistentMetadata,clearHistory:()=>We.clearChat(),setVoiceActive:y=>y?We.startVoiceRecognition():We.stopVoiceRecognition()};window.AgentWidgetBrowser=m,At.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=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&We.focusInput()};if(window.addEventListener("persona:focusInput",m),At.push(()=>{window.removeEventListener("persona:focusInput",m)}),ue){let V=Se=>{let ye=Se.detail;(!(ye!=null&&ye.instanceId)||ye.instanceId===l)&&We.showEventStream()},$=Se=>{let ye=Se.detail;(!(ye!=null&&ye.instanceId)||ye.instanceId===l)&&We.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",$),At.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",$)})}let y=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&We.showArtifacts()},b=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&We.hideArtifacts()},T=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||$!=null&&$.artifact&&We.upsertArtifact($.artifact)},W=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||typeof($==null?void 0:$.id)=="string"&&We.selectArtifact($.id)},B=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&We.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",B),At.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",B)})}let lt=qg(r.persistState);if(lt&&w){let l=zg(lt.storage),m=`${lt.keyPrefix}widget-open`,y=`${lt.keyPrefix}widget-voice`,b=`${lt.keyPrefix}widget-voice-mode`;if(l){let T=((Ll=lt.persist)==null?void 0:Ll.openState)&&l.getItem(m)==="true",W=((Il=lt.persist)==null?void 0:Il.voiceState)&&l.getItem(y)==="true",B=((Pl=lt.persist)==null?void 0:Pl.voiceState)&&l.getItem(b)==="true";if(T&&setTimeout(()=>{We.open(),setTimeout(()=>{var V;if(W||B)We.startVoiceRecognition();else if((V=lt.persist)!=null&&V.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),(Wl=lt.persist)!=null&&Wl.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(Rl=lt.persist)!=null&&Rl.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(b,V.viaVoice?"true":"false")})),lt.clearOnChatClear){let V=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(b)},$=()=>V();window.addEventListener("persona:clear-chat",$),At.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}return c&&w&&setTimeout(()=>{We.open()},0),We};var Vg=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},pu=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},ji=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=""},uu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ji(e)},Oi=e=>{e.style.transition=""},$i=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=""},_i=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ka=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Jg=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Kg=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},mu=(e,n,t,r,s,o,a)=>{var v,E,w,A,I,U;let i=Zn(o),p=i.reveal==="push";Jg(e,n,t,r,p),Kg(e,n,t,r,i.side,p),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,u=(E=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?E:!0,d=(A=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileBreakpoint)!=null?A:640,f=c!=null?c.innerWidth<=d:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$i(n),Oi(r),uu(r),_i(t),Ka(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((U=(I=o==null?void 0:o.launcher)==null?void 0:I.zIndex)!=null?U:Tn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",p&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),uu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",$i(n),Oi(r),_i(t),Ka(s,r);let k=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":L;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=k,r.style.transform=M,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Oi(r),ji(r),Ka(s,r);let k=Vg(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),M=i.animate?"transform 180ms ease":"none",P=i.side==="right"?a?`translateX(-${k}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${k}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${L+k}px`,n.style.transition=M,n.style.transform=P,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",$i(n),ji(r),_i(t),Ka(s,r);let k=i.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",M=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",P=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",r.style.position="relative",r.style.overflow=k||P?"hidden":"visible",r.style.transition=M,k&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Gg=(e,n)=>{let t=e.ownerDocument.createElement("div");return pu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){pu(t,r)},destroy(){t.remove()}}},Qg=(e,n)=>{var I,U,k,L;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),p=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),d=(U=(I=n==null?void 0:n.launcher)==null?void 0:I.enabled)==null||U?(L=(k=n==null?void 0:n.launcher)==null?void 0:k.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),r.insertBefore(a,e),p.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),Zn(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{mu(a,i,p,c,u,n,d)}),f.observe(a))},E=()=>{mu(a,i,p,c,u,n,d),v()},w=a.ownerDocument.defaultView,A=()=>{E()};return w==null||w.addEventListener("resize",A),Zn(n).reveal==="push"?(i.appendChild(p),i.appendChild(c),a.appendChild(i)):(a.appendChild(p),a.appendChild(c)),E(),{mode:"docked",host:u,shell:a,syncWidgetState(M){let P=M.launcherEnabled?M.open:!0;d!==P&&(d=P,E())},updateConfig(M){var P,N;n=M,((N=(P=n==null?void 0:n.launcher)==null?void 0:P.enabled)!=null?N:!0)===!1&&(d=!0),E()},destroy(){w==null||w.removeEventListener("resize",A),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},qs=(e,n)=>Yt(n)?Qg(e,n):Gg(e,n);var Ui={},Yg=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Xg=()=>{try{if(typeof Ui!="undefined"&&Ui.url)return new URL("../widget.css",Ui.url).href}catch{}return null},gu=(e,n)=>{let t=Xg(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},qi=e=>{var w;let n=Yg(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=qs(n,s),a,i=[],p=(A,I)=>{var M,P;let k=!((P=(M=I==null?void 0:I.launcher)==null?void 0:M.enabled)!=null?P:!0)||Yt(I),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),k&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let N=A.attachShadow({mode:"open"});N.appendChild(L),gu(N,r)}else A.appendChild(L),gu(A,r);return n.id&&L.setAttribute("data-persona-instance",n.id),L},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let A=p(o.host,s);a=Ja(A,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(A=>A()),i=[],a.destroy()};d(),(w=e.onReady)==null||w.call(e);let g=A=>{f(),o.destroy(),o=qs(n,A),s=A,d()},v={update(A){var L,M,P,N,K,G;let I={...s,...A,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(M=A==null?void 0:A.launcher)!=null?M:{},dock:{...(N=(P=s==null?void 0:s.launcher)==null?void 0:P.dock)!=null?N:{},...(G=(K=A==null?void 0:A.launcher)==null?void 0:K.dock)!=null?G:{}}}},U=Yt(s),k=Yt(I);if(U!==k){g(I);return}s=I,o.updateConfig(s),a.update(A),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},E=new Proxy(v,{get(A,I,U){if(I==="host")return o.host;if(I in A)return Reflect.get(A,I,U);let k=a[I];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=E),E};var xu=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Zg=new Set(["button","a","input","select","textarea","details","summary"]),ef=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zi=/\b(product|card|item|listing|result)\b/i,Ji=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,tf=3e3,nf=100;function vu(e){let n=typeof e.className=="string"?e.className:"";if(zi.test(n)||e.id&&zi.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&zi.test(r.value))return!0}return!1}function wu(e){var n;return Ji.test(((n=e.textContent)!=null?n:"").trim())}function Cu(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function rf(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function fu(e){let n=e.match(Ji);return n?n[0]:null}function hu(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function of(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var sf="commerce-card",af="result-card";function yu(e){return!vu(e)||!wu(e)||!Cu(e)&&!rf(e)?0:5200}function bu(e){var r;return!vu(e)||wu(e)||!Cu(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ki=[{id:sf,scoreElement(e){return yu(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||Ji.test(r)&&r.length<32)}return!0},formatSummary(e,n){var p,c,u;if(yu(e)===0)return null;let{title:t,href:r}=hu(e),s=(u=(c=fu(((p=e.textContent)!=null?p:"").trim()))!=null?c:fu(n.text))!=null?u:"",o=of(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
101
- `)}},{id:af,scoreElement(e){return bu(e)},formatSummary(e,n){if(bu(e)===0)return null;let{title:t,href:r}=hu(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
102
- `)}}];function lf(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function cf(e){var u,d,f,g,v,E,w,A,I,U,k,L,M;let n=(u=e.options)!=null?u:{},t=(f=(d=n.maxElements)!=null?d:e.maxElements)!=null?f:80,r=(v=(g=n.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",s=(w=(E=n.maxTextLength)!=null?E:e.maxTextLength)!=null?w:200,o=(I=(A=n.visibleOnly)!=null?A:e.visibleOnly)!=null?I:!0,a=(U=n.root)!=null?U:e.root,i=(k=n.mode)!=null?k:"structured",p=(L=n.maxCandidates)!=null?L:Math.max(500,t*10),c=(M=e.rules)!=null?M:Ki;return i==="simple"&&e.rules&&e.rules.length>0?(lf(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:p,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function Vi(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var df=["data-testid","data-product","data-action","data-id","data-name","data-type"];function pf(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||Zg.has(n)||t&&ef.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Au(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function uf(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let p=e.getAttribute("role");p&&(n.role=p);for(let c=0;c<e.attributes.length;c++){let u=e.attributes[c];u.name.startsWith("data-")&&(n[u.name]=u.value)}return n}function Gi(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${Vi(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of df){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${Vi(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>Vi(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let p=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function mf(e){return e==="static"?nf:tf}function Su(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:Gi(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:pf(e),attributes:uf(e)}}function gf(e,n,t,r){let s=mf(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function ff(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function hf(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,u=c.tagName.toLowerCase();if(xu.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Au(c)){i=a.nextNode();continue}let d=Su(c,e.maxTextLength),f=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(w=>w==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(d.selector)){i=a.nextNode();continue}r.add(d.selector);let{score:v,formattingRule:E}=gf(c,d,e.rules,t);s.push({el:c,domIndex:o,enriched:d,score:v,formattingRule:E}),o+=1}i=a.nextNode()}s.sort((c,u)=>{let d=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return d!==f?d-f:u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex});let p=[];for(let c of s){if(p.length>=e.maxElements)break;ff(p,c)||p.push(c)}return p.sort((c,u)=>{let d=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return d!==f?d-f:d===1&&u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex}),p.map(c=>{var f;let u;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,t);g&&(u=g)}let d={...c.enriched};return u&&(d.formattedSummary=u),d})}function yf(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let p=o,c=p.tagName.toLowerCase();if(xu.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Au(p)){o=s.nextNode();continue}let u=Su(p,e.maxTextLength),d=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(g=>g==="role");if(!d&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let p of t)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function Eu(e={}){var r;let n=cf(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?yf(n,t):hf(n,t):[]}var Ga=100;function Tu(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
100
+ `}if(!b&&!c){let Ht="max-height: -moz-available !important; max-height: stretch !important;",qt=m?"":"padding-top: 1.25em !important;",Pn=m?"":`z-index: ${(Ut=(Rt=r.launcher)==null?void 0:Rt.zIndex)!=null?Ut:yn} !important;`;Q.style.cssText+=Ht+qt+Pn}E()};tr(),ro(e,r),ui(e,r),mi(e,r);let pt=[];pt.push(()=>{document.removeEventListener("keydown",zr)});let Kt=null,Gt=null;pt.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),Wn&&pt.push(()=>{Wn==null||Wn.disconnect(),Wn=null}),pt.push(()=>{xn==null||xn(),xn=null,Tr(),Mt&&(Mt.remove(),Mt=null),gt==null||gt.element.style.removeProperty("width"),gt==null||gt.element.style.removeProperty("maxWidth")}),he&&pt.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),oe==null||oe.destroy(),oe=null,X==null||X.destroy(),X=null,te=null});let Nn=null,Kr=()=>{Nn&&(Nn(),Nn=null),r.colorScheme==="auto"&&(Nn=qa(()=>{ro(e,r)}))};Kr(),pt.push(()=>{Nn&&(Nn(),Nn=null)});let Kn=(uc=r.features)==null?void 0:uc.streamAnimation;if(Kn!=null&&Kn.type&&Kn.type!=="none"){let c=js(Kn.type,Kn.plugins);c&&(Ui(c,e),pt.push(()=>au(e)))}let nr=Mu($t),Fn=null,U,pe=!1,On=Xp(),rr=new Map,hr=new Map,gs=0,or=Va(),sr=0,ar=null,kr=!1,ho=!1,ra=4,fs=24,oa=80,Uo=new Map,ct={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},hs=(gc=(mc=r.voiceRecognition)==null?void 0:mc.autoResume)!=null?gc:!1,Gn=c=>{o.emit("voice:state",{active:ct.active,source:c,timestamp:Date.now()})},kn=()=>{g(c=>({...c,voiceState:{active:ct.active,timestamp:Date.now(),manuallyDeactivated:ct.manuallyDeactivated}}))},sa=()=>{var b,k;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=pl(d.voiceState),m=!!c.active,y=Number((k=c.timestamp)!=null?k:0);ct.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-y<kf&&setTimeout(()=>{var D,F;ct.active||(ct.manuallyDeactivated=!1,((F=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:F.type)==="runtype"?U.toggleVoice().then(()=>{ct.active=U.isVoiceActive(),Gn("restore"),U.isVoiceActive()&&to()}):xo("restore"))},1e3)},aa=()=>U?ju(U.getMessages()).filter(c=>!c.__skipPersist):[];function jo(c){if(!(i!=null&&i.save))return;let y={messages:c?ju(c):U?aa():[],metadata:d,artifacts:Rn.artifacts,selectedArtifactId:Rn.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Mr=null,ia=()=>Q.querySelector("#persona-scroll-container")||fe,yo=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),kr=!1},ys=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null),ho=!1,yo()},Lr=()=>{if(!Et()||Le){lt.parentNode&&lt.remove(),lt.style.display="none";return}lt.parentNode!==ne&&ne.appendChild(lt),qn();let c=Os(fe)>0;lt.style.display=or.isFollowing()||!c?"none":""},bs=()=>{or.pause()&&(ys(),Lr())},Gr=()=>{or.resume(),Lr()},Qr=(c=!1)=>{or.isFollowing()&&(!c&&!pe||(ar!==null&&(cancelAnimationFrame(ar),ar=null),ho=!0,ar=requestAnimationFrame(()=>{ar=null,ho=!1,or.isFollowing()&&la(ia(),c?220:140)})))},la=(c,m=500)=>{let y=c.scrollTop,b=Os(c),k=b-y;if(Math.abs(k)<1){sr=c.scrollTop;return}if(Math.abs(k)>=oa){yo(),kr=!0,c.scrollTop=b,sr=c.scrollTop,kr=!1;return}yo();let D=performance.now();kr=!0;let F=W=>1-Math.pow(1-W,3),V=W=>{if(!or.isFollowing()){yo();return}let be=Os(c);be!==b&&(b=be,k=b-y);let ce=W-D,Z=Math.min(ce/m,1),me=F(Z),xe=y+k*me;c.scrollTop=xe,sr=c.scrollTop,Z<1?Mr=requestAnimationFrame(V):(c.scrollTop=b,sr=c.scrollTop,Mr=null,kr=!1)};Mr=requestAnimationFrame(V)},ca=c=>{let m=new Map;c.forEach(y=>{let b=Uo.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Uo.clear(),m.forEach((y,b)=>{Uo.set(b,y)})},bo=(c,m,y)=>{var Ve,rt,ot,Te,Se,_e;let b=document.createElement("div"),D=(()=>{var Ae;let E=s.find(Pe=>Pe.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((Ae=r.loadingIndicator)!=null&&Ae.render)return r.loadingIndicator.render})(),F=(E,Ae)=>Ae==null?!1:typeof Ae=="string"?(E.textContent=Ae,!0):(E.appendChild(Ae),!0),V=new Set,W=new Set,be=s.some(E=>E.renderAskUserQuestion),ce=[],Z=[],me=r.enableComponentStreaming!==!1;if(m.forEach(E=>{var wn,un,Qe,st,Cn,gn,wo,Co,Ao,Ko,Go,jt,So,no;V.add(E.id);let Ae=be&&Fr(E),Pe=!Ae&&E.role==="assistant"&&!E.variant&&me&&yi(E);if(!Pe&&hr.has(E.id)){let mt=c.querySelector(`#wrapper-${E.id}`);mt==null||mt.removeAttribute("data-preserve-runtime"),hr.delete(E.id)}let qe=Fr(E)?`:${(wn=E.agentMetadata)!=null&&wn.askUserQuestionAnswered?"a":"u"}:${(un=E.agentMetadata)!=null&&un.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",ye=Qp(E,gs)+qe,St=Ae||Pe?null:Yp(On,E.id,ye);if(St){b.appendChild(St.cloneNode(!0)),Fr(E)&&((Qe=E.toolCall)!=null&&Qe.id)&&((st=E.agentMetadata)==null?void 0:st.awaitingLocalTool)===!0&&!((Cn=E.agentMetadata)!=null&&Cn.askUserQuestionAnswered)&&(W.add(E.toolCall.id),ds(E,r,de.composerOverlay));return}let nt=null,Yt=s.find(mt=>!!(E.variant==="reasoning"&&mt.renderReasoning||E.variant==="tool"&&mt.renderToolCall||E.variant==="approval"&&mt.renderApproval||!E.variant&&mt.renderMessage)),pn=(gn=r.layout)==null?void 0:gn.messages;if(Fr(E)&&((wo=E.agentMetadata)==null?void 0:wo.askUserQuestionAnswered)===!0){rr.delete(E.id);let mt=c.querySelector(`#wrapper-${E.id}`);mt==null||mt.removeAttribute("data-preserve-runtime");return}if(Fr(E)&&((Ao=(Co=r.features)==null?void 0:Co.askUserQuestion)==null?void 0:Ao.enabled)!==!1){let mt=s.find(Mn=>typeof Mn.renderAskUserQuestion=="function");if(mt&&Tt.current){let Mn=rr.get(E.id),Rr=Mn!==ye,An=null;if(Rr){let{payload:Ut,complete:Ht}=Or(E),qt=E.id,Pn=()=>{var _n;return(_n=Tt.current)==null?void 0:_n.getMessages().find(tn=>tn.id===qt)};An=mt.renderAskUserQuestion({message:E,payload:Ut,complete:Ht,resolve:_n=>{var br;let tn=Pn();tn&&((br=Tt.current)==null||br.resolveAskUserQuestion(tn,_n))},dismiss:()=>{var tn,br,Hr;let _n=Pn();(tn=_n==null?void 0:_n.agentMetadata)!=null&&tn.awaitingLocalTool&&((br=Tt.current)==null||br.markAskUserQuestionResolved(_n),(Hr=Tt.current)==null||Hr.resolveAskUserQuestion(_n,"(dismissed)"))},config:r})}let Ln=Mn!=null;if(Rr&&An===null&&!Ln){((Ko=E.agentMetadata)==null?void 0:Ko.awaitingLocalTool)===!0&&!((Go=E.agentMetadata)!=null&&Go.askUserQuestionAnswered)&&(W.add(E.toolCall.id),ds(E,r,de.composerOverlay));return}let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id=`wrapper-${E.id}`,Rt.setAttribute("data-wrapper-id",E.id),Rt.setAttribute("data-ask-plugin-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),b.appendChild(Rt),ce.push({messageId:E.id,fingerprint:ye,bubble:An});return}else{((jt=E.agentMetadata)==null?void 0:jt.awaitingLocalTool)===!0&&!((So=E.agentMetadata)!=null&&So.askUserQuestionAnswered)&&(W.add(E.toolCall.id),ds(E,r,de.composerOverlay));return}}else if(Yt)if(E.variant==="reasoning"&&E.reasoning&&Yt.renderReasoning){if(!Re)return;nt=Yt.renderReasoning({message:E,defaultRenderer:()=>Qi(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Yt.renderToolCall){if(!Ue)return;nt=Yt.renderToolCall({message:E,defaultRenderer:()=>Xi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Yt.renderApproval){if(r.approval===!1)return;nt=Yt.renderApproval({message:E,defaultRenderer:()=>sl(E,r),config:r})}else Yt.renderMessage&&(nt=Yt.renderMessage({message:E,defaultRenderer:()=>{let mt=ss(E,y,pn,r.messageActions,He,{loadingIndicatorRenderer:D,widgetConfig:r});return E.role!=="user"&&ll(mt,E,r,U),mt},config:r}));if(!nt&&Pe){let mt=bi(E);if(mt){let Mn=hr.get(E.id),Rr=Mn!==ye,An=r.wrapComponentDirectiveInBubble!==!1,Ln=null;if(Rr){let Rt=hi(mt,{config:r,message:E,transform:y});if(Rt)if(An){let Ut=document.createElement("div");if(Ut.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(" "),Ut.id=`bubble-${E.id}`,Ut.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let Ht=document.createElement("div");Ht.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ht.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),Ut.appendChild(Ht)}Ut.appendChild(Rt),Ln=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${E.id}`,Ut.setAttribute("data-message-id",E.id),Ut.setAttribute("data-persona-component-directive","true"),E.content&&E.content.trim()){let Ht=document.createElement("div");Ht.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ht.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),Ut.appendChild(Ht)}Ut.appendChild(Rt),Ln=Ut}}if(Ln||Mn!=null){let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id=`wrapper-${E.id}`,Rt.setAttribute("data-wrapper-id",E.id),Rt.setAttribute("data-component-directive-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),An||Rt.classList.add("persona-w-full"),b.appendChild(Rt),Z.push({messageId:E.id,fingerprint:ye,bubble:Ln});return}}}if(!nt)if(E.variant==="reasoning"&&E.reasoning){if(!Re)return;nt=Qi(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Ue)return;nt=Xi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;nt=sl(E,r)}else{let mt=(no=r.layout)==null?void 0:no.messages;mt!=null&&mt.renderUserMessage&&E.role==="user"?nt=mt.renderUserMessage({message:E,config:r,streaming:!!E.streaming}):mt!=null&&mt.renderAssistantMessage&&E.role==="assistant"?nt=mt.renderAssistantMessage({message:E,config:r,streaming:!!E.streaming}):nt=ss(E,y,mt,r.messageActions,He,{loadingIndicatorRenderer:D,widgetConfig:r}),E.role!=="user"&&nt&&ll(nt,E,r,U)}let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${E.id}`,kt.setAttribute("data-wrapper-id",E.id),E.role==="user"&&kt.classList.add("persona-justify-end"),(nt==null?void 0:nt.getAttribute("data-persona-component-directive"))==="true"&&kt.classList.add("persona-w-full"),kt.appendChild(nt),Zp(On,E.id,ye,kt),b.appendChild(kt)}),de.composerOverlay&&de.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ae=>{let Pe=Ae.getAttribute("data-persona-ask-sheet-for");Pe&&!W.has(Pe)&&po(de.composerOverlay,Pe)}),(rt=(Ve=r.features)==null?void 0:Ve.toolCallDisplay)!=null&&rt.grouped){let E=[],Ae=[];m.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ue){Ae.push(Pe);return}Ae.length>1&&E.push(Ae),Ae=[]}),Ae.length>1&&E.push(Ae),E.forEach((Pe,qe)=>{var un,Qe;let ye=Pe.map(st=>Array.from(b.children).find(Cn=>Cn instanceof HTMLElement&&Cn.getAttribute("data-wrapper-id")===st.id)).filter(st=>!!st);if(ye.length<2)return;let St=document.createElement("div");St.className="persona-flex",St.id=`wrapper-tool-group-${qe}-${Pe[0].id}`,St.setAttribute("data-wrapper-id",`tool-group-${qe}-${Pe[0].id}`);let nt=document.createElement("div");nt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",nt.setAttribute("data-persona-tool-group","true");let Yt=document.createElement("div");Yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let pn=`Called ${Pe.length} tools`,kt=(Qe=(un=r.toolCall)==null?void 0:un.renderGroupedSummary)==null?void 0:Qe.call(un,{messages:Pe,toolCalls:Pe.map(st=>st.toolCall).filter(st=>!!st),defaultSummary:pn,config:r});F(Yt,kt)||(Yt.textContent=pn);let wn=document.createElement("div");wn.className="persona-tool-group-stack persona-flex persona-flex-col",nt.append(Yt,wn),St.appendChild(nt),ye[0].before(St),ye.forEach((st,Cn)=>{let gn=document.createElement("div");gn.className="persona-tool-group-item persona-relative",gn.setAttribute("data-persona-tool-group-item","true"),Cn<ye.length-1&&gn.setAttribute("data-persona-tool-group-connector","true"),gn.appendChild(st),wn.appendChild(gn)})})}eu(On,V);let xe=m.some(E=>E.role==="assistant"&&E.streaming),We=m[m.length-1],Ze=(We==null?void 0:We.role)==="assistant"&&!We.streaming&&We.variant!=="approval";if(pe&&m.some(E=>E.role==="user")&&!xe&&!Ze){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:No},Ae=s.find(qe=>qe.renderLoadingIndicator),Pe=null;if(Ae!=null&&Ae.renderLoadingIndicator&&(Pe=Ae.renderLoadingIndicator(E)),Pe===null&&((ot=r.loadingIndicator)!=null&&ot.render)&&(Pe=r.loadingIndicator.render(E)),Pe===null&&(Pe=No()),Pe){let qe=document.createElement("div"),ye=((Te=r.loadingIndicator)==null?void 0:Te.showBubble)!==!1;qe.className=ye?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),qe.setAttribute("data-typing-indicator","true"),qe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",qe.appendChild(Pe);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-typing-indicator",St.setAttribute("data-wrapper-id","typing-indicator"),St.appendChild(qe),b.appendChild(St)}}if(!pe&&m.length>0){let E=m[m.length-1],Ae={config:r,lastMessage:E,messageCount:m.length},Pe=s.find(ye=>ye.renderIdleIndicator),qe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(qe=Pe.renderIdleIndicator(Ae)),qe===null&&((Se=r.loadingIndicator)!=null&&Se.renderIdle)&&(qe=r.loadingIndicator.renderIdle(Ae)),qe){let ye=document.createElement("div"),St=((_e=r.loadingIndicator)==null?void 0:_e.showBubble)!==!1;ye.className=St?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ye.setAttribute("data-idle-indicator","true"),ye.appendChild(qe);let nt=document.createElement("div");nt.className="persona-flex",nt.id="wrapper-idle-indicator",nt.setAttribute("data-wrapper-id","idle-indicator"),nt.appendChild(ye),b.appendChild(nt)}}if(za(c,b),ce.length>0)for(let{messageId:E,fingerprint:Ae,bubble:Pe}of ce){let qe=c.querySelector(`#wrapper-${E}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",Ae),rr.set(E,Ae))}if(rr.size>0)for(let E of rr.keys())V.has(E)||rr.delete(E);if(Z.length>0)for(let{messageId:E,fingerprint:Ae,bubble:Pe}of Z){let qe=c.querySelector(`#wrapper-${E}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",Ae),hr.set(E,Ae))}if(hr.size>0)for(let E of hr.keys())V.has(E)||hr.delete(E)},Xr=null,da=()=>{var y;if(Xr)return;let c=b=>{let k=b.composedPath();k.includes(Q)||we&&k.includes(we)||Wt(!1,"user")};Xr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},xs=()=>{var m;if(!Xr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Xr,!0),Xr=null};pt.push(()=>xs());let Yr=null,pa=()=>{var y;if(Yr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Wt(!1,"user"))};Yr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},vs=()=>{var m;if(!Yr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Yr,!0),Yr=null};pt.push(()=>vs());let Zr=!1,ws=new Set,ua=()=>{var m,y,b,k;let c=(b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((k=r.features)==null?void 0:k.streamAnimation)},Pr=()=>{var rt,ot,Te,Se;if(!q())return;let c=de.peekBanner,m=de.peekTextNode;if(!c||!m)return;if(B){c.classList.remove("persona-pill-peek--visible");return}let y=(rt=U==null?void 0:U.getMessages())!=null?rt:[],b;for(let _e=y.length-1;_e>=0;_e--){let E=y[_e];if(E.role==="assistant"&&E.content){b=E;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let k=b.content,D=!!b.streaming,F=ua(),V=Ga(F),W=V.type!=="none"?js(V.type,F==null?void 0:F.plugins):null,be=((ot=W==null?void 0:W.isAnimating)==null?void 0:ot.call(W,b))===!0,ce=W!==null&&(D||be);ce&&W&&!ws.has(W.name)&&(Ui(W,e),ws.add(W.name));let Z=ce&&(W!=null&&W.containerClass)?W.containerClass:null,me=(Te=m.dataset.personaPeekStreamClass)!=null?Te:null;me&&me!==Z&&(m.classList.remove(me),delete m.dataset.personaPeekStreamClass),Z&&me!==Z&&(m.classList.add(Z),m.dataset.personaPeekStreamClass=Z),ce?(m.style.setProperty("--persona-stream-step",`${V.speed}ms`),m.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let xe=ce?Qa(k,V.buffer,W,b,D):k;if(ce&&V.placeholder==="skeleton"&&D&&(!xe||!xe.trim())){let _e=document.createElement("div"),E=zs();E.classList.add("persona-pill-peek__skeleton"),_e.appendChild(E),za(m,_e)}else{let _e=Math.max(0,xe.length-100),E=xe.length>100?xe.slice(-100):xe,Ae=Lo(E);if(!ce||!W){let Pe=xe.length>100?`\u2026${E}`:E;m.textContent!==Pe&&(m.textContent=Pe)}else{let Pe=Ae;(W.wrap==="char"||W.wrap==="word")&&(Pe=qs(Ae,W.wrap,`peek-${b.id}`,{skipTags:W.skipTags,startIndex:_e}));let qe=document.createElement("div");if(qe.innerHTML=Pe,W.useCaret&&E.length>0){let ye=Xa(),St=qe.querySelectorAll(".persona-stream-char, .persona-stream-word"),nt=St[St.length-1];nt!=null&&nt.parentNode?nt.parentNode.insertBefore(ye,nt.nextSibling):qe.appendChild(ye)}za(m,qe),(Se=W.onAfterRender)==null||Se.call(W,{container:m,bubble:c,messageId:b.id,message:b,speed:V.speed,duration:V.duration})}}let Ve=pe||Zr;c.classList.toggle("persona-pill-peek--visible",Ve)};if(q()){let c=de.peekBanner;if(c){let b=k=>{k.preventDefault(),k.stopPropagation(),Wt(!0,"user")};c.addEventListener("pointerdown",b),pt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Zr||(Zr=!0,Pr())},y=()=>{Zr&&(Zr=!1,Pr())};J.addEventListener("pointerenter",m),J.addEventListener("pointerleave",y),pt.push(()=>{J.removeEventListener("pointerenter",m),J.removeEventListener("pointerleave",y)}),we&&(we.addEventListener("pointerenter",m),we.addEventListener("pointerleave",y),pt.push(()=>{we.removeEventListener("pointerenter",m),we.removeEventListener("pointerleave",y)}))}let ma=c=>{var me,xe,We,Ze,Ve,rt,ot,Te;let m=(xe=(me=r.launcher)==null?void 0:me.composerBar)!=null?xe:{},y=(We=m.expandedSize)!=null?We:"anchored",b=(Ze=m.bottomOffset)!=null?Ze:"16px",k=m.collapsedMaxWidth,D=(Ve=m.expandedMaxWidth)!=null?Ve:"880px",F=(rt=m.expandedTopOffset)!=null?rt:"5vh",V=(ot=m.modalMaxWidth)!=null?ot:"880px",W=(Te=m.modalMaxHeight)!=null?Te:"min(90vh, 800px)",be="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",Z=Q.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",we){let Se=we.style;Se.bottom=b,Se.width=k!=null?k:""}if(c&&y!=="fullscreen"){if(y==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=V,Z.maxWidth=be,Z.maxHeight=W,Z.height=W;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${ce})`,Z.top=F,Z.width=D,Z.maxWidth=be}},eo=()=>{var W,be,ce,Z,me,xe,We,Ze;if(!_())return;if(q()){let rt=(ce=((be=(W=r.launcher)==null?void 0:W.composerBar)!=null?be:{}).expandedSize)!=null?ce:"anchored",ot=B?"expanded":"collapsed";Q.dataset.state=ot,Q.dataset.expandedSize=rt,we&&(we.dataset.state=ot,we.dataset.expandedSize=rt),Q.style.removeProperty("display"),Q.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ma(B),ne.style.display=B?"flex":"none",tr(),B?(da(),pa()):(xs(),vs()),Pr();return}let c=nn(r),m=(Z=e.ownerDocument.defaultView)!=null?Z:window,y=(xe=(me=r.launcher)==null?void 0:me.mobileBreakpoint)!=null?xe:640,b=(Ze=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Ze:!0,k=m.innerWidth<=y,D=b&&k&&A,F=Xn(r).reveal;B?(Q.style.removeProperty("display"),Q.style.display=c?"flex":"",Q.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0"),J.classList.add("persona-scale-100","persona-opacity-100"),S?S.element.style.display="none":z&&(z.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!D?(Q.style.removeProperty("display"),Q.style.display="flex",Q.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.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"),J.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"),J.classList.remove("persona-scale-100","persona-opacity-100"),J.classList.add("persona-scale-95","persona-opacity-0")),S?S.element.style.display=c?"none":"":z&&(z.style.display=c?"none":""))},Wt=(c,m="user")=>{var D,F;if(!_()||B===c)return;let y=B;B=c,eo();let b=(()=>{var We,Ze,Ve,rt,ot,Te,Se,_e,E,Ae;let V=(Ze=(We=r.launcher)==null?void 0:We.sidebarMode)!=null?Ze:!1,W=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,be=(ot=(rt=r.launcher)==null?void 0:rt.mobileFullscreen)!=null?ot:!0,ce=(Se=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?Se:640,Z=W.innerWidth<=ce,me=nn(r)&&be&&Z,xe=q()&&((Ae=(E=(_e=r.launcher)==null?void 0:_e.composerBar)==null?void 0:E.expandedSize)!=null?Ae:"fullscreen")==="fullscreen";return V||be&&Z&&A||me||xe})();if(B&&b){if(!Kt){let V=e.getRootNode(),W=V instanceof ShadowRoot?V.host:e.closest(".persona-host");W&&(Kt=ji(W,(F=(D=r.launcher)==null?void 0:D.zIndex)!=null?F:yn))}Gt||(Gt=qi(e.ownerDocument))}else B||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);B&&(Me(),Qr(!0));let k={open:B,source:m,timestamp:Date.now()};B&&!y?o.emit("widget:opened",k):!B&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:B,launcherEnabled:A,voiceActive:ct.active,streaming:U.isStreaming()})},qo=c=>{Vt(c?"stop":"send"),H&&(H.disabled=c),nr.buttons.forEach(m=>{m.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},zo=()=>{ct.active||le&&le.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>zo(),200)});let Cs=()=>{var y,b,k,D,F,V,W,be,ce,Z,me;wr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",pr.textContent=(D=(k=r.copy)==null?void 0:k.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",le.placeholder=(V=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?V:"How can I help...";let c=fe.querySelector("[data-persona-intro-card]");if(c){let xe=((W=r.copy)==null?void 0:W.showWelcomeCard)!==!1;c.style.display=xe?"":"none",xe?(fe.classList.remove("persona-gap-3"),fe.classList.add("persona-gap-6")):(fe.classList.remove("persona-gap-6"),fe.classList.add("persona-gap-3"))}!((ce=(be=r.sendButton)==null?void 0:be.useIcon)!=null&&ce)&&!(U!=null&&U.isStreaming())&&(Fe.textContent=(me=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?me:"Send"),le.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',le.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{g(m=>({...m,sessionId:c}))}});let yr=null,ga=()=>{yr==null&&(yr=setInterval(()=>{let c=Xe.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(yr),yr=null;return}let m=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Ea(m-b))})},100))};if(U=new Zo(r,{onMessagesChanged(c){bo(Xe,c,Ee),ga(),U&&(c.some(k=>k.role==="user")?nr.render([],U,le,c):nr.render(r.suggestionChips,U,le,c,r.suggestionChipsConfig)),Qr(!pe),ca(c);let m=[...c].reverse().find(b=>b.role==="user"),y=ct.lastUserMessageId;m&&m.id!==y&&(ct.lastUserMessageId=m.id,o.emit("user:message",m)),ct.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),jo(c),Pr()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Be(zt,(k=>{var D,F,V,W;return k==="idle"?(D=m.idleText)!=null?D:hn.idle:k==="connecting"?(F=m.connectingText)!=null?F:hn.connecting:k==="connected"?(V=m.connectedText)!=null?V:hn.connected:k==="error"?(W=m.errorText)!=null?W:hn.error:hn[k]})(c),m,c)},onStreamingChanged(c){pe=c,qo(c),U&&bo(Xe,U.getMessages(),Ee),c||Qr(!0),Pr()},onVoiceStatusChanged(c){var m,y;if(((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":lr(),ha();break;case"speaking":lr(),ya();break;default:c==="idle"&&U.isBargeInActive()?(lr(),to(),H==null||H.setAttribute("aria-label","End voice session")):(ct.active=!1,lr(),Gn("system"),kn());break}},onArtifactsState(c){Rn=c,Dn(),jo()}}),Tt.current=U,((hc=(fc=r.voiceRecognition)==null?void 0:fc.provider)==null?void 0:hc.type)==="runtype")try{U.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&U.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(X||r.onSSEEvent)&&U.setSSEEventCallback((c,m)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,m),X==null||X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,y,b;c&&(c.metadata&&(d=pl(c.metadata),M.syncFromMetadata()),(m=c.messages)!=null&&m.length&&U.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&U.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let As=()=>{var m,y,b;!q()||B||!((b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Wt(!0,"auto")},Ss=c=>{var k;if(c.preventDefault(),U.isStreaming()){U.cancel();return}let m=le.value.trim(),y=(k=vt==null?void 0:vt.hasAttachments())!=null?k:!1;if(!m&&!y)return;As();let b;y&&(b=[],b.push(...vt.getContentParts()),m&&b.push(Hs(m))),le.value="",le.style.height="auto",U.sendMessage(m,{contentParts:b}),y&&vt.clearAttachments()},Es=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Fe.click())},Ts=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!vt)return;let m=Lf(c.clipboardData);m.length!==0&&(c.preventDefault(),await vt.handleFiles(m))},vn=null,$n=!1,Ir=null,tt=null,ks=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,xo=(c="user")=>{var D,F,V,W,be,ce,Z;if($n||U.isStreaming())return;let m=ks();if(!m)return;vn=new m;let b=(F=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?F:2e3;vn.continuous=!0,vn.interimResults=!0,vn.lang="en-US";let k=le.value;vn.onresult=me=>{let xe="",We="";for(let Ve=0;Ve<me.results.length;Ve++){let rt=me.results[Ve],ot=rt[0].transcript;rt.isFinal?xe+=ot+" ":We=ot}let Ze=k+xe+We;le.value=Ze,Ir&&clearTimeout(Ir),(xe||We)&&(Ir=window.setTimeout(()=>{let Ve=le.value.trim();Ve&&vn&&$n&&(ir(),le.value="",le.style.height="auto",U.sendMessage(Ve,{viaVoice:!0}))},b))},vn.onerror=me=>{me.error!=="no-speech"&&ir()},vn.onend=()=>{if($n){let me=le.value.trim();me&&me!==k.trim()&&(le.value="",le.style.height="auto",U.sendMessage(me,{viaVoice:!0})),ir()}};try{if(vn.start(),$n=!0,ct.active=!0,c!=="system"&&(ct.manuallyDeactivated=!1),Gn(c),kn(),H){let me=(V=r.voiceRecognition)!=null?V:{};tt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(W=me.iconName)!=null?W:"mic",iconSize:parseFloat((Z=(ce=me.iconSize)!=null?ce:(be=r.sendButton)==null?void 0:be.size)!=null?Z:"40")||24};let xe=me.recordingBackgroundColor,We=me.recordingIconColor,Ze=me.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=xe!=null?xe:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=We!=null?We:"var(--persona-voice-recording-indicator, #ffffff)",We){let Ve=H.querySelector("svg");Ve&&Ve.setAttribute("stroke",We)}Ze&&(H.style.borderColor=Ze),H.setAttribute("aria-label","Stop voice recognition")}}catch{ir("system")}},ir=(c="user")=>{if($n){if($n=!1,Ir&&(clearTimeout(Ir),Ir=null),vn){try{vn.stop()}catch{}vn=null}if(ct.active=!1,Gn(c),kn(),H){if(H.classList.remove("persona-voice-recording"),tt){H.style.backgroundColor=tt.backgroundColor,H.style.color=tt.color,H.style.borderColor=tt.borderColor;let m=H.querySelector("svg");m&&m.setAttribute("stroke",tt.color||"currentColor"),tt=null}H.setAttribute("aria-label","Start voice recognition")}}},fa=(c,m)=>{var rt,ot,Te,Se,_e,E,Ae,Pe;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((rt=c==null?void 0:c.provider)==null?void 0:rt.type)==="runtype";if(!(y||b))return null;let D=h("div","persona-send-button-wrapper"),F=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let V=(ot=c==null?void 0:c.iconName)!=null?ot:"mic",W=(Te=m==null?void 0:m.size)!=null?Te:"40px",be=(Se=c==null?void 0:c.iconSize)!=null?Se:W,ce=parseFloat(be)||24,Z=(_e=c==null?void 0:c.backgroundColor)!=null?_e:m==null?void 0:m.backgroundColor,me=(E=c==null?void 0:c.iconColor)!=null?E:m==null?void 0:m.textColor;F.style.width=be,F.style.height=be,F.style.minWidth=be,F.style.minHeight=be,F.style.fontSize="18px",F.style.lineHeight="1",me?F.style.color=me:F.style.color="var(--persona-text, #111827)";let We=ge(V,ce,me||"currentColor",1.5);We?F.appendChild(We):F.textContent="\u{1F3A4}",Z?F.style.backgroundColor=Z:F.style.backgroundColor="",c!=null&&c.borderWidth&&(F.style.borderWidth=c.borderWidth,F.style.borderStyle="solid"),c!=null&&c.borderColor&&(F.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(F.style.paddingLeft=c.paddingX,F.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(F.style.paddingTop=c.paddingY,F.style.paddingBottom=c.paddingY),D.appendChild(F);let Ze=(Ae=c==null?void 0:c.tooltipText)!=null?Ae:"Start voice recognition";if(((Pe=c==null?void 0:c.showTooltip)!=null?Pe:!1)&&Ze){let qe=h("div","persona-send-button-tooltip");qe.textContent=Ze,D.appendChild(qe)}return{micButton:F,micButtonWrapper:D}},Vo=()=>{var m,y,b,k,D;if(!H||tt)return;let c=(m=r.voiceRecognition)!=null?m:{};tt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((D=(k=c.iconSize)!=null?k:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},Jo=(c,m)=>{var D,F,V,W,be;if(!H)return;let y=H.querySelector("svg");y&&y.remove();let b=(be=tt==null?void 0:tt.iconSize)!=null?be:parseFloat((W=(V=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?V:(F=r.sendButton)==null?void 0:F.size)!=null?W:"40")||24,k=ge(c,b,m,1.5);k&&H.appendChild(k)},vo=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},to=()=>{var k;if(!H)return;Vo();let c=(k=r.voiceRecognition)!=null?k:{},m=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(vo(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let D=H.querySelector("svg");D&&D.setAttribute("stroke",y)}b&&(H.style.borderColor=b),H.setAttribute("aria-label","Stop voice recognition")},ha=()=>{var V,W,be,ce,Z,me,xe,We;if(!H)return;Vo();let c=(V=r.voiceRecognition)!=null?V:{},m=U.getVoiceInterruptionMode(),y=(W=c.processingIconName)!=null?W:"loader",b=(ce=(be=c.processingIconColor)!=null?be:tt==null?void 0:tt.color)!=null?ce:"",k=(me=(Z=c.processingBackgroundColor)!=null?Z:tt==null?void 0:tt.backgroundColor)!=null?me:"",D=(We=(xe=c.processingBorderColor)!=null?xe:tt==null?void 0:tt.borderColor)!=null?We:"";vo(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=k,H.style.borderColor=D;let F=b||"currentColor";H.style.color=F,Jo(y,F),H.setAttribute("aria-label","Processing voice input"),m==="none"&&(H.style.cursor="default")},ya=()=>{var be,ce,Z,me,xe,We,Ze,Ve,rt,ot,Te,Se;if(!H)return;Vo();let c=(be=r.voiceRecognition)!=null?be:{},m=U.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(ce=c.speakingIconName)!=null?ce:y,k=(We=c.speakingIconColor)!=null?We:m==="barge-in"?(me=(Z=c.recordingIconColor)!=null?Z:tt==null?void 0:tt.color)!=null?me:"":(xe=tt==null?void 0:tt.color)!=null?xe:"",D=(rt=c.speakingBackgroundColor)!=null?rt:m==="barge-in"?(Ze=c.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(Ve=tt==null?void 0:tt.backgroundColor)!=null?Ve:"",F=(Se=c.speakingBorderColor)!=null?Se:m==="barge-in"?(ot=c.recordingBorderColor)!=null?ot:"":(Te=tt==null?void 0:tt.borderColor)!=null?Te:"";vo(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=D,H.style.borderColor=F;let V=k||"currentColor";H.style.color=V,Jo(b,V);let W=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",W),m==="none"&&(H.style.cursor="default"),m==="barge-in"&&H.classList.add("persona-voice-recording")},lr=()=>{var c,m,y;H&&(vo(),tt&&(H.style.backgroundColor=(c=tt.backgroundColor)!=null?c:"",H.style.color=(m=tt.color)!=null?m:"",H.style.borderColor=(y=tt.borderColor)!=null?y:"",Jo(tt.iconName,tt.color||"currentColor"),tt=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},Wr=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let y=U.getVoiceStatus(),b=U.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){U.stopVoicePlayback();return}if(U.isBargeInActive()){U.stopVoicePlayback(),U.deactivateBargeIn().then(()=>{ct.active=!1,ct.manuallyDeactivated=!0,kn(),Gn("user"),lr()});return}U.toggleVoice().then(()=>{ct.active=U.isVoiceActive(),ct.manuallyDeactivated=!U.isVoiceActive(),kn(),Gn("user"),U.isVoiceActive()?to():lr()});return}if($n){let y=le.value.trim();ct.manuallyDeactivated=!0,kn(),ir("user"),y&&(le.value="",le.style.height="auto",U.sendMessage(y))}else ct.manuallyDeactivated=!1,kn(),xo("user")};ur=Wr,H&&(H.addEventListener("click",Wr),pt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(U.isVoiceActive()&&U.toggleVoice(),lr()):ir("system"),H&&H.removeEventListener("click",Wr)}));let Je=o.on("assistant:complete",()=>{hs&&(ct.active||ct.manuallyDeactivated||hs==="assistant"&&!ct.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!ct.active&&!ct.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?U.toggleVoice().then(()=>{ct.active=U.isVoiceActive(),Gn("auto"),U.isVoiceActive()&&to()}):xo("auto"))},600))});pt.push(Je);let C=o.on("action:resubmit",()=>{setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)});pt.push(C);let j=()=>{Wt(!B,"user")},S=null,z=null;if(A&&!q()){let c=s.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Js(r,j).element,onToggle:j});m&&(z=m)}z||(S=Js(r,j))}S?e.appendChild(S.element):z&&e.appendChild(z),eo(),nr.render(r.suggestionChips,U,le,void 0,r.suggestionChipsConfig),Cs(),qo(U.isStreaming()),Qr(!0),sa(),N&&(!A||q()?setTimeout(()=>zo(),0):B&&setTimeout(()=>zo(),200));let Me=()=>{var W,be,ce,Z,me,xe,We,Ze,Ve,rt,ot,Te,Se,_e,E,Ae,Pe,qe,ye,St,nt,Yt;if(q()){qn(),eo();return}let c=nn(r),m=(be=(W=r.launcher)==null?void 0:W.sidebarMode)!=null?be:!1,y=c||m||((Z=(ce=r.launcher)==null?void 0:ce.fullHeight)!=null?Z:!1),b=(me=e.ownerDocument.defaultView)!=null?me:window,k=(We=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?We:!0,D=(Ve=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?Ve:640,F=b.innerWidth<=D,V=k&&F&&A;try{if(V){tr(),ro(e,r);return}if($&&($=!1,tr(),ro(e,r)),!A&&!c){J.style.height="",J.style.width="";return}if(!m&&!c){let pn=(ot=(rt=r==null?void 0:r.launcher)==null?void 0:rt.width)!=null?ot:r==null?void 0:r.launcherWidth,kt=pn!=null?pn:jn;J.style.width=kt,J.style.maxWidth=kt}if(fr(),!y){let pn=b.innerHeight,kt=64,wn=(Se=(Te=r.launcher)==null?void 0:Te.heightOffset)!=null?Se:0,un=Math.max(200,pn-kt),Qe=Math.min(640,un),st=Math.max(200,Qe-wn);J.style.height=`${st}px`}}finally{if(qn(),eo(),B&&A){let kt=((_e=e.ownerDocument.defaultView)!=null?_e:window).innerWidth<=((Ae=(E=r.launcher)==null?void 0:E.mobileBreakpoint)!=null?Ae:640),wn=(qe=(Pe=r.launcher)==null?void 0:Pe.sidebarMode)!=null?qe:!1,un=(St=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?St:!0,Qe=nn(r)&&un&&kt,st=wn||un&&kt&&A||Qe;if(st&&!Gt){let Cn=e.getRootNode(),gn=Cn instanceof ShadowRoot?Cn.host:e.closest(".persona-host");gn&&!Kt&&(Kt=ji(gn,(Yt=(nt=r.launcher)==null?void 0:nt.zIndex)!=null?Yt:yn)),Gt=qi(e.ownerDocument)}else st||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Me();let ee=(yc=e.ownerDocument.defaultView)!=null?yc:window;if(ee.addEventListener("resize",Me),pt.push(()=>ee.removeEventListener("resize",Me)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{qn()});c.observe($e),pt.push(()=>c.disconnect())}sr=fe.scrollTop;let Ye=fe.scrollHeight,Ge=()=>{let c=fe.scrollTop,m=fe.scrollHeight,y=m<Ye;Ye=m;let{action:b,nextLastScrollTop:k}=Ja({following:or.isFollowing(),currentScrollTop:c,lastScrollTop:sr,nearBottom:$s(fe,fs),userScrollThreshold:ra,isAutoScrolling:kr||ho||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(sr=k,b==="resume"){Gr();return}b==="pause"&&bs()};fe.addEventListener("scroll",Ge,{passive:!0}),pt.push(()=>fe.removeEventListener("scroll",Ge));let Lt=c=>{let m=Ka({following:or.isFollowing(),deltaY:c.deltaY,nearBottom:$s(fe,fs),resumeWhenNearBottom:!0});m==="pause"?bs():m==="resume"&&Gr()};fe.addEventListener("wheel",Lt,{passive:!0}),pt.push(()=>fe.removeEventListener("wheel",Lt)),lt.addEventListener("click",()=>{fe.scrollTop=fe.scrollHeight,sr=fe.scrollTop,Gr(),Qr(!0)}),pt.push(()=>lt.remove()),pt.push(()=>{ys()});let ft=()=>{I&&(Fn&&(I.removeEventListener("click",Fn),Fn=null),_()?(I.style.display="",Fn=()=>{Wt(!1,"user")},I.addEventListener("click",Fn)):I.style.display="none")};ft(),(()=>{let{clearChatButton:c}=de;c&&c.addEventListener("click",()=>{U.clearMessages(),On.clear(),Gr(),po(de.composerOverlay);try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},M.syncFromMetadata(),X==null||X.clear(),oe==null||oe.update()})})(),It&&It.addEventListener("submit",Ss),le==null||le.addEventListener("keydown",Es),le==null||le.addEventListener("paste",Ts);let Dt="persona-attachment-drop-active",Qt=0,bt=()=>{Qt=0,ne.classList.remove(Dt)},ht=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&vt!==null},rn=c=>{!wi(c.dataTransfer)||!ht()||(Qt++,Qt===1&&ne.classList.add(Dt))},mn=c=>{!wi(c.dataTransfer)||!ht()||(Qt--,Qt<=0&&bt())},dn=c=>{!wi(c.dataTransfer)||!ht()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Xt=c=>{var y;if(!wi(c.dataTransfer)||!ht())return;c.preventDefault(),c.stopPropagation(),bt();let m=Array.from((y=c.dataTransfer.files)!=null?y:[]);m.length!==0&&vt.handleFiles(m)},an=!0;ne.addEventListener("dragenter",rn,an),ne.addEventListener("dragleave",mn,an),e.addEventListener("dragover",dn,an),e.addEventListener("drop",Xt,an);let ba=e.ownerDocument,Ll=c=>{ht()&&c.preventDefault()},Pl=c=>{ht()&&c.preventDefault()};ba.addEventListener("dragover",Ll),ba.addEventListener("drop",Pl),pt.push(()=>{It&&It.removeEventListener("submit",Ss),le==null||le.removeEventListener("keydown",Es),le==null||le.removeEventListener("paste",Ts)}),pt.push(()=>{ne.removeEventListener("dragenter",rn,an),ne.removeEventListener("dragleave",mn,an),e.removeEventListener("dragover",dn,an),e.removeEventListener("drop",Xt,an),ba.removeEventListener("dragover",Ll),ba.removeEventListener("drop",Pl),bt()}),pt.push(()=>{U.cancel()}),S?pt.push(()=>{S==null||S.destroy()}):z&&pt.push(()=>{z==null||z.remove()});let en={update(c){var tn,br,Hr,xa,va,wa,Eo,Ca,Ms,Sc,Ec,Tc,kc,Mc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,Uc,jc,qc,zc,Vc,Jc,Kc,Gc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,kd,Md,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,Ud,jd,qd,zd,Vd,Jd,Kd,Gd,Qd,Xd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp;let m=r.toolCall,y=r.messageActions,b=(tn=r.layout)==null?void 0:tn.messages,k=r.colorScheme,D=r.loadingIndicator,F=r.iterationDisplay,V=(br=r.features)==null?void 0:br.showReasoning,W=(Hr=r.features)==null?void 0:Hr.showToolCalls,be=(xa=r.features)==null?void 0:xa.toolCallDisplay,ce=(va=r.features)==null?void 0:va.reasoningDisplay;r={...r,...c},tr(),ro(e,r),ui(e,r),mi(e,r),Dn(),r.colorScheme!==k&&Kr();let Z=Zs.getForInstance(r.plugins);s.length=0,s.push(...Z),A=(Eo=(wa=r.launcher)==null?void 0:wa.enabled)!=null?Eo:!0,P=(Ms=(Ca=r.launcher)==null?void 0:Ca.autoExpand)!=null?Ms:!1,Re=(Ec=(Sc=r.features)==null?void 0:Sc.showReasoning)!=null?Ec:!0,Ue=(kc=(Tc=r.features)==null?void 0:Tc.showToolCalls)!=null?kc:!0,ue=(Lc=(Mc=r.features)==null?void 0:Mc.scrollToBottom)!=null?Lc:{},Ur(),Lr();let me=he;if(he=(Ic=(Pc=r.features)==null?void 0:Pc.showEventStreamToggle)!=null?Ic:!1,he&&!me){if(X||(te=new Ys(je),X=new Xs(ve,te),te.open().then(()=>X==null?void 0:X.restore()).catch(()=>{}),U.setSSEEventCallback((Y,xt)=>{var Nt;(Nt=r.onSSEEvent)==null||Nt.call(r,Y,xt),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!dt&&Oe){let Y=(Rc=(Wc=r.features)==null?void 0:Wc.eventStream)==null?void 0:Rc.classNames,xt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");dt=h("button",xt),dt.style.width="28px",dt.style.height="28px",dt.style.color=En.actionIconColor,dt.type="button",dt.setAttribute("aria-label","Event Stream"),dt.title="Event Stream";let Nt=ge("activity","18px","currentColor",1.5);Nt&&dt.appendChild(Nt);let at=de.clearChatButtonWrapper,At=de.closeButtonWrapper,on=at||At;on&&on.parentNode===Oe?Oe.insertBefore(dt,on):Oe.appendChild(dt),dt.addEventListener("click",()=>{Le?er():Ar()})}}else!he&&me&&(er(),dt&&(dt.remove(),dt=null),X==null||X.clear(),te==null||te.destroy(),X=null,te=null);if(((Hc=r.launcher)==null?void 0:Hc.enabled)===!1&&S&&(S.destroy(),S=null),((Bc=r.launcher)==null?void 0:Bc.enabled)===!1&&z&&(z.remove(),z=null),((Dc=r.launcher)==null?void 0:Dc.enabled)!==!1&&!S&&!z){let Y=s.find(xt=>xt.renderLauncher);if(Y!=null&&Y.renderLauncher){let xt=Y.renderLauncher({config:r,defaultRenderer:()=>Js(r,j).element,onToggle:j});xt&&(z=xt,e.appendChild(z))}z||(S=Js(r,j),e.appendChild(S.element))}S&&S.update(r),Ie&&((Nc=r.launcher)==null?void 0:Nc.title)!==void 0&&(Ie.textContent=r.launcher.title),ze&&((Fc=r.launcher)==null?void 0:Fc.subtitle)!==void 0&&(ze.textContent=r.launcher.subtitle);let xe=(Oc=r.layout)==null?void 0:Oc.header;if((xe==null?void 0:xe.layout)!==L&&Oe){let Y=xe?rs(r,xe,{showClose:_(),onClose:()=>Wt(!1,"user")}):Nr({config:r,showClose:_(),onClose:()=>Wt(!1,"user")});Oe.replaceWith(Y.header),Oe=Y.header,se=Y.iconHolder,Ie=Y.headerTitle,ze=Y.headerSubtitle,I=Y.closeButton,L=xe==null?void 0:xe.layout}else if(xe&&(se&&(se.style.display=xe.showIcon===!1?"none":""),Ie&&(Ie.style.display=xe.showTitle===!1?"none":""),ze&&(ze.style.display=xe.showSubtitle===!1?"none":""),I&&(I.style.display=xe.showCloseButton===!1?"none":""),de.clearChatButtonWrapper)){let Y=xe.showClearChat;if(Y!==void 0){de.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:xt}=de;xt&&!xt.classList.contains("persona-absolute")&&(Y?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let Ze=(($c=r.layout)==null?void 0:$c.showHeader)!==!1;Oe&&(Oe.style.display=Ze?"":"none");let Ve=((_c=r.layout)==null?void 0:_c.showFooter)!==!1;$e&&($e.style.display=Ve?"":"none"),qn(),Lr(),A!==T?A?Wt(P,"auto"):(B=!0,eo()):P!==R&&Wt(P,"auto"),R=P,T=A,Me(),ft();let Te=JSON.stringify(c.toolCall)!==JSON.stringify(m),Se=JSON.stringify(r.messageActions)!==JSON.stringify(y),_e=JSON.stringify((Uc=r.layout)==null?void 0:Uc.messages)!==JSON.stringify(b),E=((jc=r.loadingIndicator)==null?void 0:jc.render)!==(D==null?void 0:D.render)||((qc=r.loadingIndicator)==null?void 0:qc.renderIdle)!==(D==null?void 0:D.renderIdle)||((zc=r.loadingIndicator)==null?void 0:zc.showBubble)!==(D==null?void 0:D.showBubble),Ae=r.iterationDisplay!==F,Pe=((Jc=(Vc=r.features)==null?void 0:Vc.showReasoning)!=null?Jc:!0)!==(V!=null?V:!0)||((Gc=(Kc=r.features)==null?void 0:Kc.showToolCalls)!=null?Gc:!0)!==(W!=null?W:!0)||JSON.stringify((Qc=r.features)==null?void 0:Qc.toolCallDisplay)!==JSON.stringify(be)||JSON.stringify((Xc=r.features)==null?void 0:Xc.reasoningDisplay)!==JSON.stringify(ce);(Te||Se||_e||E||Ae||Pe)&&U&&(gs++,bo(Xe,U.getMessages(),Ee));let ye=(Yc=r.launcher)!=null?Yc:{},St=(Zc=ye.headerIconHidden)!=null?Zc:!1,nt=(td=(ed=r.layout)==null?void 0:ed.header)==null?void 0:td.showIcon,Yt=St||nt===!1,pn=ye.headerIconName,kt=(nd=ye.headerIconSize)!=null?nd:"48px";if(se){let Y=ne.querySelector(".persona-border-b-persona-divider"),xt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(Yt)se.style.display="none",Y&&xt&&!Y.contains(xt)&&Y.insertBefore(xt,Y.firstChild);else{if(se.style.display="",se.style.height=kt,se.style.width=kt,Y&&xt&&(Y.contains(se)?se.nextSibling!==xt&&(se.remove(),Y.insertBefore(se,xt)):Y.insertBefore(se,xt)),pn){let at=parseFloat(kt)||24,At=ge(pn,at*.6,"#ffffff",2);At?se.replaceChildren(At):se.textContent=(rd=ye.agentIconText)!=null?rd:"\u{1F4AC}"}else if(ye.iconUrl){let at=se.querySelector("img");if(at)at.src=ye.iconUrl,at.style.height=kt,at.style.width=kt;else{let At=document.createElement("img");At.src=ye.iconUrl,At.alt="",At.className="persona-rounded-xl persona-object-cover",At.style.height=kt,At.style.width=kt,se.replaceChildren(At)}}else{let at=se.querySelector("svg"),At=se.querySelector("img");(at||At)&&se.replaceChildren(),se.textContent=(od=ye.agentIconText)!=null?od:"\u{1F4AC}"}let Nt=se.querySelector("img");Nt&&(Nt.style.height=kt,Nt.style.width=kt)}}let wn=(ad=(sd=r.layout)==null?void 0:sd.header)==null?void 0:ad.showTitle,un=(ld=(id=r.layout)==null?void 0:id.header)==null?void 0:ld.showSubtitle;if(Ie&&(Ie.style.display=wn===!1?"none":""),ze&&(ze.style.display=un===!1?"none":""),I){((dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.showCloseButton)===!1?I.style.display="none":I.style.display="";let xt=(pd=ye.closeButtonSize)!=null?pd:"32px",Nt=(ud=ye.closeButtonPlacement)!=null?ud:"inline";I.style.height=xt,I.style.width=xt;let{closeButtonWrapper:at}=de,At=Nt==="top-right",on=at==null?void 0:at.classList.contains("persona-absolute");if(at&&At!==on)if(at.remove(),At)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(at);else{let it=(gd=(md=ye.clearChat)==null?void 0:md.placement)!=null?gd:"inline",sn=(hd=(fd=ye.clearChat)==null?void 0:fd.enabled)!=null?hd:!0;at.className=sn&&it==="inline"?"":"persona-ml-auto";let In=ne.querySelector(".persona-border-b-persona-divider");In&&In.appendChild(at)}if(I.style.color=ye.closeButtonColor||En.actionIconColor,ye.closeButtonBackgroundColor?(I.style.backgroundColor=ye.closeButtonBackgroundColor,I.classList.remove("hover:persona-bg-gray-100")):(I.style.backgroundColor="",I.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let it=ye.closeButtonBorderWidth||"0px",sn=ye.closeButtonBorderColor||"transparent";I.style.border=`${it} solid ${sn}`,I.classList.remove("persona-border-none")}else I.style.border="",I.classList.add("persona-border-none");ye.closeButtonBorderRadius?(I.style.borderRadius=ye.closeButtonBorderRadius,I.classList.remove("persona-rounded-full")):(I.style.borderRadius="",I.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(I.style.paddingLeft=ye.closeButtonPaddingX,I.style.paddingRight=ye.closeButtonPaddingX):(I.style.paddingLeft="",I.style.paddingRight=""),ye.closeButtonPaddingY?(I.style.paddingTop=ye.closeButtonPaddingY,I.style.paddingBottom=ye.closeButtonPaddingY):(I.style.paddingTop="",I.style.paddingBottom="");let fn=(yd=ye.closeButtonIconName)!=null?yd:"x",cr=(bd=ye.closeButtonIconText)!=null?bd:"\xD7";I.innerHTML="";let Sn=ge(fn,"28px","currentColor",1);Sn?I.appendChild(Sn):I.textContent=cr;let Zt=(xd=ye.closeButtonTooltipText)!=null?xd:"Close chat",Un=(vd=ye.closeButtonShowTooltip)!=null?vd:!0;if(I.setAttribute("aria-label",Zt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Un&&Zt)){let it=null,sn=()=>{if(it||!I)return;let To=I.ownerDocument,Ls=To.body;if(!Ls)return;it=xr(To,"div","persona-clear-chat-tooltip"),it.textContent=Zt;let Ps=xr(To,"div");Ps.className="persona-clear-chat-tooltip-arrow",it.appendChild(Ps);let ko=I.getBoundingClientRect();it.style.position="fixed",it.style.zIndex=String(oo),it.style.left=`${ko.left+ko.width/2}px`,it.style.top=`${ko.top-8}px`,it.style.transform="translate(-50%, -100%)",Ls.appendChild(it)},In=()=>{it&&it.parentNode&&(it.parentNode.removeChild(it),it=null)};at.addEventListener("mouseenter",sn),at.addEventListener("mouseleave",In),I.addEventListener("focus",sn),I.addEventListener("blur",In),at._cleanupTooltip=()=>{In(),at&&(at.removeEventListener("mouseenter",sn),at.removeEventListener("mouseleave",In)),I&&(I.removeEventListener("focus",sn),I.removeEventListener("blur",In))}}}let{clearChatButton:Qe,clearChatButtonWrapper:st}=de;if(Qe){let Y=(wd=ye.clearChat)!=null?wd:{},xt=(Cd=Y.enabled)!=null?Cd:!0,Nt=(Sd=(Ad=r.layout)==null?void 0:Ad.header)==null?void 0:Sd.showClearChat,at=Nt!==void 0?Nt:xt,At=(Ed=Y.placement)!=null?Ed:"inline";if(st){st.style.display=at?"":"none";let{closeButtonWrapper:on}=de;!q()&&on&&!on.classList.contains("persona-absolute")&&(at?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let fn=At==="top-right",cr=st.classList.contains("persona-absolute");if(!q()&&fn!==cr&&at){if(st.remove(),fn)st.className="persona-absolute persona-top-4 persona-z-50",st.style.right="48px",ne.style.position="relative",ne.appendChild(st);else{st.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",st.style.right="";let Zt=ne.querySelector(".persona-border-b-persona-divider"),Un=de.closeButtonWrapper;Zt&&Un&&Un.parentElement===Zt?Zt.insertBefore(st,Un):Zt&&Zt.appendChild(st)}let Sn=de.closeButtonWrapper;Sn&&!Sn.classList.contains("persona-absolute")&&(fn?Sn.classList.add("persona-ml-auto"):Sn.classList.remove("persona-ml-auto"))}}if(at){if(!q()){let it=(Td=Y.size)!=null?Td:"32px";Qe.style.height=it,Qe.style.width=it}let on=(kd=Y.iconName)!=null?kd:"refresh-cw",fn=(Md=Y.iconColor)!=null?Md:"";Qe.style.color=fn||En.actionIconColor,Qe.innerHTML="";let cr=q()?"14px":"20px",Sn=ge(on,cr,"currentColor",2);if(Sn&&Qe.appendChild(Sn),Y.backgroundColor?(Qe.style.backgroundColor=Y.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let it=Y.borderWidth||"0px",sn=Y.borderColor||"transparent";Qe.style.border=`${it} solid ${sn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");Y.borderRadius?(Qe.style.borderRadius=Y.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),Y.paddingX?(Qe.style.paddingLeft=Y.paddingX,Qe.style.paddingRight=Y.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),Y.paddingY?(Qe.style.paddingTop=Y.paddingY,Qe.style.paddingBottom=Y.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Zt=(Ld=Y.tooltipText)!=null?Ld:"Clear chat",Un=(Pd=Y.showTooltip)!=null?Pd:!0;if(Qe.setAttribute("aria-label",Zt),st&&(st._cleanupTooltip&&(st._cleanupTooltip(),delete st._cleanupTooltip),Un&&Zt)){let it=null,sn=()=>{if(it||!Qe)return;let To=Qe.ownerDocument,Ls=To.body;if(!Ls)return;it=xr(To,"div","persona-clear-chat-tooltip"),it.textContent=Zt;let Ps=xr(To,"div");Ps.className="persona-clear-chat-tooltip-arrow",it.appendChild(Ps);let ko=Qe.getBoundingClientRect();it.style.position="fixed",it.style.zIndex=String(oo),it.style.left=`${ko.left+ko.width/2}px`,it.style.top=`${ko.top-8}px`,it.style.transform="translate(-50%, -100%)",Ls.appendChild(it)},In=()=>{it&&it.parentNode&&(it.parentNode.removeChild(it),it=null)};st.addEventListener("mouseenter",sn),st.addEventListener("mouseleave",In),Qe.addEventListener("focus",sn),Qe.addEventListener("blur",In),st._cleanupTooltip=()=>{In(),st&&(st.removeEventListener("mouseenter",sn),st.removeEventListener("mouseleave",In)),Qe&&(Qe.removeEventListener("focus",sn),Qe.removeEventListener("blur",In))}}}}let Cn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ea],gn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Oo.message,Oo.messageAndClick];M=ta({parsers:Cn,handlers:gn,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ee=qu(r,M,re),U.updateConfig(r),bo(Xe,U.getMessages(),Ee),nr.render(r.suggestionChips,U,le,void 0,r.suggestionChipsConfig),Cs(),qo(U.isStreaming());let wo=((Id=r.voiceRecognition)==null?void 0:Id.enabled)===!0,Co=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ao=((Rd=(Wd=r.voiceRecognition)==null?void 0:Wd.provider)==null?void 0:Rd.type)==="runtype";if(wo&&(Co||Ao))if(!H||!ae){let Y=fa(r.voiceRecognition,r.sendButton);Y&&(H=Y.micButton,ae=Y.micButtonWrapper,_t.insertBefore(ae,ln),H.addEventListener("click",Wr),H.disabled=U.isStreaming())}else{let Y=(Hd=r.voiceRecognition)!=null?Hd:{},xt=(Bd=r.sendButton)!=null?Bd:{},Nt=(Dd=Y.iconName)!=null?Dd:"mic",at=(Nd=xt.size)!=null?Nd:"40px",At=(Fd=Y.iconSize)!=null?Fd:at,on=parseFloat(At)||24;H.style.width=At,H.style.height=At,H.style.minWidth=At,H.style.minHeight=At;let fn=($d=(Od=Y.iconColor)!=null?Od:xt.textColor)!=null?$d:"currentColor";H.innerHTML="";let cr=ge(Nt,on,fn,2);cr?H.appendChild(cr):H.textContent="\u{1F3A4}";let Sn=(_d=Y.backgroundColor)!=null?_d:xt.backgroundColor;Sn?H.style.backgroundColor=Sn:H.style.backgroundColor="",fn?H.style.color=fn:H.style.color="var(--persona-text, #111827)",Y.borderWidth?(H.style.borderWidth=Y.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),Y.borderColor?H.style.borderColor=Y.borderColor:H.style.borderColor="",Y.paddingX?(H.style.paddingLeft=Y.paddingX,H.style.paddingRight=Y.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),Y.paddingY?(H.style.paddingTop=Y.paddingY,H.style.paddingBottom=Y.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Zt=ae==null?void 0:ae.querySelector(".persona-send-button-tooltip"),Un=(Ud=Y.tooltipText)!=null?Ud:"Start voice recognition";if(((jd=Y.showTooltip)!=null?jd:!1)&&Un)if(Zt)Zt.textContent=Un,Zt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Un,ae==null||ae.insertBefore(sn,H)}else Zt&&(Zt.style.display="none");ae.style.display="",H.disabled=U.isStreaming()}else H&&ae&&(ae.style.display="none",((zd=(qd=r.voiceRecognition)==null?void 0:qd.provider)==null?void 0:zd.type)==="runtype"?U.isVoiceActive()&&U.toggleVoice():$n&&ir());if(((Vd=r.attachments)==null?void 0:Vd.enabled)===!0)if(!ut||!Ce){let Y=(Jd=r.attachments)!=null?Jd:{},Nt=(Gd=((Kd=r.sendButton)!=null?Kd:{}).size)!=null?Gd:"40px";Ft||(Ft=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ft.style.display="none",It.insertBefore(Ft,le)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((Qd=Y.allowedTypes)!=null?Qd:Dr).join(","),Ke.multiple=((Xd=Y.maxFiles)!=null?Xd:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),It.insertBefore(Ke,le)),ut=h("div","persona-send-button-wrapper"),Ce=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ce.type="button",Ce.setAttribute("aria-label",(Yd=Y.buttonTooltipText)!=null?Yd:"Attach file");let at=(Zd=Y.buttonIconName)!=null?Zd:"paperclip",At=Nt,on=parseFloat(At)||40,fn=Math.round(on*.6);Ce.style.width=At,Ce.style.height=At,Ce.style.minWidth=At,Ce.style.minHeight=At,Ce.style.fontSize="18px",Ce.style.lineHeight="1",Ce.style.backgroundColor="transparent",Ce.style.color="var(--persona-primary, #111827)",Ce.style.border="none",Ce.style.borderRadius="6px",Ce.style.transition="background-color 0.15s ease",Ce.addEventListener("mouseenter",()=>{Ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ce.addEventListener("mouseleave",()=>{Ce.style.backgroundColor="transparent"});let cr=ge(at,fn,"currentColor",1.5);cr?Ce.appendChild(cr):Ce.textContent="\u{1F4CE}",Ce.addEventListener("click",Un=>{Un.preventDefault(),Ke==null||Ke.click()}),ut.appendChild(Ce);let Sn=(ep=Y.buttonTooltipText)!=null?ep:"Attach file",Zt=h("div","persona-send-button-tooltip");Zt.textContent=Sn,ut.appendChild(Zt),wt.append(ut),!vt&&Ke&&Ft&&(vt=Bo.fromConfig(Y),vt.setPreviewsContainer(Ft),Ke.addEventListener("change",async()=>{vt&&(Ke!=null&&Ke.files)&&(await vt.handleFileSelect(Ke.files),Ke.value="")})),ne.querySelector(".persona-attachment-drop-overlay")||ne.appendChild(zu(Y.dropOverlay))}else{ut.style.display="";let Y=(tp=r.attachments)!=null?tp:{};Ke&&(Ke.accept=((np=Y.allowedTypes)!=null?np:Dr).join(","),Ke.multiple=((rp=Y.maxFiles)!=null?rp:4)>1),vt&&vt.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else ut&&(ut.style.display="none"),vt&&vt.clearAttachments(),(op=ne.querySelector(".persona-attachment-drop-overlay"))==null||op.remove();let jt=(sp=r.sendButton)!=null?sp:{},So=(ap=jt.useIcon)!=null?ap:!1,no=(ip=jt.iconText)!=null?ip:"\u2191",mt=jt.iconName,Mn=(lp=jt.tooltipText)!=null?lp:"Send message",Rr=(cp=jt.showTooltip)!=null?cp:!1,An=(dp=jt.size)!=null?dp:"40px",Ln=jt.backgroundColor,Rt=jt.textColor;if(So){if(Fe.style.width=An,Fe.style.height=An,Fe.style.minWidth=An,Fe.style.minHeight=An,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.innerHTML="",Rt?Fe.style.color=Rt:Fe.style.color="var(--persona-button-primary-fg, #ffffff)",mt){let Y=parseFloat(An)||24,xt=(Rt==null?void 0:Rt.trim())||"currentColor",Nt=ge(mt,Y,xt,2);Nt?Fe.appendChild(Nt):Fe.textContent=no}else Fe.textContent=no;Fe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ln?(Fe.style.backgroundColor=Ln,Fe.classList.remove("persona-bg-persona-primary")):(Fe.style.backgroundColor="",Fe.classList.add("persona-bg-persona-primary"))}else Fe.textContent=(up=(pp=r.copy)==null?void 0:pp.sendButtonLabel)!=null?up:"Send",Fe.style.width="",Fe.style.height="",Fe.style.minWidth="",Fe.style.minHeight="",Fe.style.fontSize="",Fe.style.lineHeight="",Fe.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",Ln?(Fe.style.backgroundColor=Ln,Fe.classList.remove("persona-bg-persona-accent")):Fe.classList.add("persona-bg-persona-accent"),Rt?Fe.style.color=Rt:Fe.classList.add("persona-text-white");jt.borderWidth?(Fe.style.borderWidth=jt.borderWidth,Fe.style.borderStyle="solid"):(Fe.style.borderWidth="",Fe.style.borderStyle=""),jt.borderColor?Fe.style.borderColor=jt.borderColor:Fe.style.borderColor="",jt.paddingX?(Fe.style.paddingLeft=jt.paddingX,Fe.style.paddingRight=jt.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),jt.paddingY?(Fe.style.paddingTop=jt.paddingY,Fe.style.paddingBottom=jt.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Ut=ln==null?void 0:ln.querySelector(".persona-send-button-tooltip");if(Rr&&Mn)if(Ut)Ut.textContent=Mn,Ut.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=Mn,ln==null||ln.insertBefore(Y,Fe)}else Ut&&(Ut.style.display="none");let Ht=(yp=(mp=r.layout)==null?void 0:mp.contentMaxWidth)!=null?yp:q()?(hp=(fp=(gp=r.launcher)==null?void 0:gp.composerBar)==null?void 0:fp.contentMaxWidth)!=null?hp:"720px":void 0;Ht?(Xe.style.maxWidth=Ht,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%",It&&(It.style.maxWidth=Ht,It.style.marginLeft="auto",It.style.marginRight="auto"),$t&&($t.style.maxWidth=Ht,$t.style.marginLeft="auto",$t.style.marginRight="auto")):(Xe.style.maxWidth="",Xe.style.marginLeft="",Xe.style.marginRight="",Xe.style.width="",It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""),$t&&($t.style.maxWidth="",$t.style.marginLeft="",$t.style.marginRight=""));let qt=(bp=r.statusIndicator)!=null?bp:{},Pn=(xp=qt.visible)!=null?xp:!0;if(zt.style.display=Pn?"":"none",U){let Y=U.getStatus();Be(zt,(Nt=>{var at,At,on,fn;return Nt==="idle"?(at=qt.idleText)!=null?at:hn.idle:Nt==="connecting"?(At=qt.connectingText)!=null?At:hn.connecting:Nt==="connected"?(on=qt.connectedText)!=null?on:hn.connected:Nt==="error"?(fn=qt.errorText)!=null?fn:hn.error:hn[Nt]})(Y),qt,Y)}zt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let _n=qt.align==="left"?"persona-text-left":qt.align==="center"?"persona-text-center":"persona-text-right";zt.classList.add(_n)},open(){_()&&Wt(!0,"api")},close(){_()&&Wt(!1,"api")},toggle(){_()&&Wt(!B,"api")},clearChat(){bn=!1,U.clearMessages(),On.clear(),Gr();try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.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)}d={},M.syncFromMetadata(),X==null||X.clear(),oe==null||oe.update()},setMessage(c){return!le||U.isStreaming()?!1:(!B&&_()&&Wt(!0,"system"),le.value=c,le.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(U.isStreaming())return!1;let m=(c==null?void 0:c.trim())||le.value.trim();return m?(!B&&_()&&Wt(!0,"system"),le.value="",le.style.height="auto",U.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return U.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(U.isVoiceActive()||(!B&&_()&&Wt(!0,"system"),ct.manuallyDeactivated=!1,kn(),U.toggleVoice().then(()=>{ct.active=U.isVoiceActive(),Gn("user"),U.isVoiceActive()&&to()})),!0):$n?!0:ks()?(!B&&_()&&Wt(!0,"system"),ct.manuallyDeactivated=!1,kn(),xo("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?U.isVoiceActive()?(U.toggleVoice().then(()=>{ct.active=!1,ct.manuallyDeactivated=!0,kn(),Gn("user"),lr()}),!0):!1:$n?(ct.manuallyDeactivated=!0,kn(),ir("user"),!0):!1},injectMessage(c){return!B&&_()&&Wt(!0,"system"),U.injectMessage(c)},injectAssistantMessage(c){!B&&_()&&Wt(!0,"system");let m=U.injectAssistantMessage(c);return O&&(O=!1,G&&(clearTimeout(G),G=null),setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)),m},injectUserMessage(c){return!B&&_()&&Wt(!0,"system"),U.injectUserMessage(c)},injectSystemMessage(c){return!B&&_()&&Wt(!0,"system"),U.injectSystemMessage(c)},injectMessageBatch(c){return!B&&_()&&Wt(!0,"system"),U.injectMessageBatch(c)},injectTestMessage(c){!B&&_()&&Wt(!0,"system"),U.injectTestEvent(c)},async connectStream(c,m){return U.connectStream(c,m)},__pushEventStreamEvent(c){X&&X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!he||!X||Ar()},hideEventStream(){Le&&er()},isEventStreamVisible(){return Le},showArtifacts(){Zn(r)&&(bn=!1,Dn(),gt==null||gt.setMobileOpen(!0))},hideArtifacts(){Zn(r)&&(bn=!0,Dn())},upsertArtifact(c){return Zn(r)?(bn=!1,U.upsertArtifact(c)):null},selectArtifact(c){Zn(r)&&U.selectArtifact(c)},clearArtifacts(){Zn(r)&&U.clearArtifacts()},getArtifacts(){var c;return(c=U==null?void 0:U.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=U==null?void 0:U.getSelectedArtifactId())!=null?c:null},focusInput(){return A&&!B&&!q()||!le?!1:(le.focus(),!0)},async resolveApproval(c,m){let b=U.getMessages().find(k=>{var D;return k.variant==="approval"&&((D=k.approval)==null?void 0:D.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);return U.resolveApproval(b.approval,m)},getMessages(){return U.getMessages()},getStatus(){return U.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return o.on(c,m)},off(c,m){o.off(c,m)},isOpen(){return _()&&B},isVoiceActive(){return ct.active},getState(){return{open:_()&&B,launcherEnabled:A,voiceActive:ct.active,streaming:U.isStreaming()}},showCSATFeedback(c){!B&&_()&&Wt(!0,"system");let m=Xe.querySelector(".persona-feedback-container");m&&m.remove();let y=xi({onSubmit:async(b,k)=>{var D;U.isClientTokenMode()&&await U.submitCSATFeedback(b,k),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});Xe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!B&&_()&&Wt(!0,"system");let m=Xe.querySelector(".persona-feedback-container");m&&m.remove();let y=vi({onSubmit:async(b,k)=>{var D;U.isClientTokenMode()&&await U.submitNPSFeedback(b,k),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});Xe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return U.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return U.submitNPSFeedback(c,m)},destroy(){yr!=null&&(clearInterval(yr),yr=null),pt.forEach(c=>c()),Q.remove(),we==null||we.remove(),S==null||S.destroy(),z==null||z.remove(),Fn&&I.removeEventListener("click",Fn)}};if((((bc=t==null?void 0:t.debugTools)!=null?bc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:y=>y?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=m,pt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=V=>{let W=V.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",m),pt.push(()=>{window.removeEventListener("persona:focusInput",m)}),he){let V=be=>{let ce=be.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&en.showEventStream()},W=be=>{let ce=be.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",W),pt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",W)})}let y=V=>{let W=V.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.showArtifacts()},b=V=>{let W=V.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.hideArtifacts()},k=V=>{let W=V.detail;W!=null&&W.instanceId&&W.instanceId!==c||W!=null&&W.artifact&&en.upsertArtifact(W.artifact)},D=V=>{let W=V.detail;W!=null&&W.instanceId&&W.instanceId!==c||typeof(W==null?void 0:W.id)=="string"&&en.selectArtifact(W.id)},F=V=>{let W=V.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",F),pt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",F)})}let Qn=Pf(r.persistState);if(Qn&&_()){let c=If(Qn.storage),m=`${Qn.keyPrefix}widget-open`,y=`${Qn.keyPrefix}widget-voice`,b=`${Qn.keyPrefix}widget-voice-mode`;if(c){let k=((xc=Qn.persist)==null?void 0:xc.openState)&&c.getItem(m)==="true",D=((vc=Qn.persist)==null?void 0:vc.voiceState)&&c.getItem(y)==="true",F=((wc=Qn.persist)==null?void 0:wc.voiceState)&&c.getItem(b)==="true";if(k&&setTimeout(()=>{en.open(),setTimeout(()=>{var V;if(D||F)en.startVoiceRecognition();else if((V=Qn.persist)!=null&&V.focusInput){let W=e.querySelector("textarea");W&&W.focus()}},100)},0),(Cc=Qn.persist)!=null&&Cc.openState&&(o.on("widget:opened",()=>{c.setItem(m,"true")}),o.on("widget:closed",()=>{c.setItem(m,"false")})),(Ac=Qn.persist)!=null&&Ac.voiceState&&(o.on("voice:state",V=>{c.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{c.setItem(b,V.viaVoice?"true":"false")})),Qn.clearOnChatClear){let V=()=>{c.removeItem(m),c.removeItem(y),c.removeItem(b)},W=()=>V();window.addEventListener("persona:clear-chat",W),pt.push(()=>{window.removeEventListener("persona:clear-chat",W)})}}}return u&&_()&&setTimeout(()=>{en.open()},0),Pr(),en};var Wf=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},Vu=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},fl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Ju=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",fl(e)},ul=e=>{e.style.transition=""},ml=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},gl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ai=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Rf=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Hf=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Ku=(e,n,t,r,s,o,a)=>{var w,x,M,A,P,N;let i=Xn(o),d=i.reveal==="push";Rf(e,n,t,r,d),Hf(e,n,t,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileFullscreen)!=null?x:!0,p=(A=(M=o==null?void 0:o.launcher)==null?void 0:M.mobileBreakpoint)!=null?A:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ml(n),ul(r),Ju(r),gl(t),Ai(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((N=(P=o==null?void 0:o.launcher)==null?void 0:P.zIndex)!=null?N:yn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ju(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ml(n),ul(r),gl(t),Ai(s,r);let R=i.animate?"transform 180ms ease":"none",T=i.side==="right"?"translateX(100%)":"translateX(-100%)",L=a?"translateX(0)":T;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=R,r.style.transform=L,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ul(r),fl(r),Ai(s,r);let R=Wf(i.width,e.clientWidth),T=Math.max(0,e.clientWidth),L=i.animate?"transform 180ms ease":"none",$=i.side==="right"?a?`translateX(-${R}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${R}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${T+R}px`,n.style.transition=L,n.style.transform=$,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${T}px`,t.style.maxWidth=`${T}px`,t.style.minWidth=`${T}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ml(n),fl(r),gl(t),Ai(s,r);let R=i.reveal==="emerge";R?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let T=a?i.width:"0px",L=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",$=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${T}`,r.style.width=T,r.style.maxWidth=T,r.style.minWidth=T,r.style.minHeight="0",r.style.position="relative",r.style.overflow=R||$?"hidden":"visible",r.style.transition=L,R&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Bf=(e,n)=>{let t=e.ownerDocument.createElement("div");return Vu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Vu(t,r)},destroy(){t.remove()}}},Df=(e,n)=>{var P,N,R,T;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(N=(P=n==null?void 0:n.launcher)==null?void 0:P.enabled)==null||N?(T=(R=n==null?void 0:n.launcher)==null?void 0:R.autoExpand)!=null?T:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},w=()=>{g(),Xn(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Ku(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{Ku(a,i,d,l,u,n,p),w()},M=a.ownerDocument.defaultView,A=()=>{x()};return M==null||M.addEventListener("resize",A),Xn(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(L){let $=L.launcherEnabled?L.open:!0;p!==$&&(p=$,x())},updateConfig(L){var $,q;n=L,((q=($=n==null?void 0:n.launcher)==null?void 0:$.enabled)!=null?q:!0)===!1&&(p=!0),x()},destroy(){M==null||M.removeEventListener("resize",A),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},na=(e,n)=>nn(n)?Df(e,n):Bf(e,n);var hl={},Nf=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Ff=()=>{try{if(typeof hl!="undefined"&&hl.url)return new URL("../widget.css",hl.url).href}catch{}return null},Gu=(e,n)=>{let t=Ff(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},yl=e=>{var M;let n=Nf(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=na(n,s),a,i=[],d=(A,P)=>{var L,$;let R=!(($=(L=P==null?void 0:P.launcher)==null?void 0:L.enabled)!=null?$:!0)||nn(P),T=r.createElement("div");if(T.setAttribute("data-persona-root","true"),R&&(T.style.height="100%",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1",T.style.minHeight="0"),t){let q=A.attachShadow({mode:"open"});q.appendChild(T),Gu(q,r)}else A.appendChild(T),Gu(A,r);return n.id&&T.setAttribute("data-persona-instance",n.id),T},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let A=d(o.host,s);a=Ci(A,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(A=>A()),i=[],a.destroy()};p(),(M=e.onReady)==null||M.call(e);let g=A=>{f(),o.destroy(),o=na(n,A),s=A,p()},w={update(A){var $,q,_,B,O,G;let P={...s,...A,launcher:{...($=s==null?void 0:s.launcher)!=null?$:{},...(q=A==null?void 0:A.launcher)!=null?q:{},dock:{...(B=(_=s==null?void 0:s.launcher)==null?void 0:_.dock)!=null?B:{},...(G=(O=A==null?void 0:A.launcher)==null?void 0:O.dock)!=null?G:{}}}},N=nn(s),R=nn(P),T=ao(s),L=ao(P);if(N!==R||T!==L){g(P);return}s=P,o.updateConfig(s),a.update(A),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(w,{get(A,P,N){if(P==="host")return o.host;if(P in A)return Reflect.get(A,P,N);let R=a[P];return typeof R=="function"?R.bind(a):R}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var em=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Of=new Set(["button","a","input","select","textarea","details","summary"]),$f=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),bl=/\b(product|card|item|listing|result)\b/i,vl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,_f=3e3,Uf=100;function tm(e){let n=typeof e.className=="string"?e.className:"";if(bl.test(n)||e.id&&bl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&bl.test(r.value))return!0}return!1}function nm(e){var n;return vl.test(((n=e.textContent)!=null?n:"").trim())}function rm(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function jf(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Qu(e){let n=e.match(vl);return n?n[0]:null}function Xu(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function qf(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var zf="commerce-card",Vf="result-card";function Yu(e){return!tm(e)||!nm(e)||!rm(e)&&!jf(e)?0:5200}function Zu(e){var r;return!tm(e)||nm(e)||!rm(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var wl=[{id:zf,scoreElement(e){return Yu(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||vl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(Yu(e)===0)return null;let{title:t,href:r}=Xu(e),s=(u=(l=Qu(((d=e.textContent)!=null?d:"").trim()))!=null?l:Qu(n.text))!=null?u:"",o=qf(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
101
+ `)}},{id:Vf,scoreElement(e){return Zu(e)},formatSummary(e,n){if(Zu(e)===0)return null;let{title:t,href:r}=Xu(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
102
+ `)}}];function Jf(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Kf(e){var u,p,f,g,w,x,M,A,P,N,R,T,L;let n=(u=e.options)!=null?u:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(w=(g=n.excludeSelector)!=null?g:e.excludeSelector)!=null?w:".persona-host",s=(M=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?M:200,o=(P=(A=n.visibleOnly)!=null?A:e.visibleOnly)!=null?P:!0,a=(N=n.root)!=null?N:e.root,i=(R=n.mode)!=null?R:"structured",d=(T=n.maxCandidates)!=null?T:Math.max(500,t*10),l=(L=e.rules)!=null?L:wl;return i==="simple"&&e.rules&&e.rules.length>0?(Jf(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function xl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Gf=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Qf(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||Of.has(n)||t&&$f.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function om(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Xf(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(n[u.name]=u.value)}return n}function Cl(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${xl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Gf){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${xl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>xl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function Yf(e){return e==="static"?Uf:_f}function sm(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:Cl(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:Qf(e),attributes:Xf(e)}}function Zf(e,n,t,r){let s=Yf(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function eh(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function th(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(em.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!om(l)){i=a.nextNode();continue}let p=sm(l,e.maxTextLength),f=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(M=>M==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:w,formattingRule:x}=Zf(l,p,e.rules,t);s.push({el:l,domIndex:o,enriched:p,score:w,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;eh(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let g=l.formattingRule.formatSummary(l.el,l.enriched,t);g&&(u=g)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function nh(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(em.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!om(d)){o=s.nextNode();continue}let u=sm(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(g=>g==="role");if(!p&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function am(e={}){var r;let n=Kf(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?nh(n,t):th(n,t):[]}var Si=100;function im(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
103
103
  ${a.map(i=>`- ${i.split(`
104
104
  `).join(`
105
105
  `)}`).join(`
106
- `)}`)}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,Ga)}" (clickable)`);r.push(`Interactive elements:
106
+ `)}`)}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,Si)}" (clickable)`);r.push(`Interactive elements:
107
107
  ${a.join(`
108
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Ga)}" (navigable)`);r.push(`Navigation links:
108
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Si)}" (navigable)`);r.push(`Navigation links:
109
109
  ${a.join(`
110
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Ga)}" (input)`);r.push(`Form inputs:
110
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Si)}" (input)`);r.push(`Form inputs:
111
111
  ${a.join(`
112
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Ga)}"`);r.push(`Content:
112
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Si)}"`);r.push(`Content:
113
113
  ${a.join(`
114
114
  `)}`)}return r.join(`
115
115
 
116
- `)}var Mu={name:"@runtypelabs/persona",version:"3.18.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{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 Lo=Mu.version;function Wr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function xf(e){if(e)return{getHeaders:Wr(e.getHeaders),onFeedback:Wr(e.onFeedback),onCopy:Wr(e.onCopy),requestMiddleware:Wr(e.requestMiddleware),actionHandlers:Wr(e.actionHandlers),actionParsers:Wr(e.actionParsers),postprocessMessage:Wr(e.postprocessMessage),contextProviders:Wr(e.contextProviders),streamParser:Wr(e.streamParser)}}var ku=`({ text, message }: any) => {
116
+ `)}var lm={name:"@runtypelabs/persona",version:"3.19.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{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 $o=lm.version;function _r(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function oh(e){if(e)return{getHeaders:_r(e.getHeaders),onFeedback:_r(e.onFeedback),onCopy:_r(e.onCopy),requestMiddleware:_r(e.requestMiddleware),actionHandlers:_r(e.actionHandlers),actionParsers:_r(e.actionParsers),postprocessMessage:_r(e.postprocessMessage),contextProviders:_r(e.contextProviders),streamParser:_r(e.streamParser)}}var cm=`({ text, message }: any) => {
117
117
  const jsonSource = (message as any).rawContent || text || message.content;
118
118
  if (!jsonSource || typeof jsonSource !== 'string') return null;
119
119
  let cleanJson = jsonSource
@@ -126,7 +126,7 @@ ${a.join(`
126
126
  if (parsed.action) return { type: parsed.action, payload: parsed };
127
127
  } catch (e) { return null; }
128
128
  return null;
129
- }`,Lu=`function(ctx) {
129
+ }`,dm=`function(ctx) {
130
130
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
131
131
  if (!jsonSource || typeof jsonSource !== 'string') return null;
132
132
  var cleanJson = jsonSource
@@ -139,7 +139,7 @@ ${a.join(`
139
139
  if (parsed.action) return { type: parsed.action, payload: parsed };
140
140
  } catch (e) { return null; }
141
141
  return null;
142
- }`,Iu=`(action: any, context: any) => {
142
+ }`,pm=`(action: any, context: any) => {
143
143
  if (action.type !== 'nav_then_click') return;
144
144
  const payload = action.payload || action.raw || {};
145
145
  const url = payload?.page;
@@ -156,7 +156,7 @@ ${a.join(`
156
156
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
157
157
  window.location.href = targetUrl;
158
158
  return { handled: true, displayText: text };
159
- }`,Pu=`function(action, context) {
159
+ }`,um=`function(action, context) {
160
160
  if (action.type !== 'nav_then_click') return;
161
161
  var payload = action.payload || action.raw || {};
162
162
  var url = payload.page;
@@ -173,26 +173,26 @@ ${a.join(`
173
173
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
174
174
  window.location.href = targetUrl;
175
175
  return { handled: true, displayText: text };
176
- }`,vf=`(parsed: any) => {
176
+ }`,sh=`(parsed: any) => {
177
177
  if (!parsed || typeof parsed !== 'object') return null;
178
178
  if (parsed.action === 'nav_then_click') return 'Navigating...';
179
179
  if (parsed.action === 'message') return parsed.text || '';
180
180
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
181
181
  return parsed.text || null;
182
- }`,wf=`function(parsed) {
182
+ }`,ah=`function(parsed) {
183
183
  if (!parsed || typeof parsed !== 'object') return null;
184
184
  if (parsed.action === 'nav_then_click') return 'Navigating...';
185
185
  if (parsed.action === 'message') return parsed.text || '';
186
186
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
187
187
  return parsed.text || null;
188
- }`;function Cf(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function Qa(e){var n,t;return(t=(n=e.parserType)!=null?n:Cf(e.streamParser))!=null?t:"plain"}function Ya(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function Xa(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function Za(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function ei(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?t.push(`${n} ${i}: "${p}",`):typeof p=="boolean"&&t.push(`${n} ${i}: ${p},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([p,c])=>{p!=="format"&&(typeof c=="string"?t.push(`${n} ${p}: "${c}",`):typeof c=="boolean"&&t.push(`${n} ${p}: ${c},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function Qi(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function Wu(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),Wu(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function to(e,n,t,r){t&&(e.push(`${r}${n}: {`),Wu(e,t,`${r} `),e.push(`${r}},`))}function Ru(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:xf(t.hooks)}:void 0;return n==="esm"?Af(r,s):n==="script-installer"?Tf(r,s):n==="script-advanced"?kf(r,s):n==="react-component"?Sf(r,s):n==="react-advanced"?Ef(r,s):Mf(r,s)}function Af(e,n){let t=n==null?void 0:n.hooks,r=Qa(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&to(o,"theme",e.theme," "),e.launcher&&to(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(...Ya(e," ")),o.push(...Xa(e," ",t)),o.push(...Za(e," ")),o.push(...ei(e," ")),o.push(...Qi(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(`
189
- `)}function Sf(e,n){let t=n==null?void 0:n.hooks,r=Qa(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&to(o,"theme",e.theme," "),e.launcher&&to(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(...Ya(e," ")),o.push(...Xa(e," ",t)),o.push(...Za(e," ")),o.push(...ei(e," ")),o.push(...Qi(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(`
190
- `)}function Ef(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&to(r,"theme",e.theme," "),e.launcher&&to(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ya(e," ")),r.push(...Xa(e," ",t)),r.push(...Za(e," ")),r.push(...ei(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${vf}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${ku}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${ku}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Iu}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Iu}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
191
- `)}function Hu(e){var s;let n=Qa(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,p])=>{i!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,p])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof p=="object"&&p!==null)a.avatar=p;else if(i==="timestamp"&&typeof p=="object"&&p!==null){let c={};Object.entries(p).forEach(([u,d])=>{u!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[u]=d)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function Tf(e,n){let t=Hu(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Lo}/dist/install.global.js" data-config='${s}'></script>`}function Mf(e,n){let t=n==null?void 0:n.hooks,r=Qa(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Lo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Lo}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&to(o,"theme",e.theme," "),e.launcher&&to(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(...Ya(e," ")),o.push(...Xa(e," ",t)),o.push(...Za(e," ")),o.push(...ei(e," ")),o.push(...Qi(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(`
192
- `)}function kf(e,n){let t=n==null?void 0:n.hooks,r=Hu(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
188
+ }`;function ih(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function Ei(e){var n,t;return(t=(n=e.parserType)!=null?n:ih(e.streamParser))!=null?t:"plain"}function Ti(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function ki(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function Mi(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function Li(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${n} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${n} ${d}: ${l},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function Al(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function mm(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),mm(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function mo(e,n,t,r){t&&(e.push(`${r}${n}: {`),mm(e,t,`${r} `),e.push(`${r}},`))}function gm(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:oh(t.hooks)}:void 0;return n==="esm"?lh(r,s):n==="script-installer"?ph(r,s):n==="script-advanced"?mh(r,s):n==="react-component"?ch(r,s):n==="react-advanced"?dh(r,s):uh(r,s)}function lh(e,n){let t=n==null?void 0:n.hooks,r=Ei(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&mo(o,"theme",e.theme," "),e.launcher&&mo(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(...Ti(e," ")),o.push(...ki(e," ",t)),o.push(...Mi(e," ")),o.push(...Li(e," ")),o.push(...Al(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(`
189
+ `)}function ch(e,n){let t=n==null?void 0:n.hooks,r=Ei(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&mo(o,"theme",e.theme," "),e.launcher&&mo(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(...Ti(e," ")),o.push(...ki(e," ",t)),o.push(...Mi(e," ")),o.push(...Li(e," ")),o.push(...Al(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(`
190
+ `)}function dh(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&mo(r,"theme",e.theme," "),e.launcher&&mo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ti(e," ")),r.push(...ki(e," ",t)),r.push(...Mi(e," ")),r.push(...Li(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${sh}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${cm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${cm}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${pm}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${pm}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
191
+ `)}function fm(e){var s;let n=Ei(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function ph(e,n){let t=fm(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${$o}/dist/install.global.js" data-config='${s}'></script>`}function uh(e,n){let t=n==null?void 0:n.hooks,r=Ei(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${$o}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${$o}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&mo(o,"theme",e.theme," "),e.launcher&&mo(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(...Ti(e," ")),o.push(...ki(e," ",t)),o.push(...Mi(e," ")),o.push(...Li(e," ")),o.push(...Al(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(`
192
+ `)}function mh(e,n){let t=n==null?void 0:n.hooks,r=fm(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
193
193
  `).map((a,i)=>i===0?a:" "+a).join(`
194
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Lo}/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(${wf});`),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(` ${Lu}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Lu}`),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(` ${Pu}`),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(` ${Pu}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
195
- `)}var Bu={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Du=.1,Nu=.15,Fu=1.5,Yi=24,Ou=40,Lf=`
194
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${$o}/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(${ah});`),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(` ${dm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${dm}`),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(` ${um}`),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(` ${um}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
195
+ `)}var hm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ym=.1,bm=.15,xm=1.5,Sl=24,vm=40,gh=`
196
196
  /* \u2500\u2500 Root \u2500\u2500 */
197
197
  .persona-dc-root {
198
198
  display: flex;
@@ -343,7 +343,7 @@ ${a.join(`
343
343
  .persona-dc-stage {
344
344
  height: 550px;
345
345
  min-height: 400px;
346
- padding: ${Yi}px;
346
+ padding: ${Sl}px;
347
347
  overflow: auto;
348
348
  background: #f0f1f3;
349
349
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -433,5 +433,5 @@ ${a.join(`
433
433
  min-height: 300px;
434
434
  }
435
435
  }
436
- `;function If(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Lf,document.head.appendChild(e)}function Pf(e,n){let t=e.clientWidth-Yi*2-Ou,r=e.clientHeight-Yi*2-Ou;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function Wf(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function $u(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:c}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");If();let u=Math.max(0,Math.min(r,t.length-1)),d=s,f=o,g=null,v=1,E=!1,w=h("div","persona-dc-root"),A=h("div","persona-dc-toolbar"),I=h("div","persona-dc-toolbar-lead"),U=h("div","persona-dc-toolbar-trail"),k=Ft({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ie(-1)}),L=h("div");L.style.position="relative";let M=h("button","persona-dc-title-btn");M.type="button",M.setAttribute("aria-expanded","false"),M.setAttribute("aria-haspopup","listbox");let P=h("span","persona-dc-title-text"),N=h("span","persona-dc-title-chevron"),K=Ae("chevron-down",12,"currentColor",2);K&&N.appendChild(K),M.append(P,N);let G=h("div","persona-dc-dropdown");G.setAttribute("role","listbox"),G.style.display="none";let j=!1;function ie(){G.innerHTML="";for(let _=0;_<t.length;_++){let q=t[_],le=h("button","persona-dc-dropdown-item");le.type="button",le.setAttribute("role","option"),le.setAttribute("aria-current",_===u?"true":"false");let Ee=h("span");if(Ee.textContent=q.title,le.appendChild(Ee),q.description){let ee=h("span","persona-dc-dropdown-desc");ee.textContent=q.description,le.appendChild(ee)}le.addEventListener("click",()=>{ue(),Pe(_)}),G.appendChild(le)}}function ve(){j=!j,G.style.display=j?"":"none",M.setAttribute("aria-expanded",j?"true":"false"),j&&ie()}function ue(){j&&(j=!1,G.style.display="none",M.setAttribute("aria-expanded","false"))}M.addEventListener("click",_=>{_.stopPropagation(),ve()});let Oe=()=>ue();document.addEventListener("click",Oe),L.append(M,G);let fe=Ft({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ie(1)}),De=h("span","persona-dc-counter");I.append(k,L,fe,De);let Le=null;i&&(Le=Ns({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:_=>{d=_,Q.dataset.device=d,g=null,R()}}),U.appendChild(Le.element));let Ne=null;if(a){let _=h("div","persona-dc-zoom-controls"),q=Ft({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.max(Nu,ee-Du),R()}});Ne=h("span","persona-dc-zoom-level"),Ne.title="Reset to 100%",Ne.style.cursor="pointer",Ne.addEventListener("click",()=>{g=1,R()});let le=Ft({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.min(Fu,ee+Du),R()}}),Ee=Ft({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,R()}});_.append(q,Ne,le,Ee),U.appendChild(_)}if(p){let _=h("div","persona-dc-separator");U.appendChild(_);let q=Ns({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:le=>{f=le,Q.dataset.colorScheme=f,pe()}});U.appendChild(q.element)}let de=h("div","persona-dc-separator");U.appendChild(de);let X=Ft({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});U.appendChild(X),A.append(I,U);let ge=h("div","persona-dc-stage"),Q=h("div","persona-dc-iframe-wrapper");Q.dataset.device=d,Q.dataset.colorScheme=f;let me=h("iframe","persona-dc-iframe");me.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),me.setAttribute("loading","lazy"),me.title=t[u].title,Q.appendChild(me),ge.appendChild(Q),w.append(A,ge),e.appendChild(w);function pe(){var _;try{let q=(_=me.contentDocument)==null?void 0:_.body;if(!q)return;f==="dark"?q.classList.add("theme-dark"):q.classList.remove("theme-dark")}catch{}}me.addEventListener("load",()=>pe());function oe(){let _=t[u];P.textContent=_.title,De.textContent=`${u+1} / ${t.length}`,me.title=_.title}function Ie(_){let q=((u+_)%t.length+t.length)%t.length;Pe(q)}function Pe(_){_<0||_>=t.length||(u=_,me.src=t[u].url,oe(),c==null||c(u,t[u]))}function R(){var le;if(E)return;let _=(le=Bu[d])!=null?le:Bu.desktop;v=Pf(ge,_);let q=Math.max(Nu,Math.min(Fu,g!=null?g:v));Wf(Q,me,_,q,d),Ne&&(Ne.textContent=`${Math.round(q*100)}%`)}let z=new ResizeObserver(()=>R());z.observe(ge),oe(),me.src=t[u].url,requestAnimationFrame(()=>R());function ne(){E||(E=!0,z.disconnect(),document.removeEventListener("click",Oe),w.remove())}return{element:w,goTo:Pe,next:()=>Ie(1),prev:()=>Ie(-1),getIndex:()=>u,setDevice(_){d=_,Q.dataset.device=_,Le==null||Le.setSelected(_),g=null,R()},setColorScheme(_){f=_,Q.dataset.colorScheme=_},setZoom(_){g=_,R()},destroy:ne}}function _u(){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 ju(){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 Uu(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:fr(e.colors.primary,.95),100:fr(e.colors.primary,.9),200:fr(e.colors.primary,.8),300:fr(e.colors.primary,.7),400:fr(e.colors.primary,.6),500:e.colors.primary,600:fr(e.colors.primary,.8),700:fr(e.colors.primary,.7),800:fr(e.colors.primary,.6),900:fr(e.colors.primary,.5),950:fr(e.colors.primary,.45)}}),{...n,palette:t}}}}function qu(){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 zu(){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 fr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Vu(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Rf={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"}}},Ju={components:{panel:{borderRadius:"0",shadow:"none"}}},Xi={id:"shop",label:"Shopping Assistant",config:{theme:Rf,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:On},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?"]}},Zi={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ju}},el={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ju}},tl={shop:Xi,minimal:Zi,fullscreen:el};function Ku(e){return tl[e]}var Hf=qi;0&&(module.exports={ASK_USER_QUESTION_TOOL_NAME,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,createAskUserQuestionBubble,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,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,listRegisteredStreamAnimations,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
436
+ `;function fh(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=gh,document.head.appendChild(e)}function hh(e,n){let t=e.clientWidth-Sl*2-vm,r=e.clientHeight-Sl*2-vm;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function yh(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function wm(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");fh();let u=Math.max(0,Math.min(r,t.length-1)),p=s,f=o,g=null,w=1,x=!1,M=h("div","persona-dc-root"),A=h("div","persona-dc-toolbar"),P=h("div","persona-dc-toolbar-lead"),N=h("div","persona-dc-toolbar-trail"),R=Ot({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>De(-1)}),T=h("div");T.style.position="relative";let L=h("button","persona-dc-title-btn");L.type="button",L.setAttribute("aria-expanded","false"),L.setAttribute("aria-haspopup","listbox");let $=h("span","persona-dc-title-text"),q=h("span","persona-dc-title-chevron"),_=ge("chevron-down",12,"currentColor",2);_&&q.appendChild(_),L.append($,q);let B=h("div","persona-dc-dropdown");B.setAttribute("role","listbox"),B.style.display="none";let O=!1;function G(){B.innerHTML="";for(let Q=0;Q<t.length;Q++){let J=t[Q],we=h("button","persona-dc-dropdown-item");we.type="button",we.setAttribute("role","option"),we.setAttribute("aria-current",Q===u?"true":"false");let de=h("span");if(de.textContent=J.title,we.appendChild(de),J.description){let ne=h("span","persona-dc-dropdown-desc");ne.textContent=J.description,we.appendChild(ne)}we.addEventListener("click",()=>{Ee(),He(Q)}),B.appendChild(we)}}function re(){O=!O,B.style.display=O?"":"none",L.setAttribute("aria-expanded",O?"true":"false"),O&&G()}function Ee(){O&&(O=!1,B.style.display="none",L.setAttribute("aria-expanded","false"))}L.addEventListener("click",Q=>{Q.stopPropagation(),re()});let Re=()=>Ee();document.addEventListener("click",Re),T.append(L,B);let Ue=Ot({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>De(1)}),he=h("span","persona-dc-counter");P.append(R,T,Ue,he);let ue=null;i&&(ue=Gs({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:Q=>{p=Q,X.dataset.device=p,g=null,K()}}),N.appendChild(ue.element));let ke=null;if(a){let Q=h("div","persona-dc-zoom-controls"),J=Ot({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ne=g!=null?g:w;g=Math.max(bm,ne-ym),K()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{g=1,K()});let we=Ot({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ne=g!=null?g:w;g=Math.min(xm,ne+ym),K()}}),de=Ot({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,K()}});Q.append(J,ke,we,de),N.appendChild(Q)}if(d){let Q=h("div","persona-dc-separator");N.appendChild(Q);let J=Gs({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:we=>{f=we,X.dataset.colorScheme=f,Le()}});N.appendChild(J.element)}let je=h("div","persona-dc-separator");N.appendChild(je);let te=Ot({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});N.appendChild(te),A.append(P,N);let ve=h("div","persona-dc-stage"),X=h("div","persona-dc-iframe-wrapper");X.dataset.device=p,X.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[u].title,X.appendChild(oe),ve.appendChild(X),M.append(A,ve),e.appendChild(M);function Le(){var Q;try{let J=(Q=oe.contentDocument)==null?void 0:Q.body;if(!J)return;f==="dark"?J.classList.add("theme-dark"):J.classList.remove("theme-dark")}catch{}}oe.addEventListener("load",()=>Le());function ie(){let Q=t[u];$.textContent=Q.title,he.textContent=`${u+1} / ${t.length}`,oe.title=Q.title}function De(Q){let J=((u+Q)%t.length+t.length)%t.length;He(J)}function He(Q){Q<0||Q>=t.length||(u=Q,oe.src=t[u].url,ie(),l==null||l(u,t[u]))}function K(){var we;if(x)return;let Q=(we=hm[p])!=null?we:hm.desktop;w=hh(ve,Q);let J=Math.max(bm,Math.min(xm,g!=null?g:w));yh(X,oe,Q,J,p),ke&&(ke.textContent=`${Math.round(J*100)}%`)}let Ne=new ResizeObserver(()=>K());Ne.observe(ve),ie(),oe.src=t[u].url,requestAnimationFrame(()=>K());function Be(){x||(x=!0,Ne.disconnect(),document.removeEventListener("click",Re),M.remove())}return{element:M,goTo:He,next:()=>De(1),prev:()=>De(-1),getIndex:()=>u,setDevice(Q){p=Q,X.dataset.device=Q,ue==null||ue.setSelected(Q),g=null,K()},setColorScheme(Q){f=Q,X.dataset.colorScheme=Q},setZoom(Q){g=Q,K()},destroy:Be}}function Cm(){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 Am(){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 Sm(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:vr(e.colors.primary,.95),100:vr(e.colors.primary,.9),200:vr(e.colors.primary,.8),300:vr(e.colors.primary,.7),400:vr(e.colors.primary,.6),500:e.colors.primary,600:vr(e.colors.primary,.8),700:vr(e.colors.primary,.7),800:vr(e.colors.primary,.6),900:vr(e.colors.primary,.5),950:vr(e.colors.primary,.45)}}),{...n,palette:t}}}}function Em(){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 Tm(){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 vr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function km(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var bh={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"}}},Mm={components:{panel:{borderRadius:"0",shadow:"none"}}},El={id:"shop",label:"Shopping Assistant",config:{theme:bh,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:jn},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?"]}},Tl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Mm}},kl={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Mm}},Ml={shop:El,minimal:Tl,fullscreen:kl};function Lm(e){return Ml[e]}var xh=yl;0&&(module.exports={ASK_USER_QUESTION_TOOL_NAME,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,createAskUserQuestionBubble,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,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,listRegisteredStreamAnimations,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
437
437
  //# sourceMappingURL=index.cjs.map