@runtypelabs/persona 3.21.2 → 3.21.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var Hm=Object.create;var Aa=Object.defineProperty;var Bm=Object.getOwnPropertyDescriptor;var Dm=Object.getOwnPropertyNames;var Nm=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var Om=(e,n)=>{for(var t in n)Aa(e,t,{get:n[t],enumerable:!0})},wp=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Dm(n))!Fm.call(e,o)&&o!==t&&Aa(e,o,{get:()=>n[o],enumerable:!(r=Bm(n,o))||r.enumerable});return e};var $m=(e,n,t)=>(t=e!=null?Hm(Nm(e)):{},wp(n||!e||!e.__esModule?Aa(t,"default",{value:e,enumerable:!0}):t,e)),_m=e=>wp(Aa({},"__esModule",{value:!0}),e);var Lh={};Om(Lh,{ASK_USER_QUESTION_TOOL_NAME:()=>tl,AgentWidgetClient:()=>Io,AgentWidgetSession:()=>es,AttachmentManager:()=>Bo,DEFAULT_COMPONENTS:()=>Ni,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>$a,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Un,DEFAULT_PALETTE:()=>Bi,DEFAULT_SEMANTIC:()=>Di,DEFAULT_WIDGET_CONFIG:()=>Ft,PRESETS:()=>Pl,PRESET_FULLSCREEN:()=>Ll,PRESET_MINIMAL:()=>kl,PRESET_SHOP:()=>Ml,THEME_ZONES:()=>Gp,VERSION:()=>$o,accessibilityPlugin:()=>Tm,animationsPlugin:()=>Mm,applyThemeVariables:()=>no,attachHeaderToContainer:()=>Do,brandPlugin:()=>km,buildComposer:()=>ss,buildDefaultHeader:()=>zi,buildHeader:()=>Dr,buildHeaderWithLayout:()=>os,buildMinimalHeader:()=>Vi,collectEnrichedPageContext:()=>dm,componentRegistry:()=>Or,createActionManager:()=>na,createAgentExperience:()=>wi,createAskUserQuestionBubble:()=>Pu,createBestAvailableVoiceProvider:()=>Fa,createBubbleWithLayout:()=>fu,createCSATFeedback:()=>xi,createComboButton:()=>ti,createComponentMiddleware:()=>zu,createComponentStreamParser:()=>fi,createDefaultSanitizer:()=>Wi,createDemoCarousel:()=>Em,createDirectivePostprocessor:()=>Mp,createDropdownMenu:()=>ao,createFlexibleJsonStreamParser:()=>Wp,createIconButton:()=>jt,createImagePart:()=>Op,createJsonStreamParser:()=>Pa,createLabelButton:()=>Gs,createLocalStorageAdapter:()=>gi,createMarkdownProcessor:()=>Ws,createMarkdownProcessorFromConfig:()=>ko,createMessageActions:()=>Xi,createNPSFeedback:()=>vi,createPlainTextParser:()=>ka,createPlugin:()=>Im,createRegexJsonParser:()=>La,createStandardBubble:()=>as,createTextPart:()=>Bs,createTheme:()=>ns,createThemeObserver:()=>qa,createToggleGroup:()=>Qs,createTypingIndicator:()=>No,createVoiceProvider:()=>Ho,createWidgetHostLayout:()=>ra,createXmlParser:()=>Ia,default:()=>kh,defaultActionHandlers:()=>Oo,defaultJsonActionParser:()=>ta,defaultParseRules:()=>Al,detectColorScheme:()=>Os,directivePostprocessor:()=>kp,ensureAskUserQuestionSheet:()=>ps,escapeHtml:()=>Lo,extractComponentDirectiveFromMessage:()=>bi,fileToImagePart:()=>$p,formatEnrichedContext:()=>pm,generateAssistantMessageId:()=>Wo,generateCodeSnippet:()=>bm,generateMessageId:()=>Hp,generateStableSelector:()=>Sl,generateUserMessageId:()=>Zo,getActiveTheme:()=>rs,getColorScheme:()=>Oi,getDisplayText:()=>Dp,getHeaderLayout:()=>Ji,getImageParts:()=>Fp,getPreset:()=>Rm,hasComponentDirective:()=>yi,hasImages:()=>Np,headerLayouts:()=>ni,highContrastPlugin:()=>Pm,initAgentWidget:()=>xl,isAskUserQuestionMessage:()=>Nr,isComponentDirectiveType:()=>qu,isDockedMountMode:()=>nn,isVoiceSupported:()=>Ns,listRegisteredStreamAnimations:()=>iu,markdownPostprocessor:()=>Ii,mergeWithDefaults:()=>_a,normalizeContent:()=>Bp,parseAskUserQuestionPayload:()=>Fr,pluginRegistry:()=>ea,reducedMotionPlugin:()=>Lm,registerStreamAnimationPlugin:()=>su,removeAskUserQuestionSheet:()=>co,renderComponentDirective:()=>hi,renderLoadingIndicatorWithFallback:()=>Qi,renderLucideIcon:()=>ge,resolveDockConfig:()=>Xn,resolveSanitizer:()=>Xo,resolveTokens:()=>ja,themeToCssVariables:()=>Ua,unregisterStreamAnimationPlugin:()=>au,validateImageFile:()=>_p,validateTheme:()=>Fi});module.exports=_m(Lh);var Sp=require("marked"),jm=e=>{if(e)return e},Ws=e=>{var o,s;let n=e==null?void 0:e.markedOptions,t=new Sp.Marked({gfm:(o=n==null?void 0:n.gfm)!=null?o:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=jm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},ko=e=>e?Ws({markedOptions:e.options,renderer:e.renderer}):Ws(),Um=Ws(),Ii=e=>Um(e),Lo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ep=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ap=e=>`%%FORM_PLACEHOLDER_${e}%%`,Tp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Ap(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Ap(n.length);return n.push({token:s,type:o}),s}),t},Mp=e=>{let n=ko(e);return t=>{let r=[],o=Tp(t,r),s=n(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Ep(i)}"></div>`;s=s.replace(d,u)}),s}},kp=e=>{let n=[],t=Tp(e,n),r=Ii(t);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Ep(s)}"></div>`;r=r.replace(a,d)}),r};var Lp=$m(require("dompurify"),1),qm={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"]},zm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wi=()=>{let e=(0,Lp.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:")&&!zm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,qm)},Xo=e=>e===!1?null:typeof e=="function"?e:Wi();var Hr=require("partial-json"),Sa=e=>e.replace(/\\n/g,`
1
+ "use strict";var Hm=Object.create;var Aa=Object.defineProperty;var Bm=Object.getOwnPropertyDescriptor;var Dm=Object.getOwnPropertyNames;var Nm=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var Om=(e,n)=>{for(var t in n)Aa(e,t,{get:n[t],enumerable:!0})},wp=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Dm(n))!Fm.call(e,o)&&o!==t&&Aa(e,o,{get:()=>n[o],enumerable:!(r=Bm(n,o))||r.enumerable});return e};var $m=(e,n,t)=>(t=e!=null?Hm(Nm(e)):{},wp(n||!e||!e.__esModule?Aa(t,"default",{value:e,enumerable:!0}):t,e)),_m=e=>wp(Aa({},"__esModule",{value:!0}),e);var Lh={};Om(Lh,{ASK_USER_QUESTION_TOOL_NAME:()=>tl,AgentWidgetClient:()=>Io,AgentWidgetSession:()=>es,AttachmentManager:()=>Bo,DEFAULT_COMPONENTS:()=>Ni,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>$a,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Un,DEFAULT_PALETTE:()=>Bi,DEFAULT_SEMANTIC:()=>Di,DEFAULT_WIDGET_CONFIG:()=>Ft,PRESETS:()=>Pl,PRESET_FULLSCREEN:()=>Ll,PRESET_MINIMAL:()=>kl,PRESET_SHOP:()=>Ml,THEME_ZONES:()=>Gp,VERSION:()=>$o,accessibilityPlugin:()=>Tm,animationsPlugin:()=>Mm,applyThemeVariables:()=>no,attachHeaderToContainer:()=>Do,brandPlugin:()=>km,buildComposer:()=>ss,buildDefaultHeader:()=>zi,buildHeader:()=>Dr,buildHeaderWithLayout:()=>os,buildMinimalHeader:()=>Vi,collectEnrichedPageContext:()=>dm,componentRegistry:()=>Or,createActionManager:()=>na,createAgentExperience:()=>wi,createAskUserQuestionBubble:()=>Pu,createBestAvailableVoiceProvider:()=>Fa,createBubbleWithLayout:()=>fu,createCSATFeedback:()=>xi,createComboButton:()=>ti,createComponentMiddleware:()=>zu,createComponentStreamParser:()=>fi,createDefaultSanitizer:()=>Wi,createDemoCarousel:()=>Em,createDirectivePostprocessor:()=>Mp,createDropdownMenu:()=>ao,createFlexibleJsonStreamParser:()=>Wp,createIconButton:()=>jt,createImagePart:()=>Op,createJsonStreamParser:()=>Pa,createLabelButton:()=>Gs,createLocalStorageAdapter:()=>gi,createMarkdownProcessor:()=>Ws,createMarkdownProcessorFromConfig:()=>ko,createMessageActions:()=>Xi,createNPSFeedback:()=>vi,createPlainTextParser:()=>ka,createPlugin:()=>Im,createRegexJsonParser:()=>La,createStandardBubble:()=>as,createTextPart:()=>Bs,createTheme:()=>ns,createThemeObserver:()=>qa,createToggleGroup:()=>Qs,createTypingIndicator:()=>No,createVoiceProvider:()=>Ho,createWidgetHostLayout:()=>ra,createXmlParser:()=>Ia,default:()=>kh,defaultActionHandlers:()=>Oo,defaultJsonActionParser:()=>ta,defaultParseRules:()=>Al,detectColorScheme:()=>Os,directivePostprocessor:()=>kp,ensureAskUserQuestionSheet:()=>ps,escapeHtml:()=>Lo,extractComponentDirectiveFromMessage:()=>bi,fileToImagePart:()=>$p,formatEnrichedContext:()=>pm,generateAssistantMessageId:()=>Wo,generateCodeSnippet:()=>bm,generateMessageId:()=>Hp,generateStableSelector:()=>Sl,generateUserMessageId:()=>Zo,getActiveTheme:()=>rs,getColorScheme:()=>Oi,getDisplayText:()=>Dp,getHeaderLayout:()=>Ji,getImageParts:()=>Fp,getPreset:()=>Rm,hasComponentDirective:()=>yi,hasImages:()=>Np,headerLayouts:()=>ni,highContrastPlugin:()=>Pm,initAgentWidget:()=>xl,isAskUserQuestionMessage:()=>Nr,isComponentDirectiveType:()=>qu,isDockedMountMode:()=>nn,isVoiceSupported:()=>Ns,listRegisteredStreamAnimations:()=>iu,markdownPostprocessor:()=>Ii,mergeWithDefaults:()=>_a,normalizeContent:()=>Bp,parseAskUserQuestionPayload:()=>Fr,pluginRegistry:()=>ea,reducedMotionPlugin:()=>Lm,registerStreamAnimationPlugin:()=>su,removeAskUserQuestionSheet:()=>co,renderComponentDirective:()=>hi,renderLoadingIndicatorWithFallback:()=>Qi,renderLucideIcon:()=>me,resolveDockConfig:()=>Xn,resolveSanitizer:()=>Xo,resolveTokens:()=>ja,themeToCssVariables:()=>Ua,unregisterStreamAnimationPlugin:()=>au,validateImageFile:()=>_p,validateTheme:()=>Fi});module.exports=_m(Lh);var Sp=require("marked"),jm=e=>{if(e)return e},Ws=e=>{var o,s;let n=e==null?void 0:e.markedOptions,t=new Sp.Marked({gfm:(o=n==null?void 0:n.gfm)!=null?o:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=jm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},ko=e=>e?Ws({markedOptions:e.options,renderer:e.renderer}):Ws(),Um=Ws(),Ii=e=>Um(e),Lo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ep=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ap=e=>`%%FORM_PLACEHOLDER_${e}%%`,Tp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Ap(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Ap(n.length);return n.push({token:s,type:o}),s}),t},Mp=e=>{let n=ko(e);return t=>{let r=[],o=Tp(t,r),s=n(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Ep(i)}"></div>`;s=s.replace(d,u)}),s}},kp=e=>{let n=[],t=Tp(e,n),r=Ii(t);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Ep(s)}"></div>`;r=r.replace(a,d)}),r};var Lp=$m(require("dompurify"),1),qm={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"]},zm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wi=()=>{let e=(0,Lp.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:")&&!zm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,qm)},Xo=e=>e===!1?null:typeof e=="function"?e:Wi();var Hr=require("partial-json"),Sa=e=>e.replace(/\\n/g,`
2
2
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Yo=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)}},Vm=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Pp=e=>e.status==="complete"?Vm(e):e.status==="pending"?"Waiting":"",Jm=e=>{var o,s,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Ip=e=>e.status==="complete"?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`},Hs=e=>{var t,r,o;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Ea(n)},Ta=e=>{var t,r,o;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Ea(n)},Ri=(e,n,t)=>{var s;if(!n)return t;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Hs(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Ma=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Rs(r,t.slice(s,a.index),[]),a[1]!==void 0?Rs(r,a[1],["bold"]):a[2]!==void 0?Rs(r,a[2],["italic"]):a[3]!==void 0&&Rs(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Rs(r,t.slice(s),[]),r},Rs=(e,n,t)=>{let r=n.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:t}),o<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},Km=()=>{let e=null,n=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(e=s),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},ka=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},La=()=>{var n;let e=Km();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 o=(0,Hr.parse)(t,Hr.STR|Hr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Sa(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Sa(o.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Wp=e=>{let n=null,t=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Sa(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Sa(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=t)return n!==null?{text:n,raw:s}:null;try{let i=(0,Hr.parse)(s,Hr.STR|Hr.OBJ),d=o(i);d!==null&&(n=d)}catch{}return t=s.length,{text:n||"",raw:s}},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 s,a,i;let r=(i=(s=t==null?void 0:t.seq)!=null?s: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 o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.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 Gm="https://api.runtype.com/v1/dispatch",Ra="https://api.runtype.com";function Qm(e){var s,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let o=n.indexOf("/");if(o>0){let i=(a=(s=n.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var 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 Xm(e){switch(e){case"json":return Pa;case"regex-json":return La;case"xml":return Ia;default:return ka}}var Rp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Ym(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 o=Rp(t);if(!Rp(r))return e;if(!o||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,o;this.apiUrl=(t=n.apiUrl)!=null?t:Gm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Xm(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],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 s,a;let n=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ra}/v1/client/feedback`}async sendFeedback(n){var s,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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),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 o,s,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,(s=(o=this.config).onSessionExpired)==null||s.call(o);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 o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ra}/v1/agents/${n.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var i,d;let s=`${((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(s,{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(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}return r}async buildPayload(n){let r={messages:n.slice().filter(Hi).sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...r},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return r}async handleCustomSSEEvent(n,t,r,o,s,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:s(),...u!==void 0&&{partId:u}};return r.current=p,o(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,o(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,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var Jt,Cr,pr,Ue;let o=n.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=q=>{let we=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,Be=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,De=q.tools?q.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...q,reasoning:we,toolCall:Be,tools:De}},p=q=>{t({type:"message",message:u(q)})},f=null,g=null,w={current:null},x={current:null},M=!1,S=new Map,L=new Map,D=new Map,N=new Map,P={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},O=(q,we,Be="")=>`${q}::${we}::${Be}`,_=(q,we)=>`${q}::${we}::`,U=(q,we,Be,De)=>{let _e=O(q,we,Be),ct=D.get(_e);if(ct)return ct;let tt=Be?`-${Be}`:"",wt={id:`nested-${q}-${we}${tt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:De,parentToolId:q,parentStepId:we}};return D.set(_e,wt),p(wt),wt},R=q=>{if(q==null)return null;try{return String(q)}catch{return null}},$=q=>{var we,Be,De,_e,ct;return R((ct=(_e=(De=(Be=(we=q.stepId)!=null?we:q.step_id)!=null?Be:q.step)!=null?De:q.parentId)!=null?_e:q.flowStepId)!=null?ct:q.flow_step_id)},J=q=>{var we,Be,De,_e,ct,tt,wt;return R((wt=(tt=(ct=(_e=(De=(Be=(we=q.callId)!=null?we:q.call_id)!=null?Be:q.requestId)!=null?De:q.request_id)!=null?_e:q.toolCallId)!=null?ct:q.tool_call_id)!=null?tt:q.stepId)!=null?wt:q.step_id)},se=r,Ie=!1,Le=()=>{if(f)return f;let q;return!Ie&&se?(q=se,Ie=!0):se&&x.current?q=`${se}_${x.current}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:q,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Qe=(q,we)=>{P.lastId=we,q&&P.byStep.set(q,we)},pe=(q,we)=>{var ct;let Be=(ct=q.reasoningId)!=null?ct:q.id,De=$(q);if(Be){let tt=String(Be);return Qe(De,tt),tt}if(De){let tt=P.byStep.get(De);if(tt)return P.lastId=tt,tt}if(P.lastId&&!we)return P.lastId;if(!we)return null;let _e=`reason-${l()}`;return Qe(De,_e),_e},ue=q=>{let we=S.get(q);if(we)return we;let Be={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:q,status:"streaming",chunks:[]}};return S.set(q,Be),p(Be),Be},ke=(q,we)=>{E.lastId=we,q&&E.byCall.set(q,we)},je=new Set,te=new Map,Se=new Set,X=new Map,ie=q=>{if(!q)return!1;let we=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return we==="emit_artifact_markdown"||we==="emit_artifact_component"},He=(q,we)=>{var ct;let Be=(ct=q.toolId)!=null?ct:q.id,De=J(q);if(Be){let tt=String(Be);return ke(De,tt),tt}if(De){let tt=E.byCall.get(De);if(tt)return E.lastId=tt,tt}if(E.lastId&&!we)return E.lastId;if(!we)return null;let _e=`tool-${l()}`;return ke(De,_e),_e},de=q=>{let we=L.get(q);if(we)return we;let Be={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:q,status:"pending"}};return L.set(q,Be),p(Be),Be},Re=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let we=Number(q);if(!Number.isNaN(we)&&Number.isFinite(we))return we;let Be=Date.parse(q);if(!Number.isNaN(Be))return Be}return Date.now()},et=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},K=new Map,ae=new Map,Oe=new Map,G=new Map,V=null,ve=(q,we,Be)=>{var wt;let De=Oe.get(q);De||(De=[],Oe.set(q,De));let _e=0,ct=De.length;for(;_e<ct;){let qt=_e+ct>>>1;De[qt].seq<we?_e=qt+1:ct=qt}((wt=De[_e])==null?void 0:wt.seq)===we?De[_e]={seq:we,text:Be}:De.splice(_e,0,{seq:we,text:Be});let tt="";for(let qt=0;qt<De.length;qt++)tt+=De[qt].text;return tt},$e=(q,we)=>{let Be=et(we),De=ae.get(q.id),_e=Ym(De,Be);q.rawContent=_e;let ct=K.get(q.id),tt=fe=>{var ze;let dt=(ze=q.content)!=null?ze:"";fe.trim()!==""&&(dt.trim().length===0||fe.startsWith(dt)||fe.trimStart().startsWith(dt.trim()))&&(q.content=fe)},wt=()=>{var fe;if(ct){let dt=(fe=ct.close)==null?void 0:fe.call(ct);dt instanceof Promise&&dt.catch(()=>{})}K.delete(q.id),ae.delete(q.id),q.streaming=!1,p(q)};if(!ct){tt(Be),wt();return}let qt=Po(_e);if(qt!==null&&qt.trim()!==""){tt(qt),wt();return}let I=fe=>{var Wt;let dt=typeof fe=="string"?fe:(Wt=fe==null?void 0:fe.text)!=null?Wt:null;if(dt!==null&&dt.trim()!=="")return dt;let ze=ct.getExtractedText();return ze!==null&&ze.trim()!==""?ze:Be},he;try{he=ct.processChunk(_e)}catch{tt(Be),wt();return}if(he instanceof Promise){he.then(fe=>{tt(I(fe)),wt()}).catch(()=>{tt(Be),wt()});return}tt(I(he)),wt()},re=[],Ee=!1,xe,Bt=()=>{Ee||(Ee=!0,queueMicrotask(()=>{Ee=!1,xe()}))},Pe=new Wa((q,we)=>{re.push({payloadType:q,payload:we}),Bt()}),ne=null,an=new Map,Ot=(Jt=this.config.iterationDisplay)!=null?Jt:"separate";for(xe=()=>{var q,we,Be,De,_e,ct,tt,wt,qt,I,he,fe,dt,ze,Wt,ln,At,xt,kt,ut,Kt,wr,qn,_r,Ct,ur,mr,Ar,er,gt,mo,gr,go,En,_o,jr,Sr,bt,Wn,Rn,yn,Lt,zn,Vn,Hn,Ur,Er,qr,Bn,Rt,bn,Jn,zr,Tr,Vr,fr,Dn,tr,ft,Gt,Qt,Nn,Jr,Kn,nr,Fn,j,ce,On,rr,hr,fs,or,sr,ar,Mr,fo,oa,hs,sa,jo,mt,ys,Gn,Tn,aa,ia,Uo,kr,la,ho,bs,Lr,xs,Kr,Gr,ca,da,Pi,yo,Qr,pa,vs,Xr,ua,Cs,Yr,ws,ma,Pr,ga,Zr,Ht,qo,zo,As,yr,fa,Ss,Es,Ts,Ms,xn,$n,Ir,nt,ks,bo,ir,ha,Vo,Jo,xo,eo,ya,ba,lr,vo;for(let Ko=0;Ko<re.length;Ko++){let Je=re[Ko].payloadType,C=re[Ko].payload;if(Je==="reason_start"){let H=(q=pe(C,!0))!=null?q:`reason-${l()}`,A=ue(H);A.reasoning=(we=A.reasoning)!=null?we:{id:H,status:"streaming",chunks:[]},A.reasoning.startedAt=(De=A.reasoning.startedAt)!=null?De:Re((Be=C.startedAt)!=null?Be:C.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",p(A)}else if(Je==="reason_delta"||Je==="reason_chunk"){let H=(ct=(_e=pe(C,!1))!=null?_e:pe(C,!0))!=null?ct:`reason-${l()}`,A=ue(H);A.reasoning=(tt=A.reasoning)!=null?tt:{id:H,status:"streaming",chunks:[]},A.reasoning.startedAt=(qt=A.reasoning.startedAt)!=null?qt:Re((wt=C.startedAt)!=null?wt:C.timestamp);let Q=(fe=(he=(I=C.reasoningText)!=null?I:C.text)!=null?he:C.delta)!=null?fe:"";if(Q&&C.hidden!==!0){let oe=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(oe!==void 0){let Y=ve(H,oe,String(Q));A.reasoning.chunks=[Y]}else A.reasoning.chunks.push(String(Q))}if(A.reasoning.status=C.done?"complete":"streaming",C.done){A.reasoning.completedAt=Re((dt=C.completedAt)!=null?dt:C.timestamp);let oe=(ze=A.reasoning.startedAt)!=null?ze:Date.now();A.reasoning.durationMs=Math.max(0,((Wt=A.reasoning.completedAt)!=null?Wt:Date.now())-oe)}A.streaming=A.reasoning.status!=="complete",p(A)}else if(Je==="reason_complete"){let H=(At=(ln=pe(C,!1))!=null?ln:pe(C,!0))!=null?At:`reason-${l()}`,A=S.get(H);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=Re((xt=C.completedAt)!=null?xt:C.timestamp);let oe=(kt=A.reasoning.startedAt)!=null?kt:Date.now();A.reasoning.durationMs=Math.max(0,((ut=A.reasoning.completedAt)!=null?ut:Date.now())-oe),A.streaming=!1,p(A)}let Q=$(C);Q&&P.byStep.delete(Q)}else if(Je==="tool_start"){let H=(Kt=He(C,!0))!=null?Kt:`tool-${l()}`,A=(wr=C.toolName)!=null?wr:C.name;if(ie(A)){je.add(H);continue}let Q=de(H),oe=(qn=Q.toolCall)!=null?qn:{id:H,status:"pending"};oe.name=A!=null?A:oe.name,oe.status="running",C.args!==void 0?oe.args=C.args:C.parameters!==void 0&&(oe.args=C.parameters),oe.startedAt=(Ct=oe.startedAt)!=null?Ct:Re((_r=C.startedAt)!=null?_r:C.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Q.toolCall=oe,Q.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(Q.agentMetadata={executionId:(ur=Y==null?void 0:Y.executionId)!=null?ur:C.executionId,iteration:(mr=Y==null?void 0:Y.iteration)!=null?mr:C.iteration}),p(Q)}else if(Je==="tool_chunk"||Je==="tool_delta"){let H=(er=(Ar=He(C,!1))!=null?Ar:He(C,!0))!=null?er:`tool-${l()}`;if(je.has(H))continue;let A=de(H),Q=(gt=A.toolCall)!=null?gt:{id:H,status:"running"};Q.startedAt=(gr=Q.startedAt)!=null?gr:Re((mo=C.startedAt)!=null?mo:C.timestamp);let oe=(_o=(En=(go=C.text)!=null?go:C.delta)!=null?En:C.message)!=null?_o:"";oe&&(Q.chunks=(jr=Q.chunks)!=null?jr:[],Q.chunks.push(String(oe))),Q.status="running",A.toolCall=Q,A.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(A.agentMetadata=(Wn=A.agentMetadata)!=null?Wn:{executionId:(Sr=Y==null?void 0:Y.executionId)!=null?Sr:C.executionId,iteration:(bt=Y==null?void 0:Y.iteration)!=null?bt:C.iteration}),p(A)}else if(Je==="tool_complete"){let H=(yn=(Rn=He(C,!1))!=null?Rn:He(C,!0))!=null?yn:`tool-${l()}`;if(je.has(H)){je.delete(H);continue}let A=de(H),Q=(Lt=A.toolCall)!=null?Lt:{id:H,status:"running"};Q.status="complete",C.result!==void 0&&(Q.result=C.result),typeof C.duration=="number"&&(Q.duration=C.duration),Q.completedAt=Re((zn=C.completedAt)!=null?zn:C.timestamp);let oe=(Vn=C.duration)!=null?Vn:C.executionTime;if(typeof oe=="number")Q.durationMs=oe;else{let Ne=(Hn=Q.startedAt)!=null?Hn:Date.now();Q.durationMs=Math.max(0,((Ur=Q.completedAt)!=null?Ur:Date.now())-Ne)}A.toolCall=Q,A.streaming=!1;let Y=C.agentContext;(Y||C.executionId)&&(A.agentMetadata=(Bn=A.agentMetadata)!=null?Bn:{executionId:(Er=Y==null?void 0:Y.executionId)!=null?Er:C.executionId,iteration:(qr=Y==null?void 0:Y.iteration)!=null?qr:C.iteration}),p(A);let Ke=J(C);Ke&&E.byCall.delete(Ke)}else if(Je==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let H=(Rt=C.toolId)!=null?Rt:`local-${l()}`,A=de(H),Q=(bn=A.toolCall)!=null?bn:{id:H,status:"pending"};Q.name=C.toolName,Q.args=C.parameters,Q.status="complete",Q.chunks=(Jn=Q.chunks)!=null?Jn:[],Q.startedAt=(Tr=Q.startedAt)!=null?Tr:Re((zr=C.startedAt)!=null?zr:C.timestamp),Q.completedAt=(Vr=Q.completedAt)!=null?Vr:Q.startedAt,A.toolCall=Q,A.streaming=!1,A.agentMetadata={...A.agentMetadata,executionId:(Dn=C.executionId)!=null?Dn:(fr=A.agentMetadata)==null?void 0:fr.executionId,awaitingLocalTool:!0},p(A)}else if(Je==="text_start"){if((tr=C.toolContext)!=null&&tr.toolId)continue;let H=C.partId;if(H!==void 0&&x.current!==null&&H!==x.current){let A=f;A&&(A.streaming=!1,p(A),V=A,f=null,M=!0)}H!==void 0&&(x.current=H)}else if(Je==="text_end"){if((ft=C.toolContext)!=null&&ft.toolId)continue;let H=f;H&&(H.streaming=!1,p(H),V=H,f=null,M=!0)}else if(Je==="step_chunk"||Je==="step_delta"){let H=C.stepType,A=C.executionType;if(H==="tool"||A==="context")continue;let Q=C.toolContext;if(Q!=null&&Q.toolId){let Ne=String((Qt=(Gt=C.id)!=null?Gt:Q.stepId)!=null?Qt:`step-${l()}`),rt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",Ye=`${Q.toolId}::${Ne}`,Et=N.get(Ye);if(rt!==""&&Et!==void 0&&Et!==""&&Et!==rt){let ht=D.get(O(Q.toolId,Ne,Et));ht&&ht.streaming!==!1&&(ht.streaming=!1,p(ht))}rt!==""&&N.set(Ye,rt);let Pt=U(Q.toolId,Ne,rt,Q.executionId),Zt=(nr=(Kn=(Jr=(Nn=C.text)!=null?Nn:C.delta)!=null?Jr:C.content)!=null?Kn:C.chunk)!=null?nr:"";Zt&&(Pt.content+=String(Zt),Pt.streaming=!0,p(Pt)),C.isComplete&&(Pt.streaming=!1,p(Pt));continue}let oe=C.partId;if(oe!==void 0&&x.current!==null&&oe!==x.current){let Ne=f;Ne&&(Ne.streaming=!1,p(Ne),V=Ne,f=null,M=!0)}oe!==void 0&&(x.current=oe);let Y=oe!==void 0&&(Fn=G.get(oe))!=null?Fn:Le();oe!==void 0&&(Y.partId||(Y.partId=oe),G.set(oe,Y));let Ke=(rr=(On=(ce=(j=C.text)!=null?j:C.delta)!=null?ce:C.content)!=null?On:C.chunk)!=null?rr:"";if(Ke){let Ne=typeof C.seq=="number"?C.seq:void 0,rt=oe!=null?oe:Y.id,Ye=Ne!==void 0?ve(rt,Ne,String(Ke)):((hr=ae.get(Y.id))!=null?hr:"")+Ke;Y.rawContent=Ye,K.has(Y.id)||K.set(Y.id,this.createStreamParser());let Et=K.get(Y.id),Pt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(Pt&&ae.set(Y.id,Ye),Et.__isPlainTextParser===!0){Y.content=Ne!==void 0?Ye:Y.content+Ke,ae.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y);continue}let ht=Et.processChunk(Ye);if(ht instanceof Promise)ht.then(Tt=>{var un;let rn=typeof Tt=="string"?Tt:(un=Tt==null?void 0:Tt.text)!=null?un:null;if(rn!==null&&rn.trim()!=="")Y.content=rn,p(Y);else if(!Pt&&!Ye.trim().startsWith("<")){let cn=f,$t=cn&&cn.id===Y.id?cn:Y;$t.id===Y.id&&($t.content=Ne!==void 0?Ye:$t.content+Ke,ae.delete($t.id),K.delete($t.id),$t.rawContent=void 0,p($t))}}).catch(()=>{Y.content=Ne!==void 0?Ye:Y.content+Ke,ae.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y)});else{let Tt=typeof ht=="string"?ht:(fs=ht==null?void 0:ht.text)!=null?fs:null;Tt!==null&&Tt.trim()!==""?(Y.content=Tt,p(Y)):!Pt&&!Ye.trim().startsWith("<")&&(Y.content=Ne!==void 0?Ye:Y.content+Ke,ae.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y))}}if(C.isComplete){let Ne=(sr=(or=C.result)==null?void 0:or.response)!=null?sr:Y.content;if(Ne){let rt=ae.get(Y.id),Ye=rt!=null?rt:et(Ne);Y.rawContent=Ye;let Et=K.get(Y.id),Pt=null,Zt=!1;if(Et&&(Pt=Et.getExtractedText(),Pt===null&&(Pt=Po(Ye)),Pt===null)){let ht=Et.processChunk(Ye);ht instanceof Promise?(Zt=!0,ht.then(Tt=>{var un;let rn=typeof Tt=="string"?Tt:(un=Tt==null?void 0:Tt.text)!=null?un:null;if(rn!==null){let cn=f;cn&&cn.id===Y.id&&(cn.content=rn,cn.streaming=!1,K.delete(cn.id),ae.delete(cn.id),p(cn))}})):Pt=typeof ht=="string"?ht:(ar=ht==null?void 0:ht.text)!=null?ar:null}if(!Zt){Pt!==null&&Pt.trim()!==""?Y.content=Pt:ae.has(Y.id)||(Y.content=et(Ne));let ht=K.get(Y.id);if(ht){let Tt=(Mr=ht.close)==null?void 0:Mr.call(ht);Tt instanceof Promise&&Tt.catch(()=>{}),K.delete(Y.id)}ae.delete(Y.id),Y.streaming=!1,p(Y)}}}}else if(Je==="step_complete"){let H=C.stepType,A=C.executionType;if(H==="tool"||A==="context")continue;let Q=C.toolContext;if(Q!=null&&Q.toolId){let Ne=String((oa=(fo=C.id)!=null?fo:Q.stepId)!=null?oa:"");if(Ne){let rt=_(Q.toolId,Ne);for(let[Ye,Et]of D)Ye.startsWith(rt)&&Et.streaming!==!1&&(Et.streaming=!1,p(Et));N.delete(`${Q.toolId}::${Ne}`)}continue}let oe=C.stopReason;if(M){if(f!==null){let Ye=f;oe&&(Ye.stopReason=oe),K.delete(Ye.id),ae.delete(Ye.id),Ye.streaming!==!1&&(Ye.streaming=!1,p(Ye))}let Ne=(hs=C.result)==null?void 0:hs.response,rt=V;rt&&(oe&&(rt.stopReason=oe),Ne!=null?$e(rt,Ne):(K.delete(rt.id),ae.delete(rt.id))),V=null;continue}let Y=(sa=C.result)==null?void 0:sa.response,Ke=Le();if(oe&&(Ke.stopReason=oe),Y!=null){let Ne=K.get(Ke.id),rt=!1,Ye=!1;if(Ne){let Et=Ne.getExtractedText(),Pt=ae.get(Ke.id),Zt=Pt!=null?Pt:et(Y);if(Ke.rawContent=Zt,Et!==null&&Et.trim()!=="")Ke.content=Et,rt=!0;else{let ht=Po(Zt);if(ht!==null)Ke.content=ht,rt=!0;else{let Tt=Ne.processChunk(Zt);if(Tt instanceof Promise)Ye=!0,Tt.then(rn=>{var cn;let un=typeof rn=="string"?rn:(cn=rn==null?void 0:rn.text)!=null?cn:null;if(un!==null&&un.trim()!==""){let $t=f;$t&&$t.id===Ke.id&&($t.content=un,$t.streaming=!1,K.delete($t.id),ae.delete($t.id),p($t))}else{let $t=Ne.getExtractedText(),Mn=f;Mn&&Mn.id===Ke.id&&($t!==null&&$t.trim()!==""?Mn.content=$t:ae.has(Mn.id)||(Mn.content=et(Y)),Mn.streaming=!1,K.delete(Mn.id),ae.delete(Mn.id),p(Mn))}});else{let rn=typeof Tt=="string"?Tt:(jo=Tt==null?void 0:Tt.text)!=null?jo:null;if(rn!==null&&rn.trim()!=="")Ke.content=rn,rt=!0;else{let un=Ne.getExtractedText();un!==null&&un.trim()!==""&&(Ke.content=un,rt=!0)}}}}}if(!Ye){if(!Ke.rawContent){let Et=ae.get(Ke.id);Ke.rawContent=Et!=null?Et:et(Y)}if(!rt&&!ae.has(Ke.id)&&(Ke.content=et(Y)),Ne){let Et=(mt=Ne.close)==null?void 0:mt.call(Ne);Et instanceof Promise&&Et.catch(()=>{})}K.delete(Ke.id),ae.delete(Ke.id),Ke.streaming=!1,p(Ke)}}else K.delete(Ke.id),ae.delete(Ke.id),Ke.streaming=!1,p(Ke)}else if(Je==="flow_complete"){let H=(ys=C.result)==null?void 0:ys.response;if(M){if(f!==null){let A=f;K.delete(A.id),ae.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}}else if(H!=null){let A=Le(),Q=ae.get(A.id),oe=Q!=null?Q:et(H);A.rawContent=oe;let Y=et(H),Ke=K.get(A.id);if(Ke){let Ye=Po(oe);if(Ye!==null)Y=Ye;else{let Et=Ke.processChunk(oe);Et instanceof Promise&&Et.then(Zt=>{var Tt;let ht=typeof Zt=="string"?Zt:(Tt=Zt==null?void 0:Zt.text)!=null?Tt:null;ht!==null&&(A.content=ht,A.streaming=!1,p(A))});let Pt=Ke.getExtractedText();Pt!==null&&(Y=Pt)}}K.delete(A.id),ae.delete(A.id);let Ne=Y!==A.content,rt=A.streaming!==!1;Ne&&(A.content=Y),A.streaming=!1,(Ne||rt)&&p(A)}else if(f!==null){let A=f;K.delete(A.id),ae.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}t({type:"status",status:"idle"})}else if(Je==="agent_start")ne={executionId:C.executionId,agentId:(Gn=C.agentId)!=null?Gn:"virtual",agentName:(Tn=C.agentName)!=null?Tn:"",status:"running",currentIteration:0,maxTurns:(aa=C.maxTurns)!=null?aa:1,startedAt:Re(C.startedAt)};else if(Je==="agent_iteration_start"){if(ne&&(ne.currentIteration=C.iteration),Ot==="separate"&&C.iteration>1){let H=f;H&&(H.streaming=!1,p(H),an.set(C.iteration-1,H),f=null)}}else if(Je==="agent_turn_start")g=null;else if(Je==="agent_turn_delta"){if(C.contentType==="text"){let H=Le();H.content+=(ia=C.delta)!=null?ia:"",H.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:ne==null?void 0:ne.agentName},g=H,p(H)}else if(C.contentType==="thinking"){let H=(Uo=C.turnId)!=null?Uo:`agent-think-${C.iteration}`,A=ue(H);A.reasoning=(kr=A.reasoning)!=null?kr:{id:H,status:"streaming",chunks:[]},A.reasoning.chunks.push((la=C.delta)!=null?la:""),A.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(A)}else if(C.contentType==="tool_input"){let H=(ho=C.toolCallId)!=null?ho:E.lastId;if(H){let A=L.get(H);A!=null&&A.toolCall&&(A.toolCall.chunks=(bs=A.toolCall.chunks)!=null?bs:[],A.toolCall.chunks.push((Lr=C.delta)!=null?Lr:""),p(A))}}}else if(Je==="agent_turn_complete"){let H=C.turnId;if(H){let oe=S.get(H);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=Re(C.completedAt);let Y=(xs=oe.reasoning.startedAt)!=null?xs:Date.now();oe.reasoning.durationMs=Math.max(0,((Kr=oe.reasoning.completedAt)!=null?Kr:Date.now())-Y),oe.streaming=!1,p(oe)}}let A=C.stopReason,Q=f!=null?f:g;if(A&&Q!==null){let oe=C.turnId;(!oe||((Gr=Q.agentMetadata)==null?void 0:Gr.turnId)===oe)&&(Q.stopReason=A,p(Q))}}else if(Je==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let H=(ca=C.toolCallId)!=null?ca:`agent-tool-${l()}`;ke(J(C),H);let A=de(H),Q=(da=A.toolCall)!=null?da:{id:H,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};Q.name=(yo=(Pi=C.toolName)!=null?Pi:C.name)!=null?yo:Q.name,Q.status="running",C.parameters!==void 0&&(Q.args=C.parameters),Q.startedAt=Re((Qr=C.startedAt)!=null?Qr:C.timestamp),A.toolCall=Q,A.streaming=!0,A.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(A)}else if(Je==="agent_tool_delta"){let H=(pa=C.toolCallId)!=null?pa:E.lastId;if(H){let A=(vs=L.get(H))!=null?vs:de(H);A.toolCall&&(A.toolCall.chunks=(Xr=A.toolCall.chunks)!=null?Xr:[],A.toolCall.chunks.push((ua=C.delta)!=null?ua:""),A.toolCall.status="running",A.streaming=!0,p(A))}}else if(Je==="agent_tool_complete"){let H=(Cs=C.toolCallId)!=null?Cs:E.lastId;if(H){let A=(Yr=L.get(H))!=null?Yr:de(H);if(A.toolCall){A.toolCall.status="complete",C.result!==void 0&&(A.toolCall.result=C.result),typeof C.executionTime=="number"&&(A.toolCall.durationMs=C.executionTime),A.toolCall.completedAt=Re((ws=C.completedAt)!=null?ws:C.timestamp),A.streaming=!1,p(A);let Q=J(C);Q&&E.byCall.delete(Q)}}}else if(Je==="agent_media"){let H=Array.isArray(C.media)?C.media:[],A=[];for(let Q of H){if(!Q||typeof Q!="object")continue;let oe=Q,Y=typeof oe.type=="string"?oe.type:void 0,Ke=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Ne=null,rt="";if(Y==="media"){let Ye=typeof oe.data=="string"?oe.data:void 0;if(!Ye)continue;rt=Ke.length>0?Ke:"application/octet-stream",Ne=`data:${rt};base64,${Ye}`}else if(Y==="image-url"){let Ye=typeof oe.url=="string"?oe.url:void 0;if(!Ye)continue;rt=Ke,Ne=Ye}else if(Y==="file-url"){let Ye=typeof oe.url=="string"?oe.url:void 0;if(!Ye)continue;rt=Ke,Ne=Ye}else continue;if(Ne)if(Y==="image-url"||rt.startsWith("image/"))A.push({type:"image",image:Ne,...rt?{mimeType:rt}:{}});else if(rt.startsWith("audio/"))A.push({type:"audio",audio:Ne,mimeType:rt});else if(rt.startsWith("video/"))A.push({type:"video",video:Ne,mimeType:rt});else{let Ye=rt||"application/octet-stream";A.push({type:"file",data:Ne,mimeType:Ye,filename:Qm(Ye)})}}if(A.length>0){let Q=l(),oe=C.toolCallId,Ke={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Q}`:String(Q)}`,role:"assistant",content:"",contentParts:A,createdAt:new Date().toISOString(),streaming:!1,sequence:Q,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(Ke);let Ne=f;Ne&&(Ne.streaming=!1,p(Ne)),f=null,w.current=null}}else if(Je!=="agent_iteration_complete"){if(Je==="agent_reflection"||Je==="agent_reflect"){let H=`agent-reflection-${C.executionId}-${C.iteration}`,A={id:H,role:"assistant",content:(ma=C.reflection)!=null?ma:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:H,status:"complete",chunks:[(Pr=C.reflection)!=null?Pr:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(A)}else if(Je==="agent_complete"){ne&&(ne.status=C.success?"complete":"error",ne.completedAt=Re(C.completedAt),ne.stopReason=C.stopReason);let H=f;H&&(H.streaming=!1,p(H)),t({type:"status",status:"idle"})}else if(Je==="agent_error"){let H=typeof C.error=="string"?C.error:(Zr=(ga=C.error)==null?void 0:ga.message)!=null?Zr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",H):t({type:"error",error:new Error(H)})}else if(Je!=="agent_ping"){if(Je==="agent_approval_start"){let H=(Ht=C.approvalId)!=null?Ht:`approval-${l()}`,A={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:H,status:"pending",agentId:(qo=ne==null?void 0:ne.agentId)!=null?qo:"virtual",executionId:(As=(zo=C.executionId)!=null?zo:ne==null?void 0:ne.executionId)!=null?As:"",toolName:(yr=C.toolName)!=null?yr:"",toolType:C.toolType,description:(Ss=C.description)!=null?Ss:`Execute ${(fa=C.toolName)!=null?fa:"tool"}`,parameters:C.parameters}};p(A)}else if(Je==="step_await"&&C.awaitReason==="approval_required"){let H=(Es=C.approvalId)!=null?Es:`approval-${l()}`,A={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:H,status:"pending",agentId:(Ts=ne==null?void 0:ne.agentId)!=null?Ts:"virtual",executionId:(xn=(Ms=C.executionId)!=null?Ms:ne==null?void 0:ne.executionId)!=null?xn:"",toolName:($n=C.toolName)!=null?$n:"",toolType:C.toolType,description:(nt=C.description)!=null?nt:`Execute ${(Ir=C.toolName)!=null?Ir:"tool"}`,parameters:C.parameters}};p(A)}else if(Je==="agent_approval_complete"){let H=C.approvalId;if(H){let Q={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:H,status:(ks=C.decision)!=null?ks:"approved",agentId:(bo=ne==null?void 0:ne.agentId)!=null?bo:"virtual",executionId:(ha=(ir=C.executionId)!=null?ir:ne==null?void 0:ne.executionId)!=null?ha:"",toolName:(Vo=C.toolName)!=null?Vo:"",description:(Jo=C.description)!=null?Jo:"",resolvedAt:Date.now()}};p(Q)}}else if(Je==="artifact_start"||Je==="artifact_delta"||Je==="artifact_update"||Je==="artifact_complete"){if(Je==="artifact_start"){let H=C.artifactType,A=String(C.id),Q=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:A,artifactType:H,title:Q,component:typeof C.component=="string"?C.component:void 0}),X.set(A,{markdown:"",title:Q}),!Se.has(A)){Se.add(A);let oe={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:Q,artifactType:H,status:"streaming"}})};te.set(A,oe),p(oe)}}else if(Je==="artifact_delta"){let H=String(C.id),A=typeof C.delta=="string"?C.delta:String((xo=C.delta)!=null?xo:"");t({type:"artifact_delta",id:H,artDelta:A});let Q=X.get(H);Q&&(Q.markdown+=A)}else if(Je==="artifact_update"){let H=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:H,component:typeof C.component=="string"?C.component:void 0})}else if(Je==="artifact_complete"){let H=String(C.id);t({type:"artifact_complete",id:H});let A=te.get(H);if(A){A.streaming=!1;try{let Q=JSON.parse((eo=A.rawContent)!=null?eo:"{}");if(Q.props){Q.props.status="complete";let oe=X.get(H);oe!=null&&oe.markdown&&(Q.props.markdown=oe.markdown)}A.rawContent=JSON.stringify(Q)}catch{}X.delete(H),p(A),te.delete(H)}}}else if(Je==="transcript_insert"){let H=C.message;if(!H||typeof H!="object")continue;let A=String((ya=H.id)!=null?ya:`msg-${l()}`),Q=H.role,Y={id:A,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:l()};if(p(Y),Y.rawContent)try{let Ke=JSON.parse(Y.rawContent),Ne=(ba=Ke==null?void 0:Ke.props)==null?void 0:ba.artifactId;typeof Ne=="string"&&Se.add(Ne)}catch{}f=null,w.current=null,K.delete(A),ae.delete(A)}else if(Je==="error"||Je==="step_error"||Je==="dispatch_error"||Je==="flow_error"){let H=null;if(C.error instanceof Error)H=C.error;else if(Je==="dispatch_error"){let A=(lr=C.message)!=null?lr:C.error;A!=null&&A!==""&&(H=new Error(String(A)))}else if(Je==="step_error"||Je==="flow_error"){let A=C.error;typeof A=="string"&&A!==""?H=new Error(A):A!=null&&typeof A=="object"&&"message"in A&&(H=new Error(String((vo=A.message)!=null?vo:A)))}else Je==="error"&&C.error!=null&&C.error!==""&&(H=new Error(String(C.error)));if(H){t({type:"error",error:H});let A=f;A&&A.streaming&&(A.streaming=!1,p(A)),t({type:"status",status:"idle"})}}}}}re.length=0};;){let{done:q,value:we}=await o.read();if(q)break;a+=s.decode(we,{stream:!0});let Be=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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(e=s),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},ka=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},La=()=>{var n;let e=Km();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 o=(0,Hr.parse)(t,Hr.STR|Hr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Sa(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Sa(o.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Wp=e=>{let n=null,t=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Sa(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Sa(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=t)return n!==null?{text:n,raw:s}:null;try{let i=(0,Hr.parse)(s,Hr.STR|Hr.OBJ),d=o(i);d!==null&&(n=d)}catch{}return t=s.length,{text:n||"",raw:s}},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 s,a,i;let r=(i=(s=t==null?void 0:t.seq)!=null?s: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 o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.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 Gm="https://api.runtype.com/v1/dispatch",Ra="https://api.runtype.com";function Qm(e){var s,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let o=n.indexOf("/");if(o>0){let i=(a=(s=n.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var 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 Xm(e){switch(e){case"json":return Pa;case"regex-json":return La;case"xml":return Ia;default:return ka}}var Rp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Ym(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 o=Rp(t);if(!Rp(r))return e;if(!o||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,o;this.apiUrl=(t=n.apiUrl)!=null?t:Gm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Xm(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],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 s,a;let n=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ra}/v1/client/feedback`}async sendFeedback(n){var s,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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),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 o,s,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,(s=(o=this.config).onSessionExpired)==null||s.call(o);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,k;return{id:g.id,role:g.role,content:(k=(x=(w=g.contentParts)!=null?w:g.llmContent)!=null?x:g.rawContent)!=null?k: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 o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ra}/v1/agents/${n.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var i,d;let s=`${((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(s,{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(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}return r}async buildPayload(n){let r={messages:n.slice().filter(Hi).sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...r},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return r}async handleCustomSSEEvent(n,t,r,o,s,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:s(),...u!==void 0&&{partId:u}};return r.current=p,o(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,o(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,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var Jt,Cr,pr,je;let o=n.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=q=>{let we=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,Be=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,De=q.tools?q.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...q,reasoning:we,toolCall:Be,tools:De}},p=q=>{t({type:"message",message:u(q)})},f=null,g=null,w={current:null},x={current:null},k=!1,S=new Map,L=new Map,D=new Map,N=new Map,P={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},O=(q,we,Be="")=>`${q}::${we}::${Be}`,_=(q,we)=>`${q}::${we}::`,U=(q,we,Be,De)=>{let _e=O(q,we,Be),ct=D.get(_e);if(ct)return ct;let tt=Be?`-${Be}`:"",wt={id:`nested-${q}-${we}${tt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:De,parentToolId:q,parentStepId:we}};return D.set(_e,wt),p(wt),wt},R=q=>{if(q==null)return null;try{return String(q)}catch{return null}},$=q=>{var we,Be,De,_e,ct;return R((ct=(_e=(De=(Be=(we=q.stepId)!=null?we:q.step_id)!=null?Be:q.step)!=null?De:q.parentId)!=null?_e:q.flowStepId)!=null?ct:q.flow_step_id)},J=q=>{var we,Be,De,_e,ct,tt,wt;return R((wt=(tt=(ct=(_e=(De=(Be=(we=q.callId)!=null?we:q.call_id)!=null?Be:q.requestId)!=null?De:q.request_id)!=null?_e:q.toolCallId)!=null?ct:q.tool_call_id)!=null?tt:q.stepId)!=null?wt:q.step_id)},se=r,Ie=!1,ke=()=>{if(f)return f;let q;return!Ie&&se?(q=se,Ie=!0):se&&x.current?q=`${se}_${x.current}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:q,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Qe=(q,we)=>{P.lastId=we,q&&P.byStep.set(q,we)},ge=(q,we)=>{var ct;let Be=(ct=q.reasoningId)!=null?ct:q.id,De=$(q);if(Be){let tt=String(Be);return Qe(De,tt),tt}if(De){let tt=P.byStep.get(De);if(tt)return P.lastId=tt,tt}if(P.lastId&&!we)return P.lastId;if(!we)return null;let _e=`reason-${l()}`;return Qe(De,_e),_e},pe=q=>{let we=S.get(q);if(we)return we;let Be={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:q,status:"streaming",chunks:[]}};return S.set(q,Be),p(Be),Be},Le=(q,we)=>{E.lastId=we,q&&E.byCall.set(q,we)},qe=new Set,te=new Map,Se=new Set,X=new Map,ie=q=>{if(!q)return!1;let we=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return we==="emit_artifact_markdown"||we==="emit_artifact_component"},He=(q,we)=>{var ct;let Be=(ct=q.toolId)!=null?ct:q.id,De=J(q);if(Be){let tt=String(Be);return Le(De,tt),tt}if(De){let tt=E.byCall.get(De);if(tt)return E.lastId=tt,tt}if(E.lastId&&!we)return E.lastId;if(!we)return null;let _e=`tool-${l()}`;return Le(De,_e),_e},de=q=>{let we=L.get(q);if(we)return we;let Be={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:q,status:"pending"}};return L.set(q,Be),p(Be),Be},Re=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let we=Number(q);if(!Number.isNaN(we)&&Number.isFinite(we))return we;let Be=Date.parse(q);if(!Number.isNaN(Be))return Be}return Date.now()},et=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},K=new Map,ae=new Map,Oe=new Map,G=new Map,V=null,ve=(q,we,Be)=>{var wt;let De=Oe.get(q);De||(De=[],Oe.set(q,De));let _e=0,ct=De.length;for(;_e<ct;){let qt=_e+ct>>>1;De[qt].seq<we?_e=qt+1:ct=qt}((wt=De[_e])==null?void 0:wt.seq)===we?De[_e]={seq:we,text:Be}:De.splice(_e,0,{seq:we,text:Be});let tt="";for(let qt=0;qt<De.length;qt++)tt+=De[qt].text;return tt},$e=(q,we)=>{let Be=et(we),De=ae.get(q.id),_e=Ym(De,Be);q.rawContent=_e;let ct=K.get(q.id),tt=fe=>{var ze;let dt=(ze=q.content)!=null?ze:"";fe.trim()!==""&&(dt.trim().length===0||fe.startsWith(dt)||fe.trimStart().startsWith(dt.trim()))&&(q.content=fe)},wt=()=>{var fe;if(ct){let dt=(fe=ct.close)==null?void 0:fe.call(ct);dt instanceof Promise&&dt.catch(()=>{})}K.delete(q.id),ae.delete(q.id),q.streaming=!1,p(q)};if(!ct){tt(Be),wt();return}let qt=Po(_e);if(qt!==null&&qt.trim()!==""){tt(qt),wt();return}let I=fe=>{var Wt;let dt=typeof fe=="string"?fe:(Wt=fe==null?void 0:fe.text)!=null?Wt:null;if(dt!==null&&dt.trim()!=="")return dt;let ze=ct.getExtractedText();return ze!==null&&ze.trim()!==""?ze:Be},he;try{he=ct.processChunk(_e)}catch{tt(Be),wt();return}if(he instanceof Promise){he.then(fe=>{tt(I(fe)),wt()}).catch(()=>{tt(Be),wt()});return}tt(I(he)),wt()},re=[],Ee=!1,xe,Bt=()=>{Ee||(Ee=!0,queueMicrotask(()=>{Ee=!1,xe()}))},Pe=new Wa((q,we)=>{re.push({payloadType:q,payload:we}),Bt()}),ne=null,an=new Map,Ot=(Jt=this.config.iterationDisplay)!=null?Jt:"separate";for(xe=()=>{var q,we,Be,De,_e,ct,tt,wt,qt,I,he,fe,dt,ze,Wt,ln,At,xt,kt,ut,Kt,wr,qn,_r,Ct,ur,mr,Ar,er,gt,mo,gr,go,En,_o,jr,Sr,bt,Wn,Rn,yn,Lt,zn,Vn,Hn,Ur,Er,qr,Bn,Rt,bn,Jn,zr,Tr,Vr,fr,Dn,tr,ft,Gt,Qt,Nn,Jr,Kn,nr,Fn,j,ce,On,rr,hr,fs,or,sr,ar,Mr,fo,oa,hs,sa,jo,mt,ys,Gn,Tn,aa,ia,Uo,kr,la,ho,bs,Lr,xs,Kr,Gr,ca,da,Pi,yo,Qr,pa,vs,Xr,ua,Cs,Yr,ws,ma,Pr,ga,Zr,Ht,qo,zo,As,yr,fa,Ss,Es,Ts,Ms,xn,$n,Ir,nt,ks,bo,ir,ha,Vo,Jo,xo,eo,ya,ba,lr,vo;for(let Ko=0;Ko<re.length;Ko++){let Je=re[Ko].payloadType,C=re[Ko].payload;if(Je==="reason_start"){let H=(q=ge(C,!0))!=null?q:`reason-${l()}`,A=pe(H);A.reasoning=(we=A.reasoning)!=null?we:{id:H,status:"streaming",chunks:[]},A.reasoning.startedAt=(De=A.reasoning.startedAt)!=null?De:Re((Be=C.startedAt)!=null?Be:C.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",p(A)}else if(Je==="reason_delta"||Je==="reason_chunk"){let H=(ct=(_e=ge(C,!1))!=null?_e:ge(C,!0))!=null?ct:`reason-${l()}`,A=pe(H);A.reasoning=(tt=A.reasoning)!=null?tt:{id:H,status:"streaming",chunks:[]},A.reasoning.startedAt=(qt=A.reasoning.startedAt)!=null?qt:Re((wt=C.startedAt)!=null?wt:C.timestamp);let Q=(fe=(he=(I=C.reasoningText)!=null?I:C.text)!=null?he:C.delta)!=null?fe:"";if(Q&&C.hidden!==!0){let oe=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(oe!==void 0){let Y=ve(H,oe,String(Q));A.reasoning.chunks=[Y]}else A.reasoning.chunks.push(String(Q))}if(A.reasoning.status=C.done?"complete":"streaming",C.done){A.reasoning.completedAt=Re((dt=C.completedAt)!=null?dt:C.timestamp);let oe=(ze=A.reasoning.startedAt)!=null?ze:Date.now();A.reasoning.durationMs=Math.max(0,((Wt=A.reasoning.completedAt)!=null?Wt:Date.now())-oe)}A.streaming=A.reasoning.status!=="complete",p(A)}else if(Je==="reason_complete"){let H=(At=(ln=ge(C,!1))!=null?ln:ge(C,!0))!=null?At:`reason-${l()}`,A=S.get(H);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=Re((xt=C.completedAt)!=null?xt:C.timestamp);let oe=(kt=A.reasoning.startedAt)!=null?kt:Date.now();A.reasoning.durationMs=Math.max(0,((ut=A.reasoning.completedAt)!=null?ut:Date.now())-oe),A.streaming=!1,p(A)}let Q=$(C);Q&&P.byStep.delete(Q)}else if(Je==="tool_start"){let H=(Kt=He(C,!0))!=null?Kt:`tool-${l()}`,A=(wr=C.toolName)!=null?wr:C.name;if(ie(A)){qe.add(H);continue}let Q=de(H),oe=(qn=Q.toolCall)!=null?qn:{id:H,status:"pending"};oe.name=A!=null?A:oe.name,oe.status="running",C.args!==void 0?oe.args=C.args:C.parameters!==void 0&&(oe.args=C.parameters),oe.startedAt=(Ct=oe.startedAt)!=null?Ct:Re((_r=C.startedAt)!=null?_r:C.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Q.toolCall=oe,Q.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(Q.agentMetadata={executionId:(ur=Y==null?void 0:Y.executionId)!=null?ur:C.executionId,iteration:(mr=Y==null?void 0:Y.iteration)!=null?mr:C.iteration}),p(Q)}else if(Je==="tool_chunk"||Je==="tool_delta"){let H=(er=(Ar=He(C,!1))!=null?Ar:He(C,!0))!=null?er:`tool-${l()}`;if(qe.has(H))continue;let A=de(H),Q=(gt=A.toolCall)!=null?gt:{id:H,status:"running"};Q.startedAt=(gr=Q.startedAt)!=null?gr:Re((mo=C.startedAt)!=null?mo:C.timestamp);let oe=(_o=(En=(go=C.text)!=null?go:C.delta)!=null?En:C.message)!=null?_o:"";oe&&(Q.chunks=(jr=Q.chunks)!=null?jr:[],Q.chunks.push(String(oe))),Q.status="running",A.toolCall=Q,A.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(A.agentMetadata=(Wn=A.agentMetadata)!=null?Wn:{executionId:(Sr=Y==null?void 0:Y.executionId)!=null?Sr:C.executionId,iteration:(bt=Y==null?void 0:Y.iteration)!=null?bt:C.iteration}),p(A)}else if(Je==="tool_complete"){let H=(yn=(Rn=He(C,!1))!=null?Rn:He(C,!0))!=null?yn:`tool-${l()}`;if(qe.has(H)){qe.delete(H);continue}let A=de(H),Q=(Lt=A.toolCall)!=null?Lt:{id:H,status:"running"};Q.status="complete",C.result!==void 0&&(Q.result=C.result),typeof C.duration=="number"&&(Q.duration=C.duration),Q.completedAt=Re((zn=C.completedAt)!=null?zn:C.timestamp);let oe=(Vn=C.duration)!=null?Vn:C.executionTime;if(typeof oe=="number")Q.durationMs=oe;else{let Ne=(Hn=Q.startedAt)!=null?Hn:Date.now();Q.durationMs=Math.max(0,((Ur=Q.completedAt)!=null?Ur:Date.now())-Ne)}A.toolCall=Q,A.streaming=!1;let Y=C.agentContext;(Y||C.executionId)&&(A.agentMetadata=(Bn=A.agentMetadata)!=null?Bn:{executionId:(Er=Y==null?void 0:Y.executionId)!=null?Er:C.executionId,iteration:(qr=Y==null?void 0:Y.iteration)!=null?qr:C.iteration}),p(A);let Ke=J(C);Ke&&E.byCall.delete(Ke)}else if(Je==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let H=(Rt=C.toolId)!=null?Rt:`local-${l()}`,A=de(H),Q=(bn=A.toolCall)!=null?bn:{id:H,status:"pending"};Q.name=C.toolName,Q.args=C.parameters,Q.status="complete",Q.chunks=(Jn=Q.chunks)!=null?Jn:[],Q.startedAt=(Tr=Q.startedAt)!=null?Tr:Re((zr=C.startedAt)!=null?zr:C.timestamp),Q.completedAt=(Vr=Q.completedAt)!=null?Vr:Q.startedAt,A.toolCall=Q,A.streaming=!1,A.agentMetadata={...A.agentMetadata,executionId:(Dn=C.executionId)!=null?Dn:(fr=A.agentMetadata)==null?void 0:fr.executionId,awaitingLocalTool:!0},p(A)}else if(Je==="text_start"){if((tr=C.toolContext)!=null&&tr.toolId)continue;let H=C.partId;if(H!==void 0&&x.current!==null&&H!==x.current){let A=f;A&&(A.streaming=!1,p(A),V=A,f=null,k=!0)}H!==void 0&&(x.current=H)}else if(Je==="text_end"){if((ft=C.toolContext)!=null&&ft.toolId)continue;let H=f;H&&(H.streaming=!1,p(H),V=H,f=null,k=!0)}else if(Je==="step_chunk"||Je==="step_delta"){let H=C.stepType,A=C.executionType;if(H==="tool"||A==="context")continue;let Q=C.toolContext;if(Q!=null&&Q.toolId){let Ne=String((Qt=(Gt=C.id)!=null?Gt:Q.stepId)!=null?Qt:`step-${l()}`),rt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",Ye=`${Q.toolId}::${Ne}`,Et=N.get(Ye);if(rt!==""&&Et!==void 0&&Et!==""&&Et!==rt){let ht=D.get(O(Q.toolId,Ne,Et));ht&&ht.streaming!==!1&&(ht.streaming=!1,p(ht))}rt!==""&&N.set(Ye,rt);let Pt=U(Q.toolId,Ne,rt,Q.executionId),Zt=(nr=(Kn=(Jr=(Nn=C.text)!=null?Nn:C.delta)!=null?Jr:C.content)!=null?Kn:C.chunk)!=null?nr:"";Zt&&(Pt.content+=String(Zt),Pt.streaming=!0,p(Pt)),C.isComplete&&(Pt.streaming=!1,p(Pt));continue}let oe=C.partId;if(oe!==void 0&&x.current!==null&&oe!==x.current){let Ne=f;Ne&&(Ne.streaming=!1,p(Ne),V=Ne,f=null,k=!0)}oe!==void 0&&(x.current=oe);let Y=oe!==void 0&&(Fn=G.get(oe))!=null?Fn:ke();oe!==void 0&&(Y.partId||(Y.partId=oe),G.set(oe,Y));let Ke=(rr=(On=(ce=(j=C.text)!=null?j:C.delta)!=null?ce:C.content)!=null?On:C.chunk)!=null?rr:"";if(Ke){let Ne=typeof C.seq=="number"?C.seq:void 0,rt=oe!=null?oe:Y.id,Ye=Ne!==void 0?ve(rt,Ne,String(Ke)):((hr=ae.get(Y.id))!=null?hr:"")+Ke;Y.rawContent=Ye,K.has(Y.id)||K.set(Y.id,this.createStreamParser());let Et=K.get(Y.id),Pt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(Pt&&ae.set(Y.id,Ye),Et.__isPlainTextParser===!0){Y.content=Ne!==void 0?Ye:Y.content+Ke,ae.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y);continue}let ht=Et.processChunk(Ye);if(ht instanceof Promise)ht.then(Tt=>{var un;let rn=typeof Tt=="string"?Tt:(un=Tt==null?void 0:Tt.text)!=null?un:null;if(rn!==null&&rn.trim()!=="")Y.content=rn,p(Y);else if(!Pt&&!Ye.trim().startsWith("<")){let cn=f,$t=cn&&cn.id===Y.id?cn:Y;$t.id===Y.id&&($t.content=Ne!==void 0?Ye:$t.content+Ke,ae.delete($t.id),K.delete($t.id),$t.rawContent=void 0,p($t))}}).catch(()=>{Y.content=Ne!==void 0?Ye:Y.content+Ke,ae.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y)});else{let Tt=typeof ht=="string"?ht:(fs=ht==null?void 0:ht.text)!=null?fs:null;Tt!==null&&Tt.trim()!==""?(Y.content=Tt,p(Y)):!Pt&&!Ye.trim().startsWith("<")&&(Y.content=Ne!==void 0?Ye:Y.content+Ke,ae.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y))}}if(C.isComplete){let Ne=(sr=(or=C.result)==null?void 0:or.response)!=null?sr:Y.content;if(Ne){let rt=ae.get(Y.id),Ye=rt!=null?rt:et(Ne);Y.rawContent=Ye;let Et=K.get(Y.id),Pt=null,Zt=!1;if(Et&&(Pt=Et.getExtractedText(),Pt===null&&(Pt=Po(Ye)),Pt===null)){let ht=Et.processChunk(Ye);ht instanceof Promise?(Zt=!0,ht.then(Tt=>{var un;let rn=typeof Tt=="string"?Tt:(un=Tt==null?void 0:Tt.text)!=null?un:null;if(rn!==null){let cn=f;cn&&cn.id===Y.id&&(cn.content=rn,cn.streaming=!1,K.delete(cn.id),ae.delete(cn.id),p(cn))}})):Pt=typeof ht=="string"?ht:(ar=ht==null?void 0:ht.text)!=null?ar:null}if(!Zt){Pt!==null&&Pt.trim()!==""?Y.content=Pt:ae.has(Y.id)||(Y.content=et(Ne));let ht=K.get(Y.id);if(ht){let Tt=(Mr=ht.close)==null?void 0:Mr.call(ht);Tt instanceof Promise&&Tt.catch(()=>{}),K.delete(Y.id)}ae.delete(Y.id),Y.streaming=!1,p(Y)}}}}else if(Je==="step_complete"){let H=C.stepType,A=C.executionType;if(H==="tool"||A==="context")continue;let Q=C.toolContext;if(Q!=null&&Q.toolId){let Ne=String((oa=(fo=C.id)!=null?fo:Q.stepId)!=null?oa:"");if(Ne){let rt=_(Q.toolId,Ne);for(let[Ye,Et]of D)Ye.startsWith(rt)&&Et.streaming!==!1&&(Et.streaming=!1,p(Et));N.delete(`${Q.toolId}::${Ne}`)}continue}let oe=C.stopReason;if(k){if(f!==null){let Ye=f;oe&&(Ye.stopReason=oe),K.delete(Ye.id),ae.delete(Ye.id),Ye.streaming!==!1&&(Ye.streaming=!1,p(Ye))}let Ne=(hs=C.result)==null?void 0:hs.response,rt=V;rt&&(oe&&(rt.stopReason=oe),Ne!=null?$e(rt,Ne):(K.delete(rt.id),ae.delete(rt.id))),V=null;continue}let Y=(sa=C.result)==null?void 0:sa.response,Ke=ke();if(oe&&(Ke.stopReason=oe),Y!=null){let Ne=K.get(Ke.id),rt=!1,Ye=!1;if(Ne){let Et=Ne.getExtractedText(),Pt=ae.get(Ke.id),Zt=Pt!=null?Pt:et(Y);if(Ke.rawContent=Zt,Et!==null&&Et.trim()!=="")Ke.content=Et,rt=!0;else{let ht=Po(Zt);if(ht!==null)Ke.content=ht,rt=!0;else{let Tt=Ne.processChunk(Zt);if(Tt instanceof Promise)Ye=!0,Tt.then(rn=>{var cn;let un=typeof rn=="string"?rn:(cn=rn==null?void 0:rn.text)!=null?cn:null;if(un!==null&&un.trim()!==""){let $t=f;$t&&$t.id===Ke.id&&($t.content=un,$t.streaming=!1,K.delete($t.id),ae.delete($t.id),p($t))}else{let $t=Ne.getExtractedText(),Mn=f;Mn&&Mn.id===Ke.id&&($t!==null&&$t.trim()!==""?Mn.content=$t:ae.has(Mn.id)||(Mn.content=et(Y)),Mn.streaming=!1,K.delete(Mn.id),ae.delete(Mn.id),p(Mn))}});else{let rn=typeof Tt=="string"?Tt:(jo=Tt==null?void 0:Tt.text)!=null?jo:null;if(rn!==null&&rn.trim()!=="")Ke.content=rn,rt=!0;else{let un=Ne.getExtractedText();un!==null&&un.trim()!==""&&(Ke.content=un,rt=!0)}}}}}if(!Ye){if(!Ke.rawContent){let Et=ae.get(Ke.id);Ke.rawContent=Et!=null?Et:et(Y)}if(!rt&&!ae.has(Ke.id)&&(Ke.content=et(Y)),Ne){let Et=(mt=Ne.close)==null?void 0:mt.call(Ne);Et instanceof Promise&&Et.catch(()=>{})}K.delete(Ke.id),ae.delete(Ke.id),Ke.streaming=!1,p(Ke)}}else K.delete(Ke.id),ae.delete(Ke.id),Ke.streaming=!1,p(Ke)}else if(Je==="flow_complete"){let H=(ys=C.result)==null?void 0:ys.response;if(k){if(f!==null){let A=f;K.delete(A.id),ae.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}}else if(H!=null){let A=ke(),Q=ae.get(A.id),oe=Q!=null?Q:et(H);A.rawContent=oe;let Y=et(H),Ke=K.get(A.id);if(Ke){let Ye=Po(oe);if(Ye!==null)Y=Ye;else{let Et=Ke.processChunk(oe);Et instanceof Promise&&Et.then(Zt=>{var Tt;let ht=typeof Zt=="string"?Zt:(Tt=Zt==null?void 0:Zt.text)!=null?Tt:null;ht!==null&&(A.content=ht,A.streaming=!1,p(A))});let Pt=Ke.getExtractedText();Pt!==null&&(Y=Pt)}}K.delete(A.id),ae.delete(A.id);let Ne=Y!==A.content,rt=A.streaming!==!1;Ne&&(A.content=Y),A.streaming=!1,(Ne||rt)&&p(A)}else if(f!==null){let A=f;K.delete(A.id),ae.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}t({type:"status",status:"idle"})}else if(Je==="agent_start")ne={executionId:C.executionId,agentId:(Gn=C.agentId)!=null?Gn:"virtual",agentName:(Tn=C.agentName)!=null?Tn:"",status:"running",currentIteration:0,maxTurns:(aa=C.maxTurns)!=null?aa:1,startedAt:Re(C.startedAt)};else if(Je==="agent_iteration_start"){if(ne&&(ne.currentIteration=C.iteration),Ot==="separate"&&C.iteration>1){let H=f;H&&(H.streaming=!1,p(H),an.set(C.iteration-1,H),f=null)}}else if(Je==="agent_turn_start")g=null;else if(Je==="agent_turn_delta"){if(C.contentType==="text"){let H=ke();H.content+=(ia=C.delta)!=null?ia:"",H.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:ne==null?void 0:ne.agentName},g=H,p(H)}else if(C.contentType==="thinking"){let H=(Uo=C.turnId)!=null?Uo:`agent-think-${C.iteration}`,A=pe(H);A.reasoning=(kr=A.reasoning)!=null?kr:{id:H,status:"streaming",chunks:[]},A.reasoning.chunks.push((la=C.delta)!=null?la:""),A.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(A)}else if(C.contentType==="tool_input"){let H=(ho=C.toolCallId)!=null?ho:E.lastId;if(H){let A=L.get(H);A!=null&&A.toolCall&&(A.toolCall.chunks=(bs=A.toolCall.chunks)!=null?bs:[],A.toolCall.chunks.push((Lr=C.delta)!=null?Lr:""),p(A))}}}else if(Je==="agent_turn_complete"){let H=C.turnId;if(H){let oe=S.get(H);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=Re(C.completedAt);let Y=(xs=oe.reasoning.startedAt)!=null?xs:Date.now();oe.reasoning.durationMs=Math.max(0,((Kr=oe.reasoning.completedAt)!=null?Kr:Date.now())-Y),oe.streaming=!1,p(oe)}}let A=C.stopReason,Q=f!=null?f:g;if(A&&Q!==null){let oe=C.turnId;(!oe||((Gr=Q.agentMetadata)==null?void 0:Gr.turnId)===oe)&&(Q.stopReason=A,p(Q))}}else if(Je==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let H=(ca=C.toolCallId)!=null?ca:`agent-tool-${l()}`;Le(J(C),H);let A=de(H),Q=(da=A.toolCall)!=null?da:{id:H,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};Q.name=(yo=(Pi=C.toolName)!=null?Pi:C.name)!=null?yo:Q.name,Q.status="running",C.parameters!==void 0&&(Q.args=C.parameters),Q.startedAt=Re((Qr=C.startedAt)!=null?Qr:C.timestamp),A.toolCall=Q,A.streaming=!0,A.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(A)}else if(Je==="agent_tool_delta"){let H=(pa=C.toolCallId)!=null?pa:E.lastId;if(H){let A=(vs=L.get(H))!=null?vs:de(H);A.toolCall&&(A.toolCall.chunks=(Xr=A.toolCall.chunks)!=null?Xr:[],A.toolCall.chunks.push((ua=C.delta)!=null?ua:""),A.toolCall.status="running",A.streaming=!0,p(A))}}else if(Je==="agent_tool_complete"){let H=(Cs=C.toolCallId)!=null?Cs:E.lastId;if(H){let A=(Yr=L.get(H))!=null?Yr:de(H);if(A.toolCall){A.toolCall.status="complete",C.result!==void 0&&(A.toolCall.result=C.result),typeof C.executionTime=="number"&&(A.toolCall.durationMs=C.executionTime),A.toolCall.completedAt=Re((ws=C.completedAt)!=null?ws:C.timestamp),A.streaming=!1,p(A);let Q=J(C);Q&&E.byCall.delete(Q)}}}else if(Je==="agent_media"){let H=Array.isArray(C.media)?C.media:[],A=[];for(let Q of H){if(!Q||typeof Q!="object")continue;let oe=Q,Y=typeof oe.type=="string"?oe.type:void 0,Ke=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Ne=null,rt="";if(Y==="media"){let Ye=typeof oe.data=="string"?oe.data:void 0;if(!Ye)continue;rt=Ke.length>0?Ke:"application/octet-stream",Ne=`data:${rt};base64,${Ye}`}else if(Y==="image-url"){let Ye=typeof oe.url=="string"?oe.url:void 0;if(!Ye)continue;rt=Ke,Ne=Ye}else if(Y==="file-url"){let Ye=typeof oe.url=="string"?oe.url:void 0;if(!Ye)continue;rt=Ke,Ne=Ye}else continue;if(Ne)if(Y==="image-url"||rt.startsWith("image/"))A.push({type:"image",image:Ne,...rt?{mimeType:rt}:{}});else if(rt.startsWith("audio/"))A.push({type:"audio",audio:Ne,mimeType:rt});else if(rt.startsWith("video/"))A.push({type:"video",video:Ne,mimeType:rt});else{let Ye=rt||"application/octet-stream";A.push({type:"file",data:Ne,mimeType:Ye,filename:Qm(Ye)})}}if(A.length>0){let Q=l(),oe=C.toolCallId,Ke={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Q}`:String(Q)}`,role:"assistant",content:"",contentParts:A,createdAt:new Date().toISOString(),streaming:!1,sequence:Q,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(Ke);let Ne=f;Ne&&(Ne.streaming=!1,p(Ne)),f=null,w.current=null}}else if(Je!=="agent_iteration_complete"){if(Je==="agent_reflection"||Je==="agent_reflect"){let H=`agent-reflection-${C.executionId}-${C.iteration}`,A={id:H,role:"assistant",content:(ma=C.reflection)!=null?ma:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:H,status:"complete",chunks:[(Pr=C.reflection)!=null?Pr:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(A)}else if(Je==="agent_complete"){ne&&(ne.status=C.success?"complete":"error",ne.completedAt=Re(C.completedAt),ne.stopReason=C.stopReason);let H=f;H&&(H.streaming=!1,p(H)),t({type:"status",status:"idle"})}else if(Je==="agent_error"){let H=typeof C.error=="string"?C.error:(Zr=(ga=C.error)==null?void 0:ga.message)!=null?Zr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",H):t({type:"error",error:new Error(H)})}else if(Je!=="agent_ping"){if(Je==="agent_approval_start"){let H=(Ht=C.approvalId)!=null?Ht:`approval-${l()}`,A={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:H,status:"pending",agentId:(qo=ne==null?void 0:ne.agentId)!=null?qo:"virtual",executionId:(As=(zo=C.executionId)!=null?zo:ne==null?void 0:ne.executionId)!=null?As:"",toolName:(yr=C.toolName)!=null?yr:"",toolType:C.toolType,description:(Ss=C.description)!=null?Ss:`Execute ${(fa=C.toolName)!=null?fa:"tool"}`,parameters:C.parameters}};p(A)}else if(Je==="step_await"&&C.awaitReason==="approval_required"){let H=(Es=C.approvalId)!=null?Es:`approval-${l()}`,A={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:H,status:"pending",agentId:(Ts=ne==null?void 0:ne.agentId)!=null?Ts:"virtual",executionId:(xn=(Ms=C.executionId)!=null?Ms:ne==null?void 0:ne.executionId)!=null?xn:"",toolName:($n=C.toolName)!=null?$n:"",toolType:C.toolType,description:(nt=C.description)!=null?nt:`Execute ${(Ir=C.toolName)!=null?Ir:"tool"}`,parameters:C.parameters}};p(A)}else if(Je==="agent_approval_complete"){let H=C.approvalId;if(H){let Q={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:H,status:(ks=C.decision)!=null?ks:"approved",agentId:(bo=ne==null?void 0:ne.agentId)!=null?bo:"virtual",executionId:(ha=(ir=C.executionId)!=null?ir:ne==null?void 0:ne.executionId)!=null?ha:"",toolName:(Vo=C.toolName)!=null?Vo:"",description:(Jo=C.description)!=null?Jo:"",resolvedAt:Date.now()}};p(Q)}}else if(Je==="artifact_start"||Je==="artifact_delta"||Je==="artifact_update"||Je==="artifact_complete"){if(Je==="artifact_start"){let H=C.artifactType,A=String(C.id),Q=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:A,artifactType:H,title:Q,component:typeof C.component=="string"?C.component:void 0}),X.set(A,{markdown:"",title:Q}),!Se.has(A)){Se.add(A);let oe={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:Q,artifactType:H,status:"streaming"}})};te.set(A,oe),p(oe)}}else if(Je==="artifact_delta"){let H=String(C.id),A=typeof C.delta=="string"?C.delta:String((xo=C.delta)!=null?xo:"");t({type:"artifact_delta",id:H,artDelta:A});let Q=X.get(H);Q&&(Q.markdown+=A)}else if(Je==="artifact_update"){let H=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:H,component:typeof C.component=="string"?C.component:void 0})}else if(Je==="artifact_complete"){let H=String(C.id);t({type:"artifact_complete",id:H});let A=te.get(H);if(A){A.streaming=!1;try{let Q=JSON.parse((eo=A.rawContent)!=null?eo:"{}");if(Q.props){Q.props.status="complete";let oe=X.get(H);oe!=null&&oe.markdown&&(Q.props.markdown=oe.markdown)}A.rawContent=JSON.stringify(Q)}catch{}X.delete(H),p(A),te.delete(H)}}}else if(Je==="transcript_insert"){let H=C.message;if(!H||typeof H!="object")continue;let A=String((ya=H.id)!=null?ya:`msg-${l()}`),Q=H.role,Y={id:A,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:l()};if(p(Y),Y.rawContent)try{let Ke=JSON.parse(Y.rawContent),Ne=(ba=Ke==null?void 0:Ke.props)==null?void 0:ba.artifactId;typeof Ne=="string"&&Se.add(Ne)}catch{}f=null,w.current=null,K.delete(A),ae.delete(A)}else if(Je==="error"||Je==="step_error"||Je==="dispatch_error"||Je==="flow_error"){let H=null;if(C.error instanceof Error)H=C.error;else if(Je==="dispatch_error"){let A=(lr=C.message)!=null?lr:C.error;A!=null&&A!==""&&(H=new Error(String(A)))}else if(Je==="step_error"||Je==="flow_error"){let A=C.error;typeof A=="string"&&A!==""?H=new Error(A):A!=null&&typeof A=="object"&&"message"in A&&(H=new Error(String((vo=A.message)!=null?vo:A)))}else Je==="error"&&C.error!=null&&C.error!==""&&(H=new Error(String(C.error)));if(H){t({type:"error",error:H});let A=f;A&&A.streaming&&(A.streaming=!1,p(A)),t({type:"status",status:"idle"})}}}}}re.length=0};;){let{done:q,value:we}=await o.read();if(q)break;a+=s.decode(we,{stream:!0});let Be=a.split(`
5
5
 
6
6
  `);a=(Cr=Be.pop())!=null?Cr:"";for(let De of Be){let _e=De.split(`
7
- `),ct="message",tt="";for(let I of _e)I.startsWith("event:")?ct=I.replace("event:","").trim():I.startsWith("data:")&&(tt+=I.replace("data:","").trim());if(!tt)continue;let wt;try{wt=JSON.parse(tt)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let qt=ct!=="message"?ct:(pr=wt.type)!=null?pr:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,qt,wt),this.parseSSEEvent){w.current=f;let I=await this.handleCustomSSEEvent(wt,t,w,p,l,x);if(w.current&&w.current!==f&&(f=w.current),I)continue}Pe.push(qt,wt),xe()}}Pe.flushPending(),xe(),Pe.destroy()}};function Hp(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Zo(){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 Bp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Dp(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Np(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Fp(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function Op(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 $p(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function _p(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 jp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Zm=["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"],Br=[...jp,...Zm];function eg(e){return jp.includes(e)||e.startsWith("image/")}function Ba(e){return eg(e.type)}async function Up(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ba(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function qp(e,n=Br,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 tg(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function zp(e,n){let t=tg(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(),o=this.pcmToFloat32(t),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.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),o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=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,o,s){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<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):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 Ds=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 o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${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=S=>{w||(w=!0,clearTimeout(M),g(new Error(S)))},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",S=>{if(!S.wasClean&&!w){let L=S.code!==1006?` (code ${S.code})`:"";x("WebSocket connection failed"+L+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}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(o=>o({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(o=>o("speaking")),this.playAudio(n.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(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(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("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,o;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.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(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}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 s,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=(s=this.config)==null?void 0:s.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),o=this.getFormatFromMimeType(n.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];t(a)},o.onerror=r,o.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 o=n.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),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=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 Ds(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 Ns(e){try{return Fa(e),!0}catch{return!1}}var es=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,o,s,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:(o=n.message.agentMetadata.iteration)!=null?o: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,((s=this.agentExecution)==null?void 0:s.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,o;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Io(n);for(let s of(o=n.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,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 Ns((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,o;try{let s=n||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Ho(s);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"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(S=>S.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(s){console.error("Failed to setup voice:",s)}}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,o,s,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:((o=n.runtype)==null?void 0:o.clientToken)||"",host:(s=n.runtype)==null?void 0:s.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:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=n,g={id:a!=null?a:t==="user"?Zo():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,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(g),g}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:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:g}=r,x={id:d!=null?d:o==="user"?Zo():o==="assistant"?Wo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=n,l={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}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 o=Zo(),s=Wo(),a={id:o,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:s},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:s,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 o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.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=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(n,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,l,u,p;let r=`approval-${n.id}`,o={...n,status:t,resolvedAt:Date.now()},s={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):f=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),f){let g=null;if(f instanceof Response){if(!f.ok){let w=await f.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${f.status}`)}g=f.body}else f instanceof ReadableStream&&(g=f);g?await this.connectStream(g,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let g=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(o=>o.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(o=>o.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,S,L,D,N,P;let r=this.messages.find(E=>E.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(p=n.agentMetadata)==null?void 0:p.executionId,s=(f=n.toolCall)==null?void 0:f.name;if(!o||!s){(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 E=(x=n.toolCall)==null?void 0:x.args,O=Array.isArray(E==null?void 0:E.questions)?E.questions:[];if(O.length===1){let _=typeof((M=O[0])==null?void 0:M.question)=="string"?O[0].question:"";_&&(a={[_]:t})}}this.markAskUserQuestionResolved(n,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(L=n.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let E=typeof t=="string"?t:Object.entries(t).map(([O,_])=>`${O}: ${Array.isArray(_)?_.join(", "):_}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let E=a!=null?a:{};l.forEach((O,_)=>{let U=typeof(O==null?void 0:O.question)=="string"?O.question:"";if(!U)return;let R=E[U],$=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:$||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let E=await this.client.resumeFlow(o,{[s]:t});if(!E.ok){let O=await E.json().catch(()=>null);throw new Error((D=O==null?void 0:O.error)!=null?D:`Resume failed: ${E.status}`)}E.body?await this.connectStream(E.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(E){let O=E instanceof Error&&(E.name==="AbortError"||E.message.includes("aborted")||E.message.includes("abort"));this.setStreaming(!1),this.abortController=null,O||(P=(N=this.callbacks).onError)==null||P.call(N,E instanceof Error?E:new Error(String(E)))}}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 o;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(o=n.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var 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 o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...n.props},n.component&&(o.component=n.component));break}case"artifact_complete":{let o=this.artifacts.get(n.id);o&&(o.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 o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(n),s=r.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=t.pickVoice?t.pickVoice(s):e.pickBestVoice(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>r.speak(o),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 o of t){let s=n.find(a=>a.name===o);if(s)return s}return(r=n.find(o=>o.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(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var i;if(s!==r)return o;let a={...o,...t};return((i=o.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.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 o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(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"),ng={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 o=ng[e];return o?rg(o,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 rg(e,n,t,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),o.appendChild(d)}),o}var Oa={allowedTypes:Br,maxFileSize:10*1024*1024,maxFiles:4};function og(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sg(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,o;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Oa.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Oa.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o: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,o,s,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=qp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await Up(l),f=Ba(l)?URL.createObjectURL(l):null,g={id:og(),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 s,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 o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.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=sg(n.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=zp(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 o=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ge("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(o),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 Vp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fs(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];Vp(s)&&Vp(o)?t[r]=Fs(s,o):t[r]=o}return t}var Un="min(440px, calc(100vw - 24px))",$a="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Un,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 Jp(e,n){if(!(!e&&!n))return e?n?Fs(e,n):e:n}function _a(e){var n,t,r,o,s,a,i,d,l,u,p,f,g,w,x,M,S,L,D,N,P;return e?{...Ft,...e,theme:Jp(Ft.theme,e.theme),darkTheme:Jp(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(n=Ft.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var ue,ke,je,te,Se,X,ie,He;let E=(ue=Ft.features)==null?void 0:ue.artifacts,O=(ke=e.features)==null?void 0:ke.artifacts,_=(je=Ft.features)==null?void 0:je.scrollToBottom,U=(te=e.features)==null?void 0:te.scrollToBottom,R=(Se=Ft.features)==null?void 0:Se.streamAnimation,$=(X=e.features)==null?void 0:X.streamAnimation,J=(ie=Ft.features)==null?void 0:ie.askUserQuestion,se=(He=e.features)==null?void 0:He.askUserQuestion,Ie=E===void 0&&O===void 0?void 0:{...E,...O,layout:{...E==null?void 0:E.layout,...O==null?void 0:O.layout}},Le=_===void 0&&U===void 0?void 0:{..._,...U},Qe=R===void 0&&$===void 0?void 0:{...R,...$},pe=J===void 0&&se===void 0?void 0:{...J,...se,styles:{...J==null?void 0:J.styles,...se==null?void 0:se.styles}};return{...Ft.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...Ie!==void 0?{artifacts:Ie}:{},...Qe!==void 0?{streamAnimation:Qe}:{},...pe!==void 0?{askUserQuestion:pe}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Ft.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(x=(w=Ft.layout)==null?void 0:w.messages)==null?void 0:x.timestamp,...(S=(M=e.layout)==null?void 0:M.messages)==null?void 0:S.timestamp}},slots:{...(L=Ft.layout)==null?void 0:L.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(N=Ft.markdown)==null?void 0:N.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}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:Un,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 ts(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ts(e,r):r}function ja(e){let n={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ts(e,a);d!==void 0&&(n[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(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 Kp(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Kp(s,o):t[r]=o}return t}function ag(e,n){return n?Kp(e,n):e}function ns(e,n={}){var o,s,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,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.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:ag(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let S=Fi(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(L=>L.message).join(", ")}`)}if(n.plugins)for(let S of n.plugins)r=S.transform(r);return r}function Ua(e){var x,M,S,L,D,N,P,E,O,_,U,R,$,J,se,Ie,Le,Qe,pe,ue,ke,je,te,Se,X,ie,He,de,Re,et,K,ae,Oe,G,V,ve,$e,re,Ee,xe,Bt,Pe,ne,an,Ot,Jt,Cr,pr,Ue,q,we,Be,De,_e,ct,tt,wt,qt,I,he,fe,dt,ze,Wt,ln,At,xt,kt,ut,Kt,wr,qn,_r,Ct,ur,mr,Ar,er,gt,mo,gr,go,En,_o,jr,Sr,bt,Wn,Rn,yn,Lt,zn,Vn,Hn,Ur,Er,qr,Bn,Rt,bn,Jn,zr,Tr,Vr,fr,Dn,tr,ft,Gt,Qt,Nn,Jr,Kn,nr,Fn,j;let n=ja(e),t={};for(let[ce,On]of Object.entries(n)){let rr=ce.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"]=(S=t["--persona-semantic-colors-accent"])!=null?S:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(L=t["--persona-semantic-colors-surface"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(D=t["--persona-semantic-colors-background"])!=null?D:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(N=t["--persona-semantic-colors-container"])!=null?N:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(P=t["--persona-semantic-colors-text"])!=null?P:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(E=t["--persona-semantic-colors-text-muted"])!=null?E:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(O=t["--persona-semantic-colors-text-inverse"])!=null?O:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(_=t["--persona-semantic-colors-border"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(U=t["--persona-semantic-colors-divider"])!=null?U:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=($=t["--persona-components-voice-recording-background"])!=null?$:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(J=t["--persona-components-voice-processing-icon"])!=null?J:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(se=t["--persona-components-voice-speaking-icon"])!=null?se:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ie=t["--persona-components-approval-requested-background"])!=null?Ie:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Le=t["--persona-components-approval-requested-border"])!=null?Le:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Qe=t["--persona-components-approval-requested-text"])!=null?Qe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(pe=t["--persona-components-approval-approve-background"])!=null?pe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(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"]=(Se=t["--persona-semantic-typography-fontSize"])!=null?Se: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"]=(ie=t["--persona-semantic-typography-lineHeight"])!=null?ie:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(He=t["--persona-palette-radius-sm"])!=null?He:"0.125rem",t["--persona-radius-md"]=(de=t["--persona-palette-radius-md"])!=null?de:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(et=t["--persona-palette-radius-xl"])!=null?et:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=(Oe=(ae=t["--persona-components-launcher-borderRadius"])!=null?ae:t["--persona-palette-radius-full"])!=null?Oe:"9999px",t["--persona-launcher-bg"]=(G=t["--persona-components-launcher-background"])!=null?G:t["--persona-primary"],t["--persona-launcher-fg"]=(V=t["--persona-components-launcher-foreground"])!=null?V:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ve=t["--persona-components-launcher-border"])!=null?ve:t["--persona-border"],t["--persona-button-primary-bg"]=($e=t["--persona-components-button-primary-background"])!=null?$e:t["--persona-primary"],t["--persona-button-primary-fg"]=(re=t["--persona-components-button-primary-foreground"])!=null?re:t["--persona-text-inverse"],t["--persona-button-radius"]=(xe=(Ee=t["--persona-components-button-primary-borderRadius"])!=null?Ee:t["--persona-palette-radius-full"])!=null?xe:"9999px",t["--persona-panel-radius"]=(Pe=(Bt=t["--persona-components-panel-borderRadius"])!=null?Bt:t["--persona-radius-xl"])!=null?Pe:"0.75rem",t["--persona-panel-border"]=(ne=t["--persona-components-panel-border"])!=null?ne:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ot=(an=t["--persona-components-panel-shadow"])!=null?an:t["--persona-palette-shadows-xl"])!=null?Ot:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Cr=(Jt=t["--persona-components-input-borderRadius"])!=null?Jt:t["--persona-radius-lg"])!=null?Cr:"0.5rem",t["--persona-message-user-radius"]=(Ue=(pr=t["--persona-components-message-user-borderRadius"])!=null?pr:t["--persona-radius-lg"])!=null?Ue:"0.5rem",t["--persona-message-assistant-radius"]=(we=(q=t["--persona-components-message-assistant-borderRadius"])!=null?q:t["--persona-radius-lg"])!=null?we:"0.5rem",t["--persona-header-bg"]=(Be=t["--persona-components-header-background"])!=null?Be:t["--persona-surface"],t["--persona-header-border"]=(De=t["--persona-components-header-border"])!=null?De:t["--persona-divider"],t["--persona-header-icon-bg"]=(_e=t["--persona-components-header-iconBackground"])!=null?_e:t["--persona-primary"],t["--persona-header-icon-fg"]=(ct=t["--persona-components-header-iconForeground"])!=null?ct:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(tt=t["--persona-components-header-titleForeground"])!=null?tt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(wt=t["--persona-components-header-subtitleForeground"])!=null?wt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(qt=t["--persona-components-header-actionIconForeground"])!=null?qt:t["--persona-muted"];let r=(I=e.components)==null?void 0:I.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(he=e.components)==null?void 0:he.introCard;t["--persona-intro-card-bg"]=(fe=t["--persona-components-introCard-background"])!=null?fe:t["--persona-surface"],t["--persona-intro-card-radius"]=(dt=t["--persona-components-introCard-borderRadius"])!=null?dt:"1rem",t["--persona-intro-card-padding"]=(ze=t["--persona-components-introCard-padding"])!=null?ze:"1.5rem",t["--persona-intro-card-shadow"]=(ln=(Wt=o==null?void 0:o.shadow)!=null?Wt:t["--persona-components-introCard-shadow"])!=null?ln:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(At=t["--persona-components-input-background"])!=null?At:t["--persona-surface"],t["--persona-input-placeholder"]=(xt=t["--persona-components-input-placeholder"])!=null?xt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(kt=t["--persona-components-message-user-background"])!=null?kt:t["--persona-accent"],t["--persona-message-user-text"]=(ut=t["--persona-components-message-user-text"])!=null?ut:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Kt=t["--persona-components-message-user-shadow"])!=null?Kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(wr=t["--persona-components-message-assistant-background"])!=null?wr:t["--persona-surface"],t["--persona-message-assistant-text"]=(qn=t["--persona-components-message-assistant-text"])!=null?qn:t["--persona-text"],t["--persona-message-assistant-border"]=(_r=t["--persona-components-message-assistant-border"])!=null?_r:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ct=t["--persona-components-message-assistant-shadow"])!=null?Ct:"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"]=(gt=t["--persona-components-scrollToBottom-border"])!=null?gt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(mo=t["--persona-components-scrollToBottom-size"])!=null?mo:"40px",t["--persona-scroll-to-bottom-radius"]=(En=(go=(gr=t["--persona-components-scrollToBottom-borderRadius"])!=null?gr:t["--persona-button-radius"])!=null?go:t["--persona-radius-full"])!=null?En:"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"]=(bt=t["--persona-components-scrollToBottom-gap"])!=null?bt:"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"]=(yn=t["--persona-components-scrollToBottom-iconSize"])!=null?yn:"14px",t["--persona-tool-bubble-shadow"]=(Lt=t["--persona-components-toolBubble-shadow"])!=null?Lt:"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"]=(Ur=t["--persona-components-markdown-inlineCode-foreground"])!=null?Ur:t["--persona-text"],t["--persona-md-link-color"]=(qr=(Er=t["--persona-components-markdown-link-foreground"])!=null?Er:t["--persona-accent"])!=null?qr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let 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"]=(Rt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Rt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(bn=t["--persona-components-markdown-codeBlock-textColor"])!=null?bn:"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"]=(zr=t["--persona-components-markdown-table-borderColor"])!=null?zr: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"]=(Vr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Vr: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"]=(ft=t["--persona-components-collapsibleWidget-surface"])!=null?ft:t["--persona-surface"],t["--cw-border"]=(Gt=t["--persona-components-collapsibleWidget-border"])!=null?Gt:t["--persona-border"],t["--persona-message-border"]=(Qt=t["--persona-components-message-border"])!=null?Qt: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 ce=w.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"]=(Nn=t["--persona-dropdown-bg"])!=null?Nn:ce.copyMenuBackground),ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ce.copyMenuBorder,t["--persona-dropdown-border"]=(Jr=t["--persona-dropdown-border"])!=null?Jr:ce.copyMenuBorder),ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(Kn=t["--persona-dropdown-shadow"])!=null?Kn:ce.copyMenuShadow),ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(nr=t["--persona-dropdown-radius"])!=null?nr:ce.copyMenuBorderRadius),ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Fn=t["--persona-dropdown-item-hover-bg"])!=null?Fn:ce.copyMenuItemHoverBackground),ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ce.iconBackground),ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ce.toolbarBorder)}if(w!=null&&w.tab){let ce=w.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(w!=null&&w.pane){let ce=w.pane;if(ce.toolbarBackground){let On=(j=ts(e,ce.toolbarBackground))!=null?j:ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=On}}return t}var Gp={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 ig={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"}}},Qp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Os=()=>{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"},lg=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Os()},Oi=e=>lg(e),cg=e=>ns(e),dg=e=>{var t;let n=ns(void 0,{validate:!1});return ns({...e,palette:{...n.palette,colors:{...ig.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},rs=e=>{let n=Oi(e),t=Qp(e==null?void 0:e.theme),r=Qp(e==null?void 0:e.darkTheme);return n==="dark"?dg(Fs(t!=null?t:{},r!=null?r:{})):cg(t)},pg=e=>Ua(e),no=(e,n)=>{var s;let t=rs(n),r=pg(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let o=(s=n==null?void 0:n.toolCall)==null?void 0:s.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},qa=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Os())});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(Os());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 Xp=require("idiomorph"),za=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Xp.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function Yp(e,n){var t,r,o,s,a,i,d,l,u,p,f,g,w,x,M,S,L,D,N,P,E,O,_,U,R,$,J,se,Ie,Le;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",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:"",(D=(L=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:L.length)!=null?D:0,(O=(E=(P=(N=e.toolCall)==null?void 0:N.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:E.slice(-32))!=null?O:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:(U=e.toolCall)!=null&&U.args?JSON.stringify(e.toolCall.args).length:0,(J=($=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:$.length)!=null?J:0,(Ie=(se=e.contentParts)==null?void 0:se.length)!=null?Ie:0,(Le=e.stopReason)!=null?Le:"",n].join("\0")}function Zp(){return new Map}function eu(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function tu(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function nu(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 $s(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,n){return $s(e)-e.scrollTop<=n}function Ja(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!n&&o&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Ka(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return n&&t<0?"pause":!n&&o&&t>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,ro=hn+1;var js={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ug=["pre","code","a","script","style"],Ga=e=>{var n,t,r,o,s;return{type:(n=e==null?void 0:e.type)!=null?n:js.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:js.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:js.speed,duration:(o=e==null?void 0:e.duration)!=null?o:js.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:js.buffer}},ou=[{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 ou)Us.set(e.name,e);var su=e=>{Us.set(e.name,e)},au=e=>{ou.some(n=>n.name===e)||Us.delete(e)},iu=()=>Array.from(Us.keys()),qs=(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,o)=>{if(!o)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(n==="line"){let s=e.lastIndexOf(`
7
+ `),ct="message",tt="";for(let I of _e)I.startsWith("event:")?ct=I.replace("event:","").trim():I.startsWith("data:")&&(tt+=I.replace("data:","").trim());if(!tt)continue;let wt;try{wt=JSON.parse(tt)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let qt=ct!=="message"?ct:(pr=wt.type)!=null?pr:"message";if((je=this.onSSEEvent)==null||je.call(this,qt,wt),this.parseSSEEvent){w.current=f;let I=await this.handleCustomSSEEvent(wt,t,w,p,l,x);if(w.current&&w.current!==f&&(f=w.current),I)continue}Pe.push(qt,wt),xe()}}Pe.flushPending(),xe(),Pe.destroy()}};function Hp(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Zo(){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 Bp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Dp(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Np(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Fp(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Bs(e){return{type:"text",text:e}}function Op(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 $p(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function _p(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 jp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Zm=["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"],Br=[...jp,...Zm];function eg(e){return jp.includes(e)||e.startsWith("image/")}function Ba(e){return eg(e.type)}async function Up(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ba(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function qp(e,n=Br,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 tg(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function zp(e,n){let t=tg(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(),o=this.pcmToFloat32(t),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.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),o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=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,o,s){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<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):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 Ds=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 o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${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=S=>{w||(w=!0,clearTimeout(k),g(new Error(S)))},k=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(k),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!w){let L=S.code!==1006?` (code ${S.code})`:"";x("WebSocket connection failed"+L+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}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(o=>o({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(o=>o("speaking")),this.playAudio(n.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(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(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("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,o;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.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(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}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 s,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=(s=this.config)==null?void 0:s.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),o=this.getFormatFromMimeType(n.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];t(a)},o.onerror=r,o.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 o=n.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),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=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 Ds(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 Ns(e){try{return Fa(e),!0}catch{return!1}}var es=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,o,s,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:(o=n.message.agentMetadata.iteration)!=null?o: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,((s=this.agentExecution)==null?void 0:s.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,o;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Io(n);for(let s of(o=n.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,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 Ns((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,o;try{let s=n||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Ho(s);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"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 k=(x=this.pendingVoiceAssistantMessageId)!=null?x:(w=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:w.id;k&&this.ttsSpokenMessageIds.add(k)}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(s){console.error("Failed to setup voice:",s)}}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,o,s,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:((o=n.runtype)==null?void 0:o.clientToken)||"",host:(s=n.runtype)==null?void 0:s.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:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=n,g={id:a!=null?a:t==="user"?Zo():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,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(g),g}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:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:g}=r,x={id:d!=null?d:o==="user"?Zo():o==="assistant"?Wo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=n,l={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}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 o=Zo(),s=Wo(),a={id:o,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:s},this.handleEvent)}catch(w){let x=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!x){let k={id:s,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(k)}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 o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.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=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(n,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,l,u,p;let r=`approval-${n.id}`,o={...n,status:t,resolvedAt:Date.now()},s={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):f=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),f){let g=null;if(f instanceof Response){if(!f.ok){let w=await f.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${f.status}`)}g=f.body}else f instanceof ReadableStream&&(g=f);g?await this.connectStream(g,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let g=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(o=>o.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(o=>o.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,k,S,L,D,N,P;let r=this.messages.find(E=>E.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(p=n.agentMetadata)==null?void 0:p.executionId,s=(f=n.toolCall)==null?void 0:f.name;if(!o||!s){(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 E=(x=n.toolCall)==null?void 0:x.args,O=Array.isArray(E==null?void 0:E.questions)?E.questions:[];if(O.length===1){let _=typeof((k=O[0])==null?void 0:k.question)=="string"?O[0].question:"";_&&(a={[_]:t})}}this.markAskUserQuestionResolved(n,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(L=n.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let E=typeof t=="string"?t:Object.entries(t).map(([O,_])=>`${O}: ${Array.isArray(_)?_.join(", "):_}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let E=a!=null?a:{};l.forEach((O,_)=>{let U=typeof(O==null?void 0:O.question)=="string"?O.question:"";if(!U)return;let R=E[U],$=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:$||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let E=await this.client.resumeFlow(o,{[s]:t});if(!E.ok){let O=await E.json().catch(()=>null);throw new Error((D=O==null?void 0:O.error)!=null?D:`Resume failed: ${E.status}`)}E.body?await this.connectStream(E.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(E){let O=E instanceof Error&&(E.name==="AbortError"||E.message.includes("aborted")||E.message.includes("abort"));this.setStreaming(!1),this.abortController=null,O||(P=(N=this.callbacks).onError)==null||P.call(N,E instanceof Error?E:new Error(String(E)))}}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 o;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(o=n.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var 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 o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...n.props},n.component&&(o.component=n.component));break}case"artifact_complete":{let o=this.artifacts.get(n.id);o&&(o.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 o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(n),s=r.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=t.pickVoice?t.pickVoice(s):e.pickBestVoice(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>r.speak(o),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 o of t){let s=n.find(a=>a.name===o);if(s)return s}return(r=n.find(o=>o.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(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var i;if(s!==r)return o;let a={...o,...t};return((i=o.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.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 o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(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"),ng={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},me=(e,n=24,t="currentColor",r=2)=>{let o=ng[e];return o?rg(o,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 rg(e,n,t,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),o.appendChild(d)}),o}var Oa={allowedTypes:Br,maxFileSize:10*1024*1024,maxFiles:4};function og(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sg(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,o;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Oa.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Oa.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o: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,o,s,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=qp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await Up(l),f=Ba(l)?URL.createObjectURL(l):null,g={id:og(),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 s,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 o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.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=sg(n.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=zp(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 o=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=me("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(o),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 Vp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fs(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];Vp(s)&&Vp(o)?t[r]=Fs(s,o):t[r]=o}return t}var Un="min(440px, calc(100vw - 24px))",$a="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Un,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 Jp(e,n){if(!(!e&&!n))return e?n?Fs(e,n):e:n}function _a(e){var n,t,r,o,s,a,i,d,l,u,p,f,g,w,x,k,S,L,D,N,P;return e?{...Ft,...e,theme:Jp(Ft.theme,e.theme),darkTheme:Jp(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(n=Ft.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var pe,Le,qe,te,Se,X,ie,He;let E=(pe=Ft.features)==null?void 0:pe.artifacts,O=(Le=e.features)==null?void 0:Le.artifacts,_=(qe=Ft.features)==null?void 0:qe.scrollToBottom,U=(te=e.features)==null?void 0:te.scrollToBottom,R=(Se=Ft.features)==null?void 0:Se.streamAnimation,$=(X=e.features)==null?void 0:X.streamAnimation,J=(ie=Ft.features)==null?void 0:ie.askUserQuestion,se=(He=e.features)==null?void 0:He.askUserQuestion,Ie=E===void 0&&O===void 0?void 0:{...E,...O,layout:{...E==null?void 0:E.layout,...O==null?void 0:O.layout}},ke=_===void 0&&U===void 0?void 0:{..._,...U},Qe=R===void 0&&$===void 0?void 0:{...R,...$},ge=J===void 0&&se===void 0?void 0:{...J,...se,styles:{...J==null?void 0:J.styles,...se==null?void 0:se.styles}};return{...Ft.features,...e.features,...ke!==void 0?{scrollToBottom:ke}:{},...Ie!==void 0?{artifacts:Ie}:{},...Qe!==void 0?{streamAnimation:Qe}:{},...ge!==void 0?{askUserQuestion:ge}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Ft.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(x=(w=Ft.layout)==null?void 0:w.messages)==null?void 0:x.timestamp,...(S=(k=e.layout)==null?void 0:k.messages)==null?void 0:S.timestamp}},slots:{...(L=Ft.layout)==null?void 0:L.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(N=Ft.markdown)==null?void 0:N.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}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:Un,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 ts(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ts(e,r):r}function ja(e){let n={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ts(e,a);d!==void 0&&(n[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(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 Kp(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Kp(s,o):t[r]=o}return t}function ag(e,n){return n?Kp(e,n):e}function ns(e,n={}){var o,s,a,i,d,l,u,p,f,g,w,x,k;let t={palette:Bi,semantic:Di,components:Ni},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.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,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:ag(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let S=Fi(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(L=>L.message).join(", ")}`)}if(n.plugins)for(let S of n.plugins)r=S.transform(r);return r}function Ua(e){var x,k,S,L,D,N,P,E,O,_,U,R,$,J,se,Ie,ke,Qe,ge,pe,Le,qe,te,Se,X,ie,He,de,Re,et,K,ae,Oe,G,V,ve,$e,re,Ee,xe,Bt,Pe,ne,an,Ot,Jt,Cr,pr,je,q,we,Be,De,_e,ct,tt,wt,qt,I,he,fe,dt,ze,Wt,ln,At,xt,kt,ut,Kt,wr,qn,_r,Ct,ur,mr,Ar,er,gt,mo,gr,go,En,_o,jr,Sr,bt,Wn,Rn,yn,Lt,zn,Vn,Hn,Ur,Er,qr,Bn,Rt,bn,Jn,zr,Tr,Vr,fr,Dn,tr,ft,Gt,Qt,Nn,Jr,Kn,nr,Fn,j;let n=ja(e),t={};for(let[ce,On]of Object.entries(n)){let rr=ce.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"]=(k=t["--persona-semantic-colors-secondary"])!=null?k:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(S=t["--persona-semantic-colors-accent"])!=null?S:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(L=t["--persona-semantic-colors-surface"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(D=t["--persona-semantic-colors-background"])!=null?D:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(N=t["--persona-semantic-colors-container"])!=null?N:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(P=t["--persona-semantic-colors-text"])!=null?P:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(E=t["--persona-semantic-colors-text-muted"])!=null?E:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(O=t["--persona-semantic-colors-text-inverse"])!=null?O:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(_=t["--persona-semantic-colors-border"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(U=t["--persona-semantic-colors-divider"])!=null?U:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=($=t["--persona-components-voice-recording-background"])!=null?$:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(J=t["--persona-components-voice-processing-icon"])!=null?J:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(se=t["--persona-components-voice-speaking-icon"])!=null?se:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ie=t["--persona-components-approval-requested-background"])!=null?Ie:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ke=t["--persona-components-approval-requested-border"])!=null?ke:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Qe=t["--persona-components-approval-requested-text"])!=null?Qe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ge=t["--persona-components-approval-approve-background"])!=null?ge:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(pe=t["--persona-components-approval-deny-background"])!=null?pe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Le=t["--persona-components-attachment-image-background"])!=null?Le:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(qe=t["--persona-components-attachment-image-border"])!=null?qe: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"]=(Se=t["--persona-semantic-typography-fontSize"])!=null?Se: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"]=(ie=t["--persona-semantic-typography-lineHeight"])!=null?ie:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(He=t["--persona-palette-radius-sm"])!=null?He:"0.125rem",t["--persona-radius-md"]=(de=t["--persona-palette-radius-md"])!=null?de:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(et=t["--persona-palette-radius-xl"])!=null?et:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=(Oe=(ae=t["--persona-components-launcher-borderRadius"])!=null?ae:t["--persona-palette-radius-full"])!=null?Oe:"9999px",t["--persona-launcher-bg"]=(G=t["--persona-components-launcher-background"])!=null?G:t["--persona-primary"],t["--persona-launcher-fg"]=(V=t["--persona-components-launcher-foreground"])!=null?V:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ve=t["--persona-components-launcher-border"])!=null?ve:t["--persona-border"],t["--persona-button-primary-bg"]=($e=t["--persona-components-button-primary-background"])!=null?$e:t["--persona-primary"],t["--persona-button-primary-fg"]=(re=t["--persona-components-button-primary-foreground"])!=null?re:t["--persona-text-inverse"],t["--persona-button-radius"]=(xe=(Ee=t["--persona-components-button-primary-borderRadius"])!=null?Ee:t["--persona-palette-radius-full"])!=null?xe:"9999px",t["--persona-panel-radius"]=(Pe=(Bt=t["--persona-components-panel-borderRadius"])!=null?Bt:t["--persona-radius-xl"])!=null?Pe:"0.75rem",t["--persona-panel-border"]=(ne=t["--persona-components-panel-border"])!=null?ne:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ot=(an=t["--persona-components-panel-shadow"])!=null?an:t["--persona-palette-shadows-xl"])!=null?Ot:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Cr=(Jt=t["--persona-components-input-borderRadius"])!=null?Jt:t["--persona-radius-lg"])!=null?Cr:"0.5rem",t["--persona-message-user-radius"]=(je=(pr=t["--persona-components-message-user-borderRadius"])!=null?pr:t["--persona-radius-lg"])!=null?je:"0.5rem",t["--persona-message-assistant-radius"]=(we=(q=t["--persona-components-message-assistant-borderRadius"])!=null?q:t["--persona-radius-lg"])!=null?we:"0.5rem",t["--persona-header-bg"]=(Be=t["--persona-components-header-background"])!=null?Be:t["--persona-surface"],t["--persona-header-border"]=(De=t["--persona-components-header-border"])!=null?De:t["--persona-divider"],t["--persona-header-icon-bg"]=(_e=t["--persona-components-header-iconBackground"])!=null?_e:t["--persona-primary"],t["--persona-header-icon-fg"]=(ct=t["--persona-components-header-iconForeground"])!=null?ct:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(tt=t["--persona-components-header-titleForeground"])!=null?tt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(wt=t["--persona-components-header-subtitleForeground"])!=null?wt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(qt=t["--persona-components-header-actionIconForeground"])!=null?qt:t["--persona-muted"];let r=(I=e.components)==null?void 0:I.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(he=e.components)==null?void 0:he.introCard;t["--persona-intro-card-bg"]=(fe=t["--persona-components-introCard-background"])!=null?fe:t["--persona-surface"],t["--persona-intro-card-radius"]=(dt=t["--persona-components-introCard-borderRadius"])!=null?dt:"1rem",t["--persona-intro-card-padding"]=(ze=t["--persona-components-introCard-padding"])!=null?ze:"1.5rem",t["--persona-intro-card-shadow"]=(ln=(Wt=o==null?void 0:o.shadow)!=null?Wt:t["--persona-components-introCard-shadow"])!=null?ln:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(At=t["--persona-components-input-background"])!=null?At:t["--persona-surface"],t["--persona-input-placeholder"]=(xt=t["--persona-components-input-placeholder"])!=null?xt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(kt=t["--persona-components-message-user-background"])!=null?kt:t["--persona-accent"],t["--persona-message-user-text"]=(ut=t["--persona-components-message-user-text"])!=null?ut:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Kt=t["--persona-components-message-user-shadow"])!=null?Kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(wr=t["--persona-components-message-assistant-background"])!=null?wr:t["--persona-surface"],t["--persona-message-assistant-text"]=(qn=t["--persona-components-message-assistant-text"])!=null?qn:t["--persona-text"],t["--persona-message-assistant-border"]=(_r=t["--persona-components-message-assistant-border"])!=null?_r:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ct=t["--persona-components-message-assistant-shadow"])!=null?Ct:"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"]=(gt=t["--persona-components-scrollToBottom-border"])!=null?gt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(mo=t["--persona-components-scrollToBottom-size"])!=null?mo:"40px",t["--persona-scroll-to-bottom-radius"]=(En=(go=(gr=t["--persona-components-scrollToBottom-borderRadius"])!=null?gr:t["--persona-button-radius"])!=null?go:t["--persona-radius-full"])!=null?En:"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"]=(bt=t["--persona-components-scrollToBottom-gap"])!=null?bt:"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"]=(yn=t["--persona-components-scrollToBottom-iconSize"])!=null?yn:"14px",t["--persona-tool-bubble-shadow"]=(Lt=t["--persona-components-toolBubble-shadow"])!=null?Lt:"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"]=(Ur=t["--persona-components-markdown-inlineCode-foreground"])!=null?Ur:t["--persona-text"],t["--persona-md-link-color"]=(qr=(Er=t["--persona-components-markdown-link-foreground"])!=null?Er:t["--persona-accent"])!=null?qr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let 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"]=(Rt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Rt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(bn=t["--persona-components-markdown-codeBlock-textColor"])!=null?bn:"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"]=(zr=t["--persona-components-markdown-table-borderColor"])!=null?zr: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"]=(Vr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Vr: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"]=(ft=t["--persona-components-collapsibleWidget-surface"])!=null?ft:t["--persona-surface"],t["--cw-border"]=(Gt=t["--persona-components-collapsibleWidget-border"])!=null?Gt:t["--persona-border"],t["--persona-message-border"]=(Qt=t["--persona-components-message-border"])!=null?Qt: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 ce=w.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"]=(Nn=t["--persona-dropdown-bg"])!=null?Nn:ce.copyMenuBackground),ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ce.copyMenuBorder,t["--persona-dropdown-border"]=(Jr=t["--persona-dropdown-border"])!=null?Jr:ce.copyMenuBorder),ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(Kn=t["--persona-dropdown-shadow"])!=null?Kn:ce.copyMenuShadow),ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(nr=t["--persona-dropdown-radius"])!=null?nr:ce.copyMenuBorderRadius),ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Fn=t["--persona-dropdown-item-hover-bg"])!=null?Fn:ce.copyMenuItemHoverBackground),ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ce.iconBackground),ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ce.toolbarBorder)}if(w!=null&&w.tab){let ce=w.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(w!=null&&w.pane){let ce=w.pane;if(ce.toolbarBackground){let On=(j=ts(e,ce.toolbarBackground))!=null?j:ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=On}}return t}var Gp={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 ig={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"}}},Qp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Os=()=>{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"},lg=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Os()},Oi=e=>lg(e),cg=e=>ns(e),dg=e=>{var t;let n=ns(void 0,{validate:!1});return ns({...e,palette:{...n.palette,colors:{...ig.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},rs=e=>{let n=Oi(e),t=Qp(e==null?void 0:e.theme),r=Qp(e==null?void 0:e.darkTheme);return n==="dark"?dg(Fs(t!=null?t:{},r!=null?r:{})):cg(t)},pg=e=>Ua(e),no=(e,n)=>{var s;let t=rs(n),r=pg(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let o=(s=n==null?void 0:n.toolCall)==null?void 0:s.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},qa=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Os())});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(Os());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 Xp=require("idiomorph"),za=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Xp.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function Yp(e,n){var t,r,o,s,a,i,d,l,u,p,f,g,w,x,k,S,L,D,N,P,E,O,_,U,R,$,J,se,Ie,ke;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",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:"",(k=(x=e.toolCall)==null?void 0:x.name)!=null?k:"",(D=(L=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:L.length)!=null?D:0,(O=(E=(P=(N=e.toolCall)==null?void 0:N.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:E.slice(-32))!=null?O:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:(U=e.toolCall)!=null&&U.args?JSON.stringify(e.toolCall.args).length:0,(J=($=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:$.length)!=null?J:0,(Ie=(se=e.contentParts)==null?void 0:se.length)!=null?Ie:0,(ke=e.stopReason)!=null?ke:"",n].join("\0")}function Zp(){return new Map}function eu(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function tu(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function nu(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 $s(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,n){return $s(e)-e.scrollTop<=n}function Ja(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!n&&o&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Ka(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return n&&t<0?"pause":!n&&o&&t>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,ro=hn+1;var js={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ug=["pre","code","a","script","style"],Ga=e=>{var n,t,r,o,s;return{type:(n=e==null?void 0:e.type)!=null?n:js.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:js.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:js.speed,duration:(o=e==null?void 0:e.duration)!=null?o:js.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:js.buffer}},ou=[{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 ou)Us.set(e.name,e);var su=e=>{Us.set(e.name,e)},au=e=>{ou.some(n=>n.name===e)||Us.delete(e)},iu=()=>Array.from(Us.keys()),qs=(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,o)=>{if(!o)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(n==="line"){let s=e.lastIndexOf(`
8
8
  `);return s<0?"":e.slice(0,s)}return e},mg=(e,n,t,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=n,o},gg=(e,n,t,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=n,o},$i=/\s/,fg=(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},hg=(e,n,t)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if($i.test(s[i])){let l=i;for(;l<s.length&&$i.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<s.length&&!$i.test(s[u]);)l.appendChild(mg(r,s[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}o.replaceChild(a,e)},yg=(e,n,t)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(gg(r,l,n,t.value)),t.value+=1));o.replaceChild(a,e)},zs=(e,n,t,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((p=r==null?void 0:r.skipTags)!=null?p:ug).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)fg(d,s)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?hg:yg;for(let g of i)u(g,t,l);return o.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},Vs=(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},ru=new WeakMap,bg=(e,n)=>{var s;if(!e.styles)return;let t=ru.get(n);if(t||(t=new Set,ru.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 o=(n instanceof ShadowRoot?n.ownerDocument:(s=n.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,n.appendChild(o)},_i=new WeakMap,xg=(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)},lu=e=>{let n=_i.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},ji=(e,n)=>{bg(e,n),xg(e,n)};function Ui(e,n=hn){let t=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.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=o}}var Js=0,oo=null;function qi(e=document){var t;if(Js++,Js===1){let r=e.body,s=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;oo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,Js=Math.max(0,Js-1),Js===0&&oo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=oo.originalOverflow,o.style.position=oo.originalPosition,o.style.top=oo.originalTop,o.style.width=oo.originalWidth,s.scrollTo(0,oo.scrollY),oo=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"},so=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,o,s,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:(o=n==null?void 0:n.width)!=null?o:Ya.width,animate:(s=n==null?void 0:n.animate)!=null?s: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 Ks=(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" />
@@ -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=s=>{var D,N,P,E,O,_,U,R,$,J,se,Ie,Le,Qe;let a=(D=s.launcher)!=null?D:{},i=nn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let pe=(N=a.title)!=null?N:"Chat Assistant";d.textContent=pe,d.setAttribute("title",pe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let pe=(P=a.subtitle)!=null?P:"Get answers fast";l.textContent=pe,l.setAttribute("title",pe)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let pe=(E=a.agentIconSize)!=null?E:"40px";if(p.style.height=pe,p.style.width=pe,p.innerHTML="",a.agentIconName){let ue=parseFloat(pe)||24,ke=ge(a.agentIconName,ue*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(p.appendChild(ke),p.style.display=""):(p.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(_=a.agentIconText)!=null?_:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let pe=(U=a.agentIconSize)!=null?U:"40px";f.style.height=pe,f.style.width=pe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let pe=(R=a.callToActionIconSize)!=null?R:"32px";g.style.height=pe,g.style.width=pe,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(pe)||24,je=Math.max(ke-ue,8),te=ge(a.callToActionIconName,je,"currentColor",2);te?g.appendChild(te):g.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else g.textContent=(J=a.callToActionIconText)!=null?J:"\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((se=a.zIndex)!=null?se:hn));let S="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Ie=a.border)!=null?Ie:S,t.style.boxShadow=(Le=a.shadow)!=null?Le:L,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=(Qe=a.collapsedMaxWidth)!=null?Qe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:o}};var vg="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Za=(e,n={})=>{var x,M,S,L,D,N;let{showClose:t=!0,wrapperClassName:r=vg,buttonSize:o,iconSize:s="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(M=o!=null?o: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=(S=a.closeButtonTooltipText)!=null?S:"Close chat",p=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(D=a.closeButtonIconName)!=null?D:"x",g=(N=a.closeButtonIconText)!=null?N:"\xD7";l.style.color=a.closeButtonColor||Sn.actionIconColor;let w=ge(f,s,"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 P=a.closeButtonBorderWidth||"0px",E=a.closeButtonBorderColor||"transparent";l.style.border=`${P} solid ${E}`,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 P=null,E=()=>{if(P)return;let _=l.ownerDocument,U=_.body;if(!U)return;P=xr(_,"div","persona-clear-chat-tooltip"),P.textContent=u;let R=xr(_,"div");R.className="persona-clear-chat-tooltip-arrow",P.appendChild(R);let $=l.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(ro),P.style.left=`${$.left+$.width/2}px`,P.style.top=`${$.top-8}px`,P.style.transform="translate(-50%, -100%)",U.appendChild(P)},O=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};d.addEventListener("mouseenter",E),d.addEventListener("mouseleave",O),l.addEventListener("focus",E),l.addEventListener("blur",O),d._cleanupTooltip=()=>{O(),d.removeEventListener("mouseenter",E),d.removeEventListener("mouseleave",O),l.removeEventListener("focus",E),l.removeEventListener("blur",O)}}return{button:l,wrapper:d}},Cg="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ei=(e,n={})=>{var P,E,O,_,U,R,$,J,se,Ie,Le,Qe,pe;let{wrapperClassName:t=Cg,buttonSize:r,iconSize:o="20px"}=n,a=(E=((P=e==null?void 0:e.launcher)!=null?P:{}).clearChat)!=null?E:{},i=(O=r!=null?r:a.size)!=null?O:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",l=(U=a.iconColor)!=null?U:"",u=(R=a.backgroundColor)!=null?R:"",p=($=a.borderWidth)!=null?$:"",f=(J=a.borderColor)!=null?J:"",g=(se=a.borderRadius)!=null?se:"",w=(Ie=a.paddingX)!=null?Ie:"",x=(Le=a.paddingY)!=null?Le:"",M=(Qe=a.tooltipText)!=null?Qe:"Clear chat",S=(pe=a.showTooltip)!=null?pe:!0,L=h("div",t),D=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");D.style.height=i,D.style.width=i,D.type="button",D.setAttribute("aria-label",M),D.style.color=l||Sn.actionIconColor;let N=ge(d,o,"currentColor",1);if(N&&(N.style.display="block",D.appendChild(N)),u&&(D.style.backgroundColor=u,D.classList.remove("hover:persona-bg-gray-100")),p||f){let ue=p||"0px",ke=f||"transparent";D.style.border=`${ue} solid ${ke}`,D.classList.remove("persona-border-none")}if(g&&(D.style.borderRadius=g,D.classList.remove("persona-rounded-full")),w&&(D.style.paddingLeft=w,D.style.paddingRight=w),x&&(D.style.paddingTop=x,D.style.paddingBottom=x),L.appendChild(D),S&&M){let ue=null,ke=()=>{if(ue)return;let te=D.ownerDocument,Se=te.body;if(!Se)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 ie=D.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(ro),ue.style.left=`${ie.left+ie.width/2}px`,ue.style.top=`${ie.top-8}px`,ue.style.transform="translate(-50%, -100%)",Se.appendChild(ue)},je=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};L.addEventListener("mouseenter",ke),L.addEventListener("mouseleave",je),D.addEventListener("focus",ke),D.addEventListener("blur",je),L._cleanupTooltip=()=>{je(),L.removeEventListener("mouseenter",ke),L.removeEventListener("mouseleave",je),D.removeEventListener("focus",ke),D.removeEventListener("blur",je)}}return{button:D,wrapper:L}};var Sn={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))"},Dr=e=>{var P,E,O,_,U,R,$,J,se,Ie,Le,Qe,pe,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 o=(P=n==null?void 0:n.launcher)!=null?P:{},s=(E=o.headerIconSize)!=null?E:"48px",a=(O=o.closeButtonPlacement)!=null?O:"inline",i=(_=o.headerIconHidden)!=null?_:!1,d=o.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,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(s)||24,Se=ge(d,te*.6,"currentColor",1);Se?l.replaceChildren(Se):l.textContent=(R=(U=n==null?void 0:n.launcher)==null?void 0:U.agentIconText)!=null?R:"\u{1F4AC}"}else if(($=n==null?void 0:n.launcher)!=null&&$.iconUrl){let te=h("img");te.src=n.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=s,te.style.width=s,l.replaceChildren(te)}else l.textContent=(se=(J=n==null?void 0:n.launcher)==null?void 0:J.agentIconText)!=null?se:"\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=Sn.titleColor,p.textContent=(Le=(Ie=n==null?void 0:n.launcher)==null?void 0:Ie.title)!=null?Le:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Sn.subtitleColor,f.textContent=(pe=(Qe=n==null?void 0:n.launcher)==null?void 0:Qe.subtitle)!=null?pe:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let g=(ue=o.clearChat)!=null?ue:{},w=(ke=g.enabled)!=null?ke:!0,x=(je=g.placement)!=null?je:"inline",M=null,S=null;if(w){let Se=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=Se.button,S=Se.wrapper,x==="top-right"&&(S.style.right="48px"),x==="inline"&&r.appendChild(S)}let L=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:D,wrapper:N}=Za(n,{showClose:t,wrapperClassName:L});return a!=="top-right"&&r.appendChild(N),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:D,closeButtonWrapper:N,clearChatButton:M,clearChatButtonWrapper:S}},Do=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function ao(e){let{items:n,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(ro)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let 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(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="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 s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function jt(e){let{icon:n,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=ge(n,r!=null?r:16,"currentColor",o!=null?o: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 Gs(e){let{icon:n,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=ge(n,s!=null?s: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 Qs(e){let{items:n,selectedId:t,onSelect:r,className:o}=e,s=h("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=jt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),s.appendChild(p)}function l(u){a=u,d()}return{element:s,setSelected:l}}function ti(e){var g,w;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="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=ao({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,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=Dr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=n.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return n};function wg(e,n,t){var r,o,s;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",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ge(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=h("div","persona-relative");d.appendChild(i);let l=ao({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 L,D,N,P,E,O,_,U,R;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=n==null?void 0:n.launcher)!=null?L:{},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=o==null?void 0:o.titleMenu,l,u;if(d)l=ti({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Sn.titleColor,u=(N=l.querySelector(".persona-combo-btn-label"))!=null?N:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Sn.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(u),wg(l,o==null?void 0:o.trailingActions,(E=o==null?void 0:o.onAction)!=null?E:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let J=o.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||J()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),J())})}let $=o==null?void 0:o.titleRowHover;$&&(l.style.borderRadius=(O=$.borderRadius)!=null?O:"10px",l.style.padding=(_=$.padding)!=null?_:"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 J,se;l.style.backgroundColor=(J=$.background)!=null?J:"",l.style.borderColor=(se=$.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(U=a.closeButtonSize)!=null?U:"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||Sn.actionIconColor;let w=(R=a.closeButtonIconName)!=null?R:"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 S=h("span");return S.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:S,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},os=(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",s=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&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};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 o=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,o());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:s}},oi=e=>{var P,E,O,_,U,R,$,J,se,Ie,Le,Qe;let n=(P=e==null?void 0:e.sendButton)!=null?P:{},t=(E=n.useIcon)!=null?E:!1,r=(O=n.iconText)!=null?O:"\u2191",o=n.iconName,s=(_=n.stopIconName)!=null?_:"square",a=(U=n.tooltipText)!=null?U:"Send message",i=(R=n.stopTooltipText)!=null?R:"Stop generating",d=(J=($=e==null?void 0:e.copy)==null?void 0:$.sendButtonLabel)!=null?J:"Send",l=(Ie=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?Ie:"Stop",u=(Le=n.showTooltip)!=null?Le:!1,p=(Qe=n.size)!=null?Qe:"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,S=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 pe=parseFloat(p)||24,ue=(g==null?void 0:g.trim())||"currentColor";o?(M=ge(o,pe,ue,2),M?x.appendChild(M):x.textContent=r):x.textContent=r,S=ge(s,pe,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 L=null;u&&a&&(L=h("div","persona-send-button-tooltip"),L.textContent=a,w.appendChild(L)),x.setAttribute("aria-label",a),w.appendChild(x);let D="send";return{button:x,wrapper:w,setMode:pe=>{if(pe===D)return;D=pe;let ue=pe==="stop"?i:a;if(x.setAttribute("aria-label",ue),L&&(L.textContent=ue),t){if(M&&S){let ke=pe==="stop"?S:M,je=pe==="stop"?M:S;je.parentNode===x?x.replaceChild(ke,je):x.appendChild(ke)}}else x.textContent=pe==="stop"?l:d}}},si=e=>{var L,D,N,P,E,O,_,U,R,$,J,se;let n=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((D=n.provider)==null?void 0:D.type)==="runtype";if(!(r||o))return null;let a=(P=(N=e==null?void 0:e.sendButton)==null?void 0:N.size)!=null?P:"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=(E=n.iconName)!=null?E:"mic",u=(O=n.iconSize)!=null?O:a,p=parseFloat(u)||24,f=(U=n.backgroundColor)!=null?U:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,g=($=n.iconColor)!=null?$:(R=e==null?void 0:e.sendButton)==null?void 0:R.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=(J=n.tooltipText)!=null?J:"Start voice recognition";if(((se=n.showTooltip)!=null?se:!1)&&M){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=M,i.appendChild(Ie)}return{button:d,wrapper:i}},ai=e=>{var w,x,M,S,L,D,N,P;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 o=h("input");o.type="file",o.accept=((S=n.allowedTypes)!=null?S:Br).join(","),o.multiple=((L=n.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=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",(D=n.buttonTooltipText)!=null?D:"Attach file");let i=(N=n.buttonIconName)!=null?N:"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",E=>{E.preventDefault(),o.click()}),s.appendChild(a);let f=(P=n.buttonTooltipText)!=null?P:"Attach file",g=h("div","persona-send-button-tooltip");return g.textContent=f,s.appendChild(g),{button:a,wrapper:s,input:o,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 o=(i=n.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(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=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},li=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ss=e=>{var w,x,M,S,L,D;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(),o=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");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=ri(n);a();let i=oi(n),d=si(n),l=ai(n),u=ii(n);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);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),o.append(p),o.addEventListener("click",N=>{N.target!==i.button&&N.target!==i.wrapper&&N.target!==(d==null?void 0:d.button)&&N.target!==(d==null?void 0:d.wrapper)&&N.target!==(l==null?void 0:l.button)&&N.target!==(l==null?void 0:l.wrapper)&&s.focus()}),t.append(r,o,u),{footer:t,suggestions:r,composerForm:o,textarea:s,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:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var cu=()=>{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"),o=h("span","persona-pill-peek__caret"),s=ge("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(n,r,o),{root:e,textNode:r}},du=e=>{var w,x,M,S,L,D;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 o=ii(n);o.style.display="none";let{textarea:s,attachAutoResize:a}=ri(n);s.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",N=>{N.target!==i.button&&N.target!==i.wrapper&&N.target!==(d==null?void 0:d.button)&&N.target!==(d==null?void 0:d.wrapper)&&N.target!==(l==null?void 0:l.button)&&N.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(p,s,f),l&&t.append(l.previewsContainer),t.append(u,r,o);let g=u;return{footer:t,suggestions:r,composerForm:u,textarea:s,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:o,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var pu=e=>{var u,p,f,g,w,x,M,S,L,D,N,P,E,O,_,U,R;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=nn(e);if(so(e)){let $=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},J=h("div","persona-widget-wrapper persona-fixed persona-transition");J.setAttribute("data-persona-composer-bar",""),J.dataset.state="collapsed",J.dataset.expandedSize=(w=$.expandedSize)!=null?w:"anchored",J.style.zIndex=String((M=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?M:hn);let se=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",J.appendChild(se);let Ie=h("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(S=$.expandedSize)!=null?S:"anchored",Ie.style.zIndex=String((D=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?D:hn),{wrapper:J,panel:se,pillRoot:Ie}}if(t){let $=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),J=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return $.appendChild(J),{wrapper:$,panel:J}}if(!n){let $=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),J=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(P=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?P:"100%";return $.style.width=se,J.style.width="100%",$.appendChild(J),{wrapper:$,panel:J}}let o=(E=e==null?void 0:e.launcher)!=null?E:{},s=o.position&&dr[o.position]?dr[o.position]:dr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((_=(O=e==null?void 0:e.launcher)==null?void 0:O.zIndex)!=null?_:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(U=e==null?void 0:e.launcher)==null?void 0:U.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:Un;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ag=(e,n)=>{var N,P,E,O,_,U,R,$,J;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:o}=Za(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(E=(P=(N=e==null?void 0:e.launcher)==null?void 0:N.clearChat)==null?void 0:P.enabled)!=null?E:!0,a=null,i=null;if(s){let se=ei(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.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=(_=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeTitle)!=null?_:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(R=(U=e==null?void 0:e.copy)==null?void 0:U.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",u.append(p,f);let g=h("div","persona-flex persona-flex-col persona-gap-3"),w=($=e==null?void 0:e.layout)==null?void 0:$.contentMaxWidth;w&&(g.style.maxWidth=w,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((J=e==null?void 0:e.copy)==null?void 0:J.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 S=du({config:e}),{root:L,textNode:D}=cu();return t.append(d,o,l,M),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:g,composerOverlay:M,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode,peekBanner:L,peekTextNode:D}},uu=(e,n=!0)=>{var M,S,L,D,N,P,E,O,_;if(so(e))return Ag(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,o=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,s=r?os(e,r,{showClose:n}):Dr({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=(D=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?D:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(P=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(E=e==null?void 0:e.layout)==null?void 0:E.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=ss({config:e}),w=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;o?Do(t,s,e):(s.header.style.display="none",Do(t,s,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:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.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 Sg=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}},Eg=(e,n)=>{if(!e)return null;let t=Sg(e);if(t===null)return null;let r=n==null?void 0:n[e],o=r!==void 0?r:t;return o||null},Tg=(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},Mg=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Ki=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},Gi=320,gu=320,kg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Lg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),Pg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),Ig=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),Wg=(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 o=0,s=!1,a=()=>{s||(s=!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=`${Gi}px`,l.style.maxHeight=`${gu}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;o+=1,l.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{u=!0}),Mg(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},Rg=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!Ki(r.audio))return;let o=h("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Gi}px`,n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Hg=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!Ki(r.video))return;let o=h("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Gi}px`,o.style.maxHeight=`${gu}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Bg=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!Ki(r.data))return;let o=h("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return 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 o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(o),e},Qi=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:No};if(n){let o=n(r);if(o!==null)return o}return No()},Dg=(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 o=h("img");o.src=r,o.alt=n==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(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},mu=(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},Ng=(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},Xi=(e,n,t)=>{var g,w,x,M,S,L;let r=(g=n.showCopy)!=null?g:!0,o=(w=n.showUpvote)!=null?w:!0,s=(x=n.showDownvote)!=null?x:!0;if(!r&&!o&&!s){let D=h("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let a=(M=n.visibility)!=null?M:"hover",i=(S=n.align)!=null?S:"right",d=(L=n.layout)!=null?L:"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=(D,N,P)=>{let E=jt({icon:D,label:N,size:14,className:"persona-message-action-btn"});return E.setAttribute("data-action",P),E};return r&&p.appendChild(f("copy","Copy message","copy")),o&&p.appendChild(f("thumbs-up","Upvote","upvote")),s&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},as=(e,n,t,r,o,s)=>{var te,Se,X,ie,He,de,Re,et,K,ae,Oe,G,V,ve,$e,re,Ee;let a=t!=null?t:{},i=(te=a.layout)!=null?te:"bubble",d=a.avatar,l=a.timestamp,u=(Se=d==null?void 0:d.show)!=null?Se:!1,p=(X=l==null?void 0:l.show)!=null?X:!1,f=(ie=d==null?void 0:d.position)!=null?ie:"left",g=(He=l==null?void 0:l.position)!=null?He:"below",w=Ng(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=kg(e),S=(Re=(de=e.content)==null?void 0:de.trim())!=null?Re:"",D=M.length>0&&S===Ha,N=Ga((K=(et=s==null?void 0:s.widgetConfig)==null?void 0:et.features)==null?void 0:K.streamAnimation),P=(G=(Oe=(ae=s==null?void 0:s.widgetConfig)==null?void 0:ae.features)==null?void 0:Oe.streamAnimation)==null?void 0:G.plugins,E=e.role==="assistant"&&N.type!=="none"?qs(N.type,P):null,O=e.role==="assistant"&&((V=E==null?void 0:E.isAnimating)==null?void 0:V.call(E,e))===!0,_=e.role==="assistant"&&E!==null&&(!!e.streaming||O);_&&(E!=null&&E.bubbleClass)&&x.classList.add(E.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),_&&E&&(E.containerClass&&U.classList.add(E.containerClass),U.style.setProperty("--persona-stream-step",`${N.speed}ms`),U.style.setProperty("--persona-stream-duration",`${N.duration}ms`));let R=_?Qa((ve=e.content)!=null?ve:"",N.buffer,E,e,!!e.streaming):($e=e.content)!=null?$e:"",$=n({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),J=$;_&&(E==null?void 0:E.wrap)==="char"?J=zs($,"char",e.id,{skipTags:E.skipTags}):_&&(E==null?void 0:E.wrap)==="word"&&(J=zs($,"word",e.id,{skipTags:E.skipTags}));let se=null;if(D?(se=document.createElement("div"),se.innerHTML=J,se.style.display="none",U.appendChild(se)):U.innerHTML=J,_&&(E!=null&&E.useCaret)&&!D&&S){let xe=Xa(),Bt=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pe=Bt[Bt.length-1];if(Pe!=null&&Pe.parentNode)Pe.parentNode.insertBefore(xe,Pe.nextSibling);else{let ne=U.lastElementChild;ne?ne.appendChild(xe):U.appendChild(xe)}}if(p&&g==="inline"&&e.createdAt){let xe=mu(e,l);xe.classList.add("persona-ml-2","persona-inline"),U.appendChild(xe)}if(M.length>0){let xe=Wg(M,!D&&!!S,()=>{D&&se&&(se.style.display="")});xe?x.appendChild(xe):D&&se&&(se.style.display="")}let Ie=Lg(e);if(Ie.length>0){let xe=Rg(Ie);xe&&x.appendChild(xe)}let Le=Pg(e);if(Le.length>0){let xe=Hg(Le);xe&&x.appendChild(xe)}let Qe=Ig(e);if(Qe.length>0){let xe=Bg(Qe);xe&&x.appendChild(xe)}if(x.appendChild(U),p&&g==="below"&&e.createdAt){let xe=mu(e,l);xe.classList.add("persona-mt-1"),x.appendChild(xe)}let pe=e.role==="assistant"?Eg(e.stopReason,(Ee=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.copy)==null?void 0:Ee.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let xe=!!(R&&R.trim()),Bt=N.placeholder==="skeleton",Pe=Bt&&N.buffer==="line"&&xe;if(xe)Pe&&x.appendChild(Vs());else if(Bt)x.appendChild(Vs());else{let ne=Qi("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ne&&x.appendChild(ne)}}if(pe&&e.stopReason&&!e.streaming&&(S||(U.style.display="none"),x.appendChild(Tg(e.stopReason,pe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let xe=Xi(e,r,o);x.appendChild(xe)}if(!u||e.role==="system")return x;let ke=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),je=Dg(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ke.append(x,je):ke.append(je,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ke},fu=(e,n,t,r,o,s)=>{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}):as(e,n,t,r,o,s)};var is=new Set,Fg=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Og=(e,n)=>{var r,o;let t=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,n).join(`
17
- `):""},hu=(e,n)=>{let t=is.has(e),r=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".persona-border-t"),s=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},Yi=(e,n)=>{var Le,Qe,pe,ue,ke,je,te,Se,X,ie,He;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let o=(Qe=(Le=n==null?void 0:n.features)==null?void 0:Le.reasoningDisplay)!=null?Qe:{},s=o.expandable!==!1,a=s&&is.has(e.id),i=t.status!=="complete",d=Og(e,(pe=o.previewMaxLines)!=null?pe:3),l=h("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(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 de=h("span","");return de.setAttribute("data-tool-elapsed",w),de.textContent=Ta(t),de},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 S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=Pp(t),u.appendChild(S);let L=(te=o.loadingAnimation)!=null?te:"none",D=g.activeTextTemplate,N=g.completeTextTemplate,P=i?D:N,E=M instanceof HTMLElement,O=(de,Re,et)=>{let K=et;for(let ae of Re){let Oe=h("span","persona-tool-char");Oe.style.setProperty("--char-index",String(K)),Oe.textContent=ae===" "?"\xA0":ae,de.appendChild(Oe),K++}return K},_=(de,Re)=>{p.textContent="";let et=Ma(de,""),K=0;for(let ae of et){let Oe=ae.styles.length>0?(()=>{let G=h("span",ae.styles.map(V=>`persona-tool-text-${V}`).join(" "));return p.appendChild(G),G})():p;if(ae.isDuration&&i)Oe.appendChild(x());else{let G=ae.isDuration?Ta(t):ae.text;Re?K=O(Oe,G,K):Oe.appendChild(document.createTextNode(G))}}};if(!E&&P)if(S.style.display="none",p.style.display="",i&&L!=="none"){let de=(Se=g.loadingAnimationDuration)!=null?Se:2e3;p.setAttribute("data-preserve-animation","true"),L==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`),_(P,!1)):(p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`),L==="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)),_(P,!0))}else _(P,!1);else if(!E&&i&&L!=="none"){p.style.display="";let de=(X=g.loadingAnimationDuration)!=null?X:2e3;if(p.setAttribute("data-preserve-animation","true"),L==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`),L==="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 Re=p.textContent||f;p.textContent="",O(p,Re,0)}t.status==="complete"&&(p.style.display="none")}else E||(t.status==="complete"?p.style.display="none":p.style.display="");let U=null;if(s){U=h("div","persona-flex persona-items-center");let Re=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?U.appendChild(Re):U.textContent=a?"Hide":"Show";let et=h("div","persona-flex persona-items-center persona-ml-auto");et.append(U),l.append(u,et)}else l.append(u);let R=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let de=(He=(ie=n==null?void 0:n.reasoning)==null?void 0:ie.renderCollapsedPreview)==null?void 0:He.call(ie,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});Fg(R,de)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,R),r;let $=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=a?"":"none";let J=t.chunks.join(""),se=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return se.textContent=J||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(se),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let Re=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?U.appendChild(Re):U.textContent=a?"Hide":"Show"}$.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(l,R,$),r};var ls=new Set,$g=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),_g=(e,n)=>{var s;let t=e.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
16
+ `,t.addEventListener("click",n);let r=s=>{var D,N,P,E,O,_,U,R,$,J,se,Ie,ke,Qe;let a=(D=s.launcher)!=null?D:{},i=nn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let ge=(N=a.title)!=null?N:"Chat Assistant";d.textContent=ge,d.setAttribute("title",ge)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let ge=(P=a.subtitle)!=null?P:"Get answers fast";l.textContent=ge,l.setAttribute("title",ge)}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 ge=(E=a.agentIconSize)!=null?E:"40px";if(p.style.height=ge,p.style.width=ge,p.innerHTML="",a.agentIconName){let pe=parseFloat(ge)||24,Le=me(a.agentIconName,pe*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(p.appendChild(Le),p.style.display=""):(p.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(_=a.agentIconText)!=null?_:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ge=(U=a.agentIconSize)!=null?U:"40px";f.style.height=ge,f.style.width=ge,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 ge=(R=a.callToActionIconSize)!=null?R:"32px";g.style.height=ge,g.style.width=ge,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 pe=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,pe=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Le=parseFloat(ge)||24,qe=Math.max(Le-pe,8),te=me(a.callToActionIconName,qe,"currentColor",2);te?g.appendChild(te):g.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else g.textContent=(J=a.callToActionIconText)!=null?J:"\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",k="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?k:`${x} ${w}`,i||(t.style.zIndex=String((se=a.zIndex)!=null?se:hn));let S="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Ie=a.border)!=null?Ie:S,t.style.boxShadow=(ke=a.shadow)!=null?ke:L,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=(Qe=a.collapsedMaxWidth)!=null?Qe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:o}};var vg="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Za=(e,n={})=>{var x,k,S,L,D,N;let{showClose:t=!0,wrapperClassName:r=vg,buttonSize:o,iconSize:s="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(k=o!=null?o:a.closeButtonSize)!=null?k:"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=(S=a.closeButtonTooltipText)!=null?S:"Close chat",p=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(D=a.closeButtonIconName)!=null?D:"x",g=(N=a.closeButtonIconText)!=null?N:"\xD7";l.style.color=a.closeButtonColor||Sn.actionIconColor;let w=me(f,s,"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 P=a.closeButtonBorderWidth||"0px",E=a.closeButtonBorderColor||"transparent";l.style.border=`${P} solid ${E}`,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 P=null,E=()=>{if(P)return;let _=l.ownerDocument,U=_.body;if(!U)return;P=xr(_,"div","persona-clear-chat-tooltip"),P.textContent=u;let R=xr(_,"div");R.className="persona-clear-chat-tooltip-arrow",P.appendChild(R);let $=l.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(ro),P.style.left=`${$.left+$.width/2}px`,P.style.top=`${$.top-8}px`,P.style.transform="translate(-50%, -100%)",U.appendChild(P)},O=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};d.addEventListener("mouseenter",E),d.addEventListener("mouseleave",O),l.addEventListener("focus",E),l.addEventListener("blur",O),d._cleanupTooltip=()=>{O(),d.removeEventListener("mouseenter",E),d.removeEventListener("mouseleave",O),l.removeEventListener("focus",E),l.removeEventListener("blur",O)}}return{button:l,wrapper:d}},Cg="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ei=(e,n={})=>{var P,E,O,_,U,R,$,J,se,Ie,ke,Qe,ge;let{wrapperClassName:t=Cg,buttonSize:r,iconSize:o="20px"}=n,a=(E=((P=e==null?void 0:e.launcher)!=null?P:{}).clearChat)!=null?E:{},i=(O=r!=null?r:a.size)!=null?O:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",l=(U=a.iconColor)!=null?U:"",u=(R=a.backgroundColor)!=null?R:"",p=($=a.borderWidth)!=null?$:"",f=(J=a.borderColor)!=null?J:"",g=(se=a.borderRadius)!=null?se:"",w=(Ie=a.paddingX)!=null?Ie:"",x=(ke=a.paddingY)!=null?ke:"",k=(Qe=a.tooltipText)!=null?Qe:"Clear chat",S=(ge=a.showTooltip)!=null?ge:!0,L=h("div",t),D=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");D.style.height=i,D.style.width=i,D.type="button",D.setAttribute("aria-label",k),D.style.color=l||Sn.actionIconColor;let N=me(d,o,"currentColor",1);if(N&&(N.style.display="block",D.appendChild(N)),u&&(D.style.backgroundColor=u,D.classList.remove("hover:persona-bg-gray-100")),p||f){let pe=p||"0px",Le=f||"transparent";D.style.border=`${pe} solid ${Le}`,D.classList.remove("persona-border-none")}if(g&&(D.style.borderRadius=g,D.classList.remove("persona-rounded-full")),w&&(D.style.paddingLeft=w,D.style.paddingRight=w),x&&(D.style.paddingTop=x,D.style.paddingBottom=x),L.appendChild(D),S&&k){let pe=null,Le=()=>{if(pe)return;let te=D.ownerDocument,Se=te.body;if(!Se)return;pe=xr(te,"div","persona-clear-chat-tooltip"),pe.textContent=k;let X=xr(te,"div");X.className="persona-clear-chat-tooltip-arrow",pe.appendChild(X);let ie=D.getBoundingClientRect();pe.style.position="fixed",pe.style.zIndex=String(ro),pe.style.left=`${ie.left+ie.width/2}px`,pe.style.top=`${ie.top-8}px`,pe.style.transform="translate(-50%, -100%)",Se.appendChild(pe)},qe=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};L.addEventListener("mouseenter",Le),L.addEventListener("mouseleave",qe),D.addEventListener("focus",Le),D.addEventListener("blur",qe),L._cleanupTooltip=()=>{qe(),L.removeEventListener("mouseenter",Le),L.removeEventListener("mouseleave",qe),D.removeEventListener("focus",Le),D.removeEventListener("blur",qe)}}return{button:D,wrapper:L}};var Sn={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))"},Dr=e=>{var P,E,O,_,U,R,$,J,se,Ie,ke,Qe,ge,pe,Le,qe;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 o=(P=n==null?void 0:n.launcher)!=null?P:{},s=(E=o.headerIconSize)!=null?E:"48px",a=(O=o.closeButtonPlacement)!=null?O:"inline",i=(_=o.headerIconHidden)!=null?_:!1,d=o.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,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(s)||24,Se=me(d,te*.6,"currentColor",1);Se?l.replaceChildren(Se):l.textContent=(R=(U=n==null?void 0:n.launcher)==null?void 0:U.agentIconText)!=null?R:"\u{1F4AC}"}else if(($=n==null?void 0:n.launcher)!=null&&$.iconUrl){let te=h("img");te.src=n.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=s,te.style.width=s,l.replaceChildren(te)}else l.textContent=(se=(J=n==null?void 0:n.launcher)==null?void 0:J.agentIconText)!=null?se:"\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=Sn.titleColor,p.textContent=(ke=(Ie=n==null?void 0:n.launcher)==null?void 0:Ie.title)!=null?ke:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Sn.subtitleColor,f.textContent=(ge=(Qe=n==null?void 0:n.launcher)==null?void 0:Qe.subtitle)!=null?ge:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let g=(pe=o.clearChat)!=null?pe:{},w=(Le=g.enabled)!=null?Le:!0,x=(qe=g.placement)!=null?qe:"inline",k=null,S=null;if(w){let Se=ei(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=Se.button,S=Se.wrapper,x==="top-right"&&(S.style.right="48px"),x==="inline"&&r.appendChild(S)}let L=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:D,wrapper:N}=Za(n,{showClose:t,wrapperClassName:L});return a!=="top-right"&&r.appendChild(N),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:D,closeButtonWrapper:N,clearChatButton:k,clearChatButtonWrapper:S}},Do=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function ao(e){let{items:n,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(ro)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of n){if(g.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}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 k=me(g.icon,16,"currentColor",1.5);k&&w.appendChild(k)}let x=document.createElement("span");x.textContent=g.label,w.appendChild(x),w.addEventListener("click",k=>{k.stopPropagation(),u(),t(g.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="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 s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function jt(e){let{icon:n,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=me(n,r!=null?r:16,"currentColor",o!=null?o: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 Gs(e){let{icon:n,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=me(n,s!=null?s: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 Qs(e){let{items:n,selectedId:t,onSelect:r,className:o}=e,s=h("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=jt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),s.appendChild(p)}function l(u){a=u,d()}return{element:s,setSelected:l}}function ti(e){var g,w;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="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=me(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,k;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(k=d.border)!=null?k:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=ao({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let k=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",k?"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=Dr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=n.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return n};function wg(e,n,t){var r,o,s;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",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=h("div","persona-relative");d.appendChild(i);let l=ao({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 L,D,N,P,E,O,_,U,R;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=n==null?void 0:n.launcher)!=null?L:{},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=o==null?void 0:o.titleMenu,l,u;if(d)l=ti({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Sn.titleColor,u=(N=l.querySelector(".persona-combo-btn-label"))!=null?N:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Sn.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(u),wg(l,o==null?void 0:o.trailingActions,(E=o==null?void 0:o.onAction)!=null?E:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let J=o.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||J()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),J())})}let $=o==null?void 0:o.titleRowHover;$&&(l.style.borderRadius=(O=$.borderRadius)!=null?O:"10px",l.style.padding=(_=$.padding)!=null?_:"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 J,se;l.style.backgroundColor=(J=$.background)!=null?J:"",l.style.borderColor=(se=$.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(U=a.closeButtonSize)!=null?U:"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||Sn.actionIconColor;let w=(R=a.closeButtonIconName)!=null?R:"x",x=me(w,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let k=h("div");k.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:k,headerTitle:u,headerSubtitle:S,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},os=(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",s=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&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};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 o=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,o());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:s}},oi=e=>{var P,E,O,_,U,R,$,J,se,Ie,ke,Qe;let n=(P=e==null?void 0:e.sendButton)!=null?P:{},t=(E=n.useIcon)!=null?E:!1,r=(O=n.iconText)!=null?O:"\u2191",o=n.iconName,s=(_=n.stopIconName)!=null?_:"square",a=(U=n.tooltipText)!=null?U:"Send message",i=(R=n.stopTooltipText)!=null?R:"Stop generating",d=(J=($=e==null?void 0:e.copy)==null?void 0:$.sendButtonLabel)!=null?J:"Send",l=(Ie=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?Ie:"Stop",u=(ke=n.showTooltip)!=null?ke:!1,p=(Qe=n.size)!=null?Qe:"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 k=null,S=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 ge=parseFloat(p)||24,pe=(g==null?void 0:g.trim())||"currentColor";o?(k=me(o,ge,pe,2),k?x.appendChild(k):x.textContent=r):x.textContent=r,S=me(s,ge,pe,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 L=null;u&&a&&(L=h("div","persona-send-button-tooltip"),L.textContent=a,w.appendChild(L)),x.setAttribute("aria-label",a),w.appendChild(x);let D="send";return{button:x,wrapper:w,setMode:ge=>{if(ge===D)return;D=ge;let pe=ge==="stop"?i:a;if(x.setAttribute("aria-label",pe),L&&(L.textContent=pe),t){if(k&&S){let Le=ge==="stop"?S:k;x.replaceChildren(Le)}}else x.textContent=ge==="stop"?l:d}}},si=e=>{var L,D,N,P,E,O,_,U,R,$,J,se;let n=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((D=n.provider)==null?void 0:D.type)==="runtype";if(!(r||o))return null;let a=(P=(N=e==null?void 0:e.sendButton)==null?void 0:N.size)!=null?P:"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=(E=n.iconName)!=null?E:"mic",u=(O=n.iconSize)!=null?O:a,p=parseFloat(u)||24,f=(U=n.backgroundColor)!=null?U:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,g=($=n.iconColor)!=null?$:(R=e==null?void 0:e.sendButton)==null?void 0:R.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=me(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 k=(J=n.tooltipText)!=null?J:"Start voice recognition";if(((se=n.showTooltip)!=null?se:!1)&&k){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=k,i.appendChild(Ie)}return{button:d,wrapper:i}},ai=e=>{var w,x,k,S,L,D,N,P;let n=(w=e==null?void 0:e.attachments)!=null?w:{};if(n.enabled!==!0)return null;let t=(k=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?k:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let o=h("input");o.type="file",o.accept=((S=n.allowedTypes)!=null?S:Br).join(","),o.multiple=((L=n.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=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",(D=n.buttonTooltipText)!=null?D:"Attach file");let i=(N=n.buttonIconName)!=null?N:"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=me(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",E=>{E.preventDefault(),o.click()}),s.appendChild(a);let f=(P=n.buttonTooltipText)!=null?P:"Attach file",g=h("div","persona-send-button-tooltip");return g.textContent=f,s.appendChild(g),{button:a,wrapper:s,input:o,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 o=(i=n.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(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=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},li=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ss=e=>{var w,x,k,S,L,D;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(),o=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");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=ri(n);a();let i=oi(n),d=si(n),l=ai(n),u=ii(n);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);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),o.append(p),o.addEventListener("click",N=>{N.target!==i.button&&N.target!==i.wrapper&&N.target!==(d==null?void 0:d.button)&&N.target!==(d==null?void 0:d.wrapper)&&N.target!==(l==null?void 0:l.button)&&N.target!==(l==null?void 0:l.wrapper)&&s.focus()}),t.append(r,o,u),{footer:t,suggestions:r,composerForm:o,textarea:s,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:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var cu=()=>{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=me("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),o=h("span","persona-pill-peek__caret"),s=me("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(n,r,o),{root:e,textNode:r}},du=e=>{var w,x,k,S,L,D;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 o=ii(n);o.style.display="none";let{textarea:s,attachAutoResize:a}=ri(n);s.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",N=>{N.target!==i.button&&N.target!==i.wrapper&&N.target!==(d==null?void 0:d.button)&&N.target!==(d==null?void 0:d.wrapper)&&N.target!==(l==null?void 0:l.button)&&N.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(p,s,f),l&&t.append(l.previewsContainer),t.append(u,r,o);let g=u;return{footer:t,suggestions:r,composerForm:u,textarea:s,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:o,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var pu=e=>{var u,p,f,g,w,x,k,S,L,D,N,P,E,O,_,U,R;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=nn(e);if(so(e)){let $=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},J=h("div","persona-widget-wrapper persona-fixed persona-transition");J.setAttribute("data-persona-composer-bar",""),J.dataset.state="collapsed",J.dataset.expandedSize=(w=$.expandedSize)!=null?w:"anchored",J.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let se=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",J.appendChild(se);let Ie=h("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(S=$.expandedSize)!=null?S:"anchored",Ie.style.zIndex=String((D=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?D:hn),{wrapper:J,panel:se,pillRoot:Ie}}if(t){let $=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),J=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return $.appendChild(J),{wrapper:$,panel:J}}if(!n){let $=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),J=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(P=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?P:"100%";return $.style.width=se,J.style.width="100%",$.appendChild(J),{wrapper:$,panel:J}}let o=(E=e==null?void 0:e.launcher)!=null?E:{},s=o.position&&dr[o.position]?dr[o.position]:dr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((_=(O=e==null?void 0:e.launcher)==null?void 0:O.zIndex)!=null?_:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(U=e==null?void 0:e.launcher)==null?void 0:U.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:Un;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ag=(e,n)=>{var N,P,E,O,_,U,R,$,J;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:o}=Za(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(E=(P=(N=e==null?void 0:e.launcher)==null?void 0:N.clearChat)==null?void 0:P.enabled)!=null?E:!0,a=null,i=null;if(s){let se=ei(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.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=(_=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeTitle)!=null?_:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(R=(U=e==null?void 0:e.copy)==null?void 0:U.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",u.append(p,f);let g=h("div","persona-flex persona-flex-col persona-gap-3"),w=($=e==null?void 0:e.layout)==null?void 0:$.contentMaxWidth;w&&(g.style.maxWidth=w,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((J=e==null?void 0:e.copy)==null?void 0:J.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let k=h("div","persona-composer-overlay persona-pointer-events-none");k.setAttribute("data-persona-composer-overlay",""),k.style.position="absolute",k.style.left="0",k.style.right="0",k.style.bottom="0",k.style.zIndex="20";let S=du({config:e}),{root:L,textNode:D}=cu();return t.append(d,o,l,k),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:g,composerOverlay:k,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode,peekBanner:L,peekTextNode:D}},uu=(e,n=!0)=>{var k,S,L,D,N,P,E,O,_;if(so(e))return Ag(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=(k=e==null?void 0:e.layout)==null?void 0:k.header,o=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,s=r?os(e,r,{showClose:n}):Dr({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=(D=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?D:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(P=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(E=e==null?void 0:e.layout)==null?void 0:E.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=ss({config:e}),w=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;o?Do(t,s,e):(s.header.style.display="none",Do(t,s,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:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.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 Sg=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}},Eg=(e,n)=>{if(!e)return null;let t=Sg(e);if(t===null)return null;let r=n==null?void 0:n[e],o=r!==void 0?r:t;return o||null},Tg=(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},Mg=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Ki=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},Gi=320,gu=320,kg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Lg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),Pg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),Ig=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),Wg=(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 o=0,s=!1,a=()=>{s||(s=!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=`${Gi}px`,l.style.maxHeight=`${gu}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;o+=1,l.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{u=!0}),Mg(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},Rg=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!Ki(r.audio))return;let o=h("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Gi}px`,n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Hg=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!Ki(r.video))return;let o=h("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Gi}px`,o.style.maxHeight=`${gu}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Bg=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!Ki(r.data))return;let o=h("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return 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 o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(o),e},Qi=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:No};if(n){let o=n(r);if(o!==null)return o}return No()},Dg=(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 o=h("img");o.src=r,o.alt=n==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(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},mu=(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},Ng=(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},Xi=(e,n,t)=>{var g,w,x,k,S,L;let r=(g=n.showCopy)!=null?g:!0,o=(w=n.showUpvote)!=null?w:!0,s=(x=n.showDownvote)!=null?x:!0;if(!r&&!o&&!s){let D=h("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let a=(k=n.visibility)!=null?k:"hover",i=(S=n.align)!=null?S:"right",d=(L=n.layout)!=null?L:"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=(D,N,P)=>{let E=jt({icon:D,label:N,size:14,className:"persona-message-action-btn"});return E.setAttribute("data-action",P),E};return r&&p.appendChild(f("copy","Copy message","copy")),o&&p.appendChild(f("thumbs-up","Upvote","upvote")),s&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},as=(e,n,t,r,o,s)=>{var te,Se,X,ie,He,de,Re,et,K,ae,Oe,G,V,ve,$e,re,Ee;let a=t!=null?t:{},i=(te=a.layout)!=null?te:"bubble",d=a.avatar,l=a.timestamp,u=(Se=d==null?void 0:d.show)!=null?Se:!1,p=(X=l==null?void 0:l.show)!=null?X:!1,f=(ie=d==null?void 0:d.position)!=null?ie:"left",g=(He=l==null?void 0:l.position)!=null?He:"below",w=Ng(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 k=kg(e),S=(Re=(de=e.content)==null?void 0:de.trim())!=null?Re:"",D=k.length>0&&S===Ha,N=Ga((K=(et=s==null?void 0:s.widgetConfig)==null?void 0:et.features)==null?void 0:K.streamAnimation),P=(G=(Oe=(ae=s==null?void 0:s.widgetConfig)==null?void 0:ae.features)==null?void 0:Oe.streamAnimation)==null?void 0:G.plugins,E=e.role==="assistant"&&N.type!=="none"?qs(N.type,P):null,O=e.role==="assistant"&&((V=E==null?void 0:E.isAnimating)==null?void 0:V.call(E,e))===!0,_=e.role==="assistant"&&E!==null&&(!!e.streaming||O);_&&(E!=null&&E.bubbleClass)&&x.classList.add(E.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),_&&E&&(E.containerClass&&U.classList.add(E.containerClass),U.style.setProperty("--persona-stream-step",`${N.speed}ms`),U.style.setProperty("--persona-stream-duration",`${N.duration}ms`));let R=_?Qa((ve=e.content)!=null?ve:"",N.buffer,E,e,!!e.streaming):($e=e.content)!=null?$e:"",$=n({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),J=$;_&&(E==null?void 0:E.wrap)==="char"?J=zs($,"char",e.id,{skipTags:E.skipTags}):_&&(E==null?void 0:E.wrap)==="word"&&(J=zs($,"word",e.id,{skipTags:E.skipTags}));let se=null;if(D?(se=document.createElement("div"),se.innerHTML=J,se.style.display="none",U.appendChild(se)):U.innerHTML=J,_&&(E!=null&&E.useCaret)&&!D&&S){let xe=Xa(),Bt=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pe=Bt[Bt.length-1];if(Pe!=null&&Pe.parentNode)Pe.parentNode.insertBefore(xe,Pe.nextSibling);else{let ne=U.lastElementChild;ne?ne.appendChild(xe):U.appendChild(xe)}}if(p&&g==="inline"&&e.createdAt){let xe=mu(e,l);xe.classList.add("persona-ml-2","persona-inline"),U.appendChild(xe)}if(k.length>0){let xe=Wg(k,!D&&!!S,()=>{D&&se&&(se.style.display="")});xe?x.appendChild(xe):D&&se&&(se.style.display="")}let Ie=Lg(e);if(Ie.length>0){let xe=Rg(Ie);xe&&x.appendChild(xe)}let ke=Pg(e);if(ke.length>0){let xe=Hg(ke);xe&&x.appendChild(xe)}let Qe=Ig(e);if(Qe.length>0){let xe=Bg(Qe);xe&&x.appendChild(xe)}if(x.appendChild(U),p&&g==="below"&&e.createdAt){let xe=mu(e,l);xe.classList.add("persona-mt-1"),x.appendChild(xe)}let ge=e.role==="assistant"?Eg(e.stopReason,(Ee=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.copy)==null?void 0:Ee.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let xe=!!(R&&R.trim()),Bt=N.placeholder==="skeleton",Pe=Bt&&N.buffer==="line"&&xe;if(xe)Pe&&x.appendChild(Vs());else if(Bt)x.appendChild(Vs());else{let ne=Qi("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ne&&x.appendChild(ne)}}if(ge&&e.stopReason&&!e.streaming&&(S||(U.style.display="none"),x.appendChild(Tg(e.stopReason,ge))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let xe=Xi(e,r,o);x.appendChild(xe)}if(!u||e.role==="system")return x;let Le=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),qe=Dg(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Le.append(x,qe):Le.append(qe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},fu=(e,n,t,r,o,s)=>{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}):as(e,n,t,r,o,s)};var is=new Set,Fg=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Og=(e,n)=>{var r,o;let t=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,n).join(`
17
+ `):""},hu=(e,n)=>{let t=is.has(e),r=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".persona-border-t"),s=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=me(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},Yi=(e,n)=>{var ke,Qe,ge,pe,Le,qe,te,Se,X,ie,He;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let o=(Qe=(ke=n==null?void 0:n.features)==null?void 0:ke.reasoningDisplay)!=null?Qe:{},s=o.expandable!==!1,a=s&&is.has(e.id),i=t.status!=="complete",d=Og(e,(ge=o.previewMaxLines)!=null?ge:3),l=h("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(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=(pe=n==null?void 0:n.reasoning)!=null?pe:{},w=String((Le=t.startedAt)!=null?Le:Date.now()),x=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",w),de.textContent=Ta(t),de},k=(qe=g.renderCollapsedSummary)==null?void 0:qe.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:Ta(t),createElapsedElement:x});typeof k=="string"&&k.trim()?(p.textContent=k,u.appendChild(p)):k instanceof HTMLElement?u.appendChild(k):(p.textContent=f,u.appendChild(p));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=Pp(t),u.appendChild(S);let L=(te=o.loadingAnimation)!=null?te:"none",D=g.activeTextTemplate,N=g.completeTextTemplate,P=i?D:N,E=k instanceof HTMLElement,O=(de,Re,et)=>{let K=et;for(let ae of Re){let Oe=h("span","persona-tool-char");Oe.style.setProperty("--char-index",String(K)),Oe.textContent=ae===" "?"\xA0":ae,de.appendChild(Oe),K++}return K},_=(de,Re)=>{p.textContent="";let et=Ma(de,""),K=0;for(let ae of et){let Oe=ae.styles.length>0?(()=>{let G=h("span",ae.styles.map(V=>`persona-tool-text-${V}`).join(" "));return p.appendChild(G),G})():p;if(ae.isDuration&&i)Oe.appendChild(x());else{let G=ae.isDuration?Ta(t):ae.text;Re?K=O(Oe,G,K):Oe.appendChild(document.createTextNode(G))}}};if(!E&&P)if(S.style.display="none",p.style.display="",i&&L!=="none"){let de=(Se=g.loadingAnimationDuration)!=null?Se:2e3;p.setAttribute("data-preserve-animation","true"),L==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`),_(P,!1)):(p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`),L==="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)),_(P,!0))}else _(P,!1);else if(!E&&i&&L!=="none"){p.style.display="";let de=(X=g.loadingAnimationDuration)!=null?X:2e3;if(p.setAttribute("data-preserve-animation","true"),L==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${de}ms`),L==="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 Re=p.textContent||f;p.textContent="",O(p,Re,0)}t.status==="complete"&&(p.style.display="none")}else E||(t.status==="complete"?p.style.display="none":p.style.display="");let U=null;if(s){U=h("div","persona-flex persona-items-center");let Re=me(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?U.appendChild(Re):U.textContent=a?"Hide":"Show";let et=h("div","persona-flex persona-items-center persona-ml-auto");et.append(U),l.append(u,et)}else l.append(u);let R=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let de=(He=(ie=n==null?void 0:n.reasoning)==null?void 0:ie.renderCollapsedPreview)==null?void 0:He.call(ie,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});Fg(R,de)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,R),r;let $=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=a?"":"none";let J=t.chunks.join(""),se=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return se.textContent=J||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(se),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let Re=me(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?U.appendChild(Re):U.textContent=a?"Hide":"Show"}$.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(l,R,$),r};var ls=new Set,$g=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),_g=(e,n)=>{var s;let t=e.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
18
18
  `);let o=Yo(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
19
- `):""},jg=(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,o=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",s=_g(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?Ip(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(g=n==null?void 0:n.toolCall)!=null?g:{},l=a;return o==="tool-name"?l=((w=t.name)==null?void 0:w.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Ri(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ri(t,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},yu=(e,n,t)=>{var u;let r=ls.has(e),o=(u=t==null?void 0:t.toolCall)!=null?u:{},s=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=o.toggleTextColor||o.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")},Zi=(e,n)=>{var J,se,Ie,Le,Qe,pe,ue,ke,je;let t=e.toolCall,r=(J=n==null?void 0:n.toolCall)!=null?J:{},o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),!t)return o;let s=(Ie=(se=n==null?void 0:n.features)==null?void 0:se.toolCallDisplay)!=null?Ie:{},a=s.expandable!==!1,i=a&&ls.has(e.id),{summary:d,previewText:l,isActive:u}=jg(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((Le=t.startedAt)!=null?Le:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",w),te.textContent=Hs(t),te},M=(pe=r.renderCollapsedSummary)==null?void 0:pe.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Qe=s.collapsedMode)!=null?Qe:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Hs(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 S=(ue=s.loadingAnimation)!=null?ue:"none",L=r.activeTextTemplate,D=r.completeTextTemplate,N=u?L:D,P=M instanceof HTMLElement,E=(te,Se,X)=>{let ie=X;for(let He of Se){let de=h("span","persona-tool-char");de.style.setProperty("--char-index",String(ie)),de.textContent=He===" "?"\xA0":He,te.appendChild(de),ie++}return ie},O=(te,Se)=>{var de;g.textContent="";let X=((de=t.name)==null?void 0:de.trim())||"tool",ie=Ma(te,X),He=0;for(let Re of ie){let et=Re.styles.length>0?(()=>{let K=h("span",Re.styles.map(ae=>`persona-tool-text-${ae}`).join(" "));return g.appendChild(K),K})():g;if(Re.isDuration&&u)et.appendChild(x());else{let K=Re.isDuration?Hs(t):Re.text;Se?He=E(et,K,He):et.appendChild(document.createTextNode(K))}}};if(!P)if(u&&S!=="none"){let te=(ke=r.loadingAnimationDuration)!=null?ke:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),N&&O(N,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),S==="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)),N)O(N,!0);else{let Se=g.textContent||d;g.textContent="",E(g,Se,0)}}else N&&O(N,!1);let _=null;if(a){_=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",Se=ge(i?"chevron-up":"chevron-down",16,te,2);Se?_.appendChild(Se):_.textContent=i?"Hide":"Show";let X=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(_),p.append(f,X)}else p.append(f);let U=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&u&&s.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:{}});$g(U,te)||(U.textContent=l),U.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(p,U),o;let R=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.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,R.appendChild(te)}if(t.args!==void 0){let te=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Se.style.color=r.labelTextColor),Se.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=Yo(t.args),te.append(Se,X),R.appendChild(te)}if(t.chunks&&t.chunks.length){let te=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Se.style.color=r.labelTextColor),Se.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(Se,X),R.appendChild(te)}if(t.status==="complete"&&t.result!==void 0){let te=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Se.style.color=r.labelTextColor),Se.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=Yo(t.result),te.append(Se,X),R.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`,R.appendChild(te)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",Se=ge(i?"chevron-up":"chevron-down",16,te,2);Se?_.appendChild(Se):_.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(p,U,R),o};var io=require("partial-json");var tl="ask_user_question",el=8,cs="data-persona-ask-sheet-for",Ug="Other",qg="Other\u2026",xu="Type your own answer here",vu="Send",zg="Next",Vg="Back",Jg="Submit all",Kg="Skip",Gg=3,nl="data-ask-current-index",rl="data-ask-question-count",Cu="data-ask-answers",ol="data-ask-grouped",wu="data-ask-layout",Qg=e=>e.layout==="pills"?"pills":"rows",Xg=e=>e.getAttribute(wu)==="pills"?"pills":"rows",bu=!1,Au=e=>e.replace(/["\\]/g,"\\$&"),Nr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===tl,ci=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},Fr=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 o=r.join(""),s=(0,io.parse)(o,io.STR|io.OBJ|io.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Xs=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>el&&!bu&&(bu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${el}.`)),n.slice(0,el)},Yg=e=>{var n;return(n=Xs(e)[0])!=null?n:null},Zg=(e,n)=>{var t;return(t=Xs(e)[n])!=null?t:null},Su=(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))},Eu=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let o=h("span","persona-ask-row-check");r.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},ef=(e,n,t,r)=>{let s=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(n)),s.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)}s.appendChild(a);let d=Eu(t,r,n);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},tf=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},nf=(e,n,t,r)=>{var u,p,f;let s=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");s.setAttribute("role","group"),s.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<Gg;g++)s.appendChild(tf(r));return s}if(d.forEach((g,w)=>{s.appendChild(ef(g,w,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Ug:qg;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:xu,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 S=Eu(r,a,d.length);S&&w.appendChild(S),s.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,s.appendChild(w)}}return s},Tu=(e,n)=>{var s,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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:xu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),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:vu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},rf=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:vu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},of=(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 o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=t.backLabel)!=null?l:Vg,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=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:Kg,a.setAttribute("data-ask-user-action","skip"),s.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:Jg:(f=t.nextLabel)!=null?f:zg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Fo=e=>{let n=e.getAttribute(Cu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Mu=(e,n)=>{e.setAttribute(Cu,JSON.stringify(n))},Yn=e=>{var t;let n=Number((t=e.getAttribute(nl))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},sf=(e,n)=>{e.setAttribute(nl,String(Math.max(0,Math.floor(n))))},ds=e=>{var t;let n=Number((t=e.getAttribute(rl))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},lo=e=>e.getAttribute(ol)==="true",af=(e,n)=>{var o;let t=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},lf=(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}=Fr(n),r=Xs(t),o=Fo(e),s={},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(o,d)&&(s[l]=o[d]))}),s},ku=e=>{let n=Fo(e),t=Yn(e),r=n[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=o.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).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=""},Lu=e=>{if(!lo(e))return;let n=Fo(e),t=Yn(e),r=n[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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}},sl=(e,n,t)=>{let r=ci(t),o=Xg(e),{payload:s,complete:a}=Fr(n),i=lo(e),d=Yn(e),l=ds(e),u=i?Zg(s,d):Yg(s),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 L=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=L,w.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=nf(u,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Tu(r,o))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!M?e.appendChild(rf(r)):(!p||i)&&M&&M.remove(),e.setAttribute("data-multi-select",p?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=of(d,l,r);S?S.replaceWith(L):e.appendChild(L)}else S&&S.remove();ku(e),Lu(e)},cf=(e,n,t)=>{let r=ci(n),o=Qg(r),s=e.toolCall.id,a=Xs(t),i=Math.max(1,a.length),d=i>1,l=af(e,a),u=d?lf(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(cs,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(rl,String(i)),p.setAttribute(nl,String(u)),p.setAttribute(ol,d?"true":"false"),p.setAttribute(wu,o),Mu(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`),Su(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",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),p.appendChild(M),o!=="rows"&&p.appendChild(Tu(r,o)),sl(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},df=(e,n,t)=>{let{payload:r}=Fr(n),o=Math.max(1,Xs(r).length);o>ds(e)&&(e.setAttribute(rl,String(o)),o>1&&!lo(e)&&e.setAttribute(ol,"true")),sl(e,n,t)},Pu=(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);Su(t,r);let o=h("span","persona-ask-stub-label"),{complete:s}=Fr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},ps=(e,n,t)=>{if(!t||!Nr(e)||ci(n).enabled===!1)return;let o=e.toolCall.id;t.querySelectorAll(`[${cs}]`).forEach(l=>{l.getAttribute(cs)!==o&&l.remove()});let a=t.querySelector(`[${cs}="${Au(o)}"]`);if(a){df(a,e,n);return}let{payload:i}=Fr(e),d=cf(e,n,i);t.appendChild(d)},co=(e,n)=>{if(!e)return;let t=n?`[${cs}="${Au(n)}"]`:`[${cs}]`;e.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},al=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),po=(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,Mu(e,t),ku(e),Lu(e)},pi=(e,n,t,r)=>{let o=ds(e),s=Math.max(0,Math.min(o-1,r));sf(e,s),sl(e,n,t)};var il=(e,n)=>{var x,M,S,L,D,N,P,E,O,_,U,R;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(M=r==null?void 0:r.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!t)return s;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)":(S=r==null?void 0:r.titleColor)!=null?S:"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=(L=r==null?void 0:r.title)!=null?L:"Approval Required",f.appendChild(g),!o){let $=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",t.status),t.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):t.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):t.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),f.appendChild($)}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 $=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&&($.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&($.style.color=r.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=Yo(t.parameters),p.appendChild($)}if(o){let $=h("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let J=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");J.type="button",J.style.backgroundColor=(D=r==null?void 0:r.approveButtonColor)!=null?D:"var(--persona-approval-approve-bg, #22c55e)",J.style.color=(N=r==null?void 0:r.approveButtonTextColor)!=null?N:"#ffffff",J.setAttribute("data-approval-action","approve");let se=ge("shield-check",14,(P=r==null?void 0:r.approveButtonTextColor)!=null?P:"#ffffff",2);se&&(se.style.marginRight="4px",J.appendChild(se));let Ie=document.createTextNode((E=r==null?void 0:r.approveLabel)!=null?E:"Approve");J.appendChild(Ie);let Le=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");Le.type="button",Le.style.backgroundColor=(O=r==null?void 0:r.denyButtonColor)!=null?O:"transparent",Le.style.color=(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",Le.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Le.setAttribute("data-approval-action","deny");let Qe=ge("shield-x",14,(U=r==null?void 0:r.denyButtonTextColor)!=null?U:"var(--persona-feedback-error, #dc2626)",2);Qe&&(Qe.style.marginRight="4px",Le.appendChild(Qe));let pe=document.createTextNode((R=r==null?void 0:r.denyLabel)!=null?R:"Deny");Le.appendChild(pe),$.append(J,Le),p.appendChild($)}return a.append(i,p),s.appendChild(a),s};var Iu=e=>{let n=[];return{buttons:n,render:(r,o,s,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(g=>g.role==="user"))return;let u=document.createDocumentFragment(),p=o?o.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",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(g))}),u.appendChild(w),n.push(w)}),e.appendChild(u)}}};var Ys=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 Zs=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 o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,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 o of n)r.put(o)}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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((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 o of n)r.put(o)}catch{}}};function us(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var pf={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)"}},uf={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},mf=["flowName","stepName","reasoningText","text","name","tool","toolName"],gf=100;function ff(e,n){let t={...pf,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return uf}function hf(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function yf(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function bf(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function xf(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 vf(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 Cf(e,n,t){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=n.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:o});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 ll(e,n,t,r,o,s,a,i){var f;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");us(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:()=>s(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var J,se;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 S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(J=r.timestampFormat)!=null?J:"relative";S.textContent=L==="relative"?hf(e.timestamp,t):yf(e.timestamp);let D=null;r.showSequenceNumbers!==!1&&(D=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(n+1));let N=ff(e.type,r.badgeColors),P=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");P.style.backgroundColor=N.bg,P.style.color=N.text,P.style.borderColor=N.text+"50",P.textContent=e.type;let E=(se=r.descriptionFields)!=null?se:mf,O=bf(e.payload,E),_=null;O&&(_=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=O);let U=h("div","persona-flex-1 persona-min-w-0"),R=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"),$=ge("clipboard","12px","currentColor",1.5);return $&&R.appendChild($),R.addEventListener("click",async Ie=>{Ie.stopPropagation(),await xf(vf(e)),R.innerHTML="";let Le=ge("check","12px","currentColor",1.5);Le&&R.appendChild(Le),setTimeout(()=>{R.innerHTML="";let Qe=ge("clipboard","12px","currentColor",1.5);Qe&&R.appendChild(Qe)},1500)}),w.appendChild(x),w.appendChild(S),D&&w.appendChild(D),w.appendChild(P),_&&w.appendChild(_),w.appendChild(U),w.appendChild(R),g.appendChild(w),d&&g.appendChild(Cf(e,a,i)),g}}function Wu(e){var g,w,x,M,S;let{buffer:n,getFullHistory:t,onClose:r,config:o,plugins:s=[]}=e,a=(g=o==null?void 0:o.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=(S=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?S:{},p=s.find(L=>L.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&o){let L=p.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return f();function f(){let L=u.classNames,D=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");us(D,L==null?void 0:L.panel);let N=[],P="",E="",O=null,_=[],U={},R=0,$=Va(),J=0,se=0,Ie=!1,Le=null,Qe=!1,pe=0,ue=new Set,ke=new Map,je="",te="",Se=null,X,ie,He,de,Re;function et(){let I=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),he=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");us(he,L==null?void 0:L.headerBar);let fe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");fe.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 dt=h("div","persona-flex-1");ie=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 ze=h("option","");ze.value="",ze.textContent="All events",ie.appendChild(ze),He=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),He.type="button",He.title="Copy All";let ln=ge("clipboard-copy","12px","currentColor",1.5);ln&&He.appendChild(ln);let At=h("span","persona-text-xs");At.textContent="Copy All",He.appendChild(At),he.appendChild(fe),he.appendChild(X),he.appendChild(dt),he.appendChild(ie),he.appendChild(He);let xt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");us(xt,L==null?void 0:L.searchBar);let kt=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),ut=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");kt&&ut.appendChild(kt),de=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),us(de,L==null?void 0:L.searchInput),de.type="text",de.placeholder="Search event payloads...",Re=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Re.type="button",Re.style.display="none";let Kt=ge("x","12px","currentColor",2);return Kt&&Re.appendChild(Kt),xt.appendChild(ut),xt.appendChild(de),xt.appendChild(Re),I.appendChild(he),I.appendChild(xt),I}let K,ae=s.find(I=>I.renderEventStreamToolbar);if(ae!=null&&ae.renderEventStreamToolbar&&o){let I=ae.renderEventStreamToolbar({config:o,defaultRenderer:()=>et(),eventCount:n.getSize(),filteredCount:0,onFilterChange:he=>{P=he,ne(),Jt()},onSearchChange:he=>{E=he,ne(),Jt()}});K=I!=null?I:et()}else K=et();let Oe=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";let G=h("div","persona-flex-1 persona-min-h-0 persona-relative"),V=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let ve=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");us(ve,L==null?void 0:L.scrollIndicator),ve.style.display="none",ve.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let $e=ge(d,"14px","currentColor",2);$e&&ve.appendChild($e);let re=h("span","");re.textContent=l,ve.appendChild(re);let Ee=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ee.style.display="none",G.appendChild(V),G.appendChild(Ee),G.appendChild(ve),D.setAttribute("tabindex","0"),D.appendChild(K),D.appendChild(Oe),D.appendChild(G);function xe(){let I=n.getAll(),he={};for(let At of I)he[At.type]=(he[At.type]||0)+1;let fe=Object.keys(he).sort(),dt=fe.length!==_.length||!fe.every((At,xt)=>At===_[xt]),ze=!dt&&fe.some(At=>he[At]!==U[At]),Wt=I.length!==Object.values(U).reduce((At,xt)=>At+xt,0);if(!dt&&!ze&&!Wt||(_=fe,U=he,!ie))return;let ln=ie.value;if(ie.options[0].textContent="All events",dt){for(;ie.options.length>1;)ie.remove(1);for(let At of fe){let xt=h("option","");xt.value=At,xt.textContent=`${At} (${he[At]||0})`,ie.appendChild(xt)}ln&&fe.includes(ln)?ie.value=ln:ln&&(ie.value="",P="")}else for(let At=1;At<ie.options.length;At++){let xt=ie.options[At];xt.textContent=`${xt.value} (${he[xt.value]||0})`}}function Bt(){let I=n.getAll();if(P&&(I=I.filter(he=>he.type===P)),E){let he=E.toLowerCase();I=I.filter(fe=>fe.type.toLowerCase().includes(he)||fe.payload.toLowerCase().includes(he))}return I}function Pe(){return P!==""||E!==""}function ne(){R=0,J=0,$.resume(),ve.style.display="none"}function an(I){ue.has(I)?ue.delete(I):ue.add(I),Se=I;let he=V.scrollTop,fe=$.isFollowing();Qe=!0,$.pause(),Jt(),V.scrollTop=he,fe&&$.resume(),Qe=!1}function Ot(){return _s(V,50)}function Jt(){se=Date.now(),Ie=!1,xe();let I=n.getEvictedCount();I>0?(Oe.textContent=`${I.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",N=Bt();let he=N.length,fe=n.getSize()>0;X&&(X.textContent=String(n.getSize())),he===0&&fe&&Pe()?(Ee.textContent=E?`No events matching '${E}'`:"No events matching filter",Ee.style.display="",V.style.display="none"):(Ee.style.display="none",V.style.display=""),He&&(He.title=Pe()?`Copy Filtered (${he})`:"Copy All"),i&&!$.isFollowing()&&he>R&&(J+=he-R,re.textContent=l?`${l}${J>0?` (${J})`:""}`:"",ve.style.display=""),R=he;let dt=n.getAll(),ze=dt.length>0?dt[0].timestamp:0,Wt=new Set(N.map(xt=>xt.id));for(let xt of ue)Wt.has(xt)||ue.delete(xt);let ln=P!==je||E!==te,At=ke.size===0&&N.length>0;if(ln||At||N.length===0){V.innerHTML="",ke.clear();let xt=document.createDocumentFragment();for(let kt=0;kt<N.length;kt++){let ut=ll(N[kt],kt,ze,u,ue,an,s,o);ke.set(N[kt].id,ut),xt.appendChild(ut)}V.appendChild(xt),je=P,te=E,Se=null}else{if(Se!==null){let kt=ke.get(Se);if(kt&&kt.parentNode===V){let ut=N.findIndex(Kt=>Kt.id===Se);if(ut>=0){let Kt=ll(N[ut],ut,ze,u,ue,an,s,o);V.insertBefore(Kt,kt),kt.remove(),ke.set(Se,Kt)}}Se=null}let xt=new Set(N.map(kt=>kt.id));for(let[kt,ut]of ke)xt.has(kt)||(ut.remove(),ke.delete(kt));for(let kt=0;kt<N.length;kt++){let ut=N[kt];if(!ke.has(ut.id)){let Kt=ll(ut,kt,ze,u,ue,an,s,o);ke.set(ut.id,Kt),V.appendChild(Kt)}}}$.isFollowing()&&(V.scrollTop=V.scrollHeight)}function Cr(){if(Date.now()-se>=gf){Le!==null&&(cancelAnimationFrame(Le),Le=null),Jt();return}Ie||(Ie=!0,Le=requestAnimationFrame(()=>{Le=null,Jt()}))}let pr=(I,he)=>{if(!He)return;He.innerHTML="";let fe=ge(I,"12px","currentColor",1.5);fe&&He.appendChild(fe);let dt=h("span","persona-text-xs");dt.textContent="Copy All",He.appendChild(dt),setTimeout(()=>{He.innerHTML="";let ze=ge("clipboard-copy","12px","currentColor",1.5);ze&&He.appendChild(ze);let Wt=h("span","persona-text-xs");Wt.textContent="Copy All",He.appendChild(Wt),He.disabled=!1},he)},Ue=async()=>{if(He){He.disabled=!0;try{let I;Pe()?I=N:t?(I=await t(),I.length===0&&(I=n.getAll())):I=n.getAll();let he=I.map(fe=>{try{return JSON.parse(fe.payload)}catch{return fe.payload}});await navigator.clipboard.writeText(JSON.stringify(he,null,2)),pr("check",1500)}catch{pr("x",1500)}}},q=()=>{ie&&(P=ie.value,ne(),Jt())},we=()=>{!de||!Re||(Re.style.display=de.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{E=de.value,ne(),Jt()},150))},Be=()=>{!de||!Re||(de.value="",E="",Re.style.display="none",O&&clearTimeout(O),ne(),Jt())},De=()=>{if(Qe)return;let I=V.scrollTop,{action:he,nextLastScrollTop:fe}=Ja({following:$.isFollowing(),currentScrollTop:I,lastScrollTop:pe,nearBottom:Ot(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});pe=fe,he==="resume"?($.resume(),J=0,ve.style.display="none"):he==="pause"&&($.pause(),i&&(re.textContent=l,ve.style.display=""))},_e=I=>{let he=Ka({following:$.isFollowing(),deltaY:I.deltaY,nearBottom:Ot(),resumeWhenNearBottom:!0});he==="pause"?($.pause(),i&&(re.textContent=l,ve.style.display="")):he==="resume"&&($.resume(),J=0,ve.style.display="none")},ct=()=>{i&&(V.scrollTop=V.scrollHeight,$.resume(),J=0,ve.style.display="none")},tt=I=>{let he=I.target;if(!he||he.closest("button"))return;let fe=he.closest("[data-event-id]");if(!fe)return;let dt=fe.getAttribute("data-event-id");dt&&an(dt)},wt=I=>{if((I.metaKey||I.ctrlKey)&&I.key==="f"){I.preventDefault(),de==null||de.focus(),de==null||de.select();return}I.key==="Escape"&&(de&&document.activeElement===de?(Be(),de.blur(),D.focus()):r&&r())};He&&He.addEventListener("click",Ue),ie&&ie.addEventListener("change",q),de&&de.addEventListener("input",we),Re&&Re.addEventListener("click",Be),V.addEventListener("scroll",De),V.addEventListener("wheel",_e,{passive:!0}),V.addEventListener("click",tt),ve.addEventListener("click",ct),D.addEventListener("keydown",wt);function qt(){O&&clearTimeout(O),Le!==null&&(cancelAnimationFrame(Le),Le=null),Ie=!1,ke.clear(),He&&He.removeEventListener("click",Ue),ie&&ie.removeEventListener("change",q),de&&de.removeEventListener("input",we),Re&&Re.removeEventListener("click",Be),V.removeEventListener("scroll",De),V.removeEventListener("wheel",_e),V.removeEventListener("click",tt),ve.removeEventListener("click",ct),D.removeEventListener("keydown",wt)}return{element:D,update:Cr,destroy:qt}}}function Ru(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=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)",o==="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),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Hu=(e,n)=>{var r,o,s;let t=(s=(o=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>Ru(e,n)});if(u)return u}return Ru(e,n)};var cl=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)})}},Or=new cl;Or.register("PersonaArtifactCard",Hu);function wf(e){var o;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((o=e.props)!=null?o:{},null,2),n.appendChild(t),n.appendChild(r),n}function Bu(e,n){var He,de,Re,et;let t=(de=(He=e.features)==null?void 0:He.artifacts)==null?void 0:de.layout,o=((Re=t==null?void 0:t.toolbarPreset)!=null?Re:"default")==="document",s=(et=t==null?void 0:t.panePadding)==null?void 0:et.trim(),a=e.markdown?ko(e.markdown):null,i=Xo(e.sanitize),d=K=>{let ae=a?a(K):Lo(K);return i?i(ae):ae},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"),$==null||$.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"),o&&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"),o&&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"),S=o?jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):jt({icon:"eye",label:"Rendered view"}),L=o?jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):jt({icon:"code-2",label:"Source"}),D=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),N=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,P=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,E=t==null?void 0:t.documentToolbarCopyMenuItems,O=!!(P&&E&&E.length>0),_=null,U,R=null,$=null;if(o&&(N||P)&&!O){if(U=N?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let K=ge("chevron-down",14,"currentColor",2);K&&U.appendChild(K)}}else o&&O?(_=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),U=N?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=jt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),_.append(U,R)):o?U=jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):U=jt({icon:"copy",label:"Copy"});let J=o?jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):jt({icon:"refresh-cw",label:"Refresh"}),se=o?jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):jt({icon:"x",label:"Close"}),Ie=()=>{var V,ve,$e;let K=(V=je.find(re=>re.id===te))!=null?V:je[je.length-1],ae=(ve=K==null?void 0:K.id)!=null?ve:null,Oe=(K==null?void 0:K.artifactType)==="markdown"&&($e=K.markdown)!=null?$e:"",G=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Oe,jsonPayload:G,id:ae}},Le=async()=>{var V;let{markdown:K,jsonPayload:ae}=Ie(),Oe=(V=je.find(ve=>ve.id===te))!=null?V:je[je.length-1],G=(Oe==null?void 0:Oe.artifactType)==="markdown"?K:Oe?ae:"";try{await navigator.clipboard.writeText(G)}catch{}};if(U.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&O){let{markdown:ae,jsonPayload:Oe,id:G}=Ie();try{await K({actionId:"primary",artifactId:G,markdown:ae,jsonPayload:Oe})}catch{}return}await Le()}),R&&(E!=null&&E.length)){let K=()=>{var Oe;return(Oe=p.closest("[data-persona-root]"))!=null?Oe:document.body},ae=()=>{$=ao({items:E.map(Oe=>({id:Oe.id,label:Oe.label})),onSelect:async Oe=>{let{markdown:G,jsonPayload:V,id:ve}=Ie(),$e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:Oe,artifactId:ve,markdown:G,jsonPayload:V}):Oe==="markdown"||Oe==="md"?await navigator.clipboard.writeText(G):Oe==="json"||Oe==="source"?await navigator.clipboard.writeText(V):await navigator.clipboard.writeText(G||V)}catch{}},anchor:_!=null?_:R,position:"bottom-right",portal:K()})};p.isConnected?ae():requestAnimationFrame(ae),R.addEventListener("click",Oe=>{Oe.stopPropagation(),$==null||$.toggle()})}J.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}X()}),se.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let Qe=()=>{o&&(S.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};S.addEventListener("click",()=>{x="rendered",Qe(),X()}),L.addEventListener("click",()=>{x="source",Qe(),X()});let pe=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),M.append(S,L),_?D.append(_,J,se):D.append(U,J,se),f.append(M,pe,D),Qe()):(f.appendChild(g),f.appendChild(w)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);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");s&&(ue.style.paddingLeft=s,ue.style.paddingRight=s,ke.style.padding=s),p.appendChild(f),p.appendChild(ue),p.appendChild(ke);let je=[],te=null,Se=!1,X=()=>{var G,V,ve,$e;let K=o&&je.length<=1;ue.classList.toggle("persona-hidden",K),ue.replaceChildren();for(let re of je){let Ee=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");Ee.type="button",Ee.textContent=re.title||re.id.slice(0,8),re.id===te&&Ee.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ee.addEventListener("click",()=>n.onSelect(re.id)),ue.appendChild(Ee)}ke.replaceChildren();let ae=te&&je.find(re=>re.id===te)||je[je.length-1];if(!ae)return;if(o){let re=ae.artifactType==="markdown"?"MD":(G=ae.component)!=null?G:"Component",xe=(ae.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";pe.textContent=`${xe} \xB7 ${re}`}else g.textContent="Artifacts";if(ae.artifactType==="markdown"){if(o&&x==="source"){let Ee=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ee.textContent=(V=ae.markdown)!=null?V:"",ke.appendChild(Ee);return}let re=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");re.innerHTML=d((ve=ae.markdown)!=null?ve:""),ke.appendChild(re);return}let Oe=ae.component?Or.get(ae.component):void 0;if(Oe){let Ee={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let xe=Oe(($e=ae.props)!=null?$e:{},Ee);if(xe){ke.appendChild(xe);return}}catch{}}ke.appendChild(wf(ae))},ie=()=>{var ae;let K=je.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Oe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,V=((ae=Oe==null?void 0:Oe.classList.contains("persona-artifact-narrow-host"))!=null?ae:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&V&&Se?(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 ae,Oe,G;je=K.artifacts,te=(G=(Oe=K.selectedId)!=null?Oe:(ae=K.artifacts[K.artifacts.length-1])==null?void 0:ae.id)!=null?G:null,je.length>0&&(Se=!0),X(),ie()},setMobileOpen(K){Se=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ie()}}}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 Du(e,n){var s,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=(s=n.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Af(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,S;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"),Af(e),Du(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(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 o=(w=t==null?void 0:t.panePadding)==null?void 0:w.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):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=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Du(e,n)}var Nu=["panel","seamless"];function mi(e,n){var i,d,l,u,p,f;for(let g of Nu)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",o=Nu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);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())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Fu(e,n){var t,r,o;return!n||!Zn(e)?!1:((o=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Sf(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 Ef(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 Tf(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Mf(e,n,t,r){let o=e-r-2*n-t;return Math.max(0,o)}function Ou(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function $u(e,n,t,r,o,s){let a=Sf(o,200),i=Mf(n,t,r,200);i=Math.max(a,i);let d=Ef(s);return d!==null&&(i=Math.min(i,d)),Tf(e,a,i)}var _u={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},dl=(e,n,t,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,x,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(x=_u[a])!=null?x:_u.init;s.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 S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,d.appendChild(S)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var E,O;let L=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${n.id}-${a}-${S.name}`;let D=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=S.label,L.appendChild(D);let N=(E=S.type)!=null?E:"text",P;N==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=N),P.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",P.id=`${n.id}-${a}-${S.name}`,P.name=S.name,P.placeholder=(O=S.placeholder)!=null?O:"",S.required&&(P.required=!0),L.appendChild(P),u.appendChild(L)});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),s.replaceChildren(d,u),u.addEventListener("submit",async S=>{var P,E;S.preventDefault();let L=(P=t.formEndpoint)!=null?P:"/form",D=new FormData(u),N={};D.forEach((O,_)=>{N[_]=O}),N.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let O=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!O.ok)throw new Error(`Form submission failed (${O.status})`);let _=await O.json();f.textContent=(E=_.message)!=null?E:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(O){f.textContent=O instanceof Error?O.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var pl=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,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...n].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},ea=new pl;var ju=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:n,off:t,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var kf=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Lf=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<n.length;o+=1){let s=n[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return n.slice(t,o+1)}return null},ta=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=kf(e),t=Lf(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},ul=e=>typeof e=="string"?e:e==null?"":String(e),Oo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ul(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,r=ul(t.element);if(r&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ul(t.text)}}},Uu=e=>Array.isArray(e)?e.map(n=>String(n)):[],na=e=>{let n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;n.add(s.message.id),r();let d={action:i,message:s.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:s.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 Pf=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}},If=e=>e.map(n=>({...n,streaming:!1})),Wf=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?Pf(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let o={...t,messages:t.messages?If(t.messages):void 0,artifacts:t.artifacts?Wf(t.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},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 ms=require("partial-json");function Rf(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Hf(e,n){if(!Rf(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 o=(0,ms.parse)(t,ms.STR|ms.OBJ),s=Hf(o,t);s&&(e=s)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function qu(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:o}=n,s=Or.get(e.component);if(!s)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=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function zu(){let e=fi();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Vu(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function yi(e){let n=Vu(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function bi(e){let n=Vu(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var Bf=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xi(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Bf}=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=o,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 S=[];for(let E=1;E<=5;E++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-star-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`${E} star${E>1?"s":""}: ${l[E-1]}`),O.title=l[E-1],O.dataset.rating=String(E),O.innerHTML=`
19
+ `):""},jg=(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,o=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",s=_g(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?Ip(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(g=n==null?void 0:n.toolCall)!=null?g:{},l=a;return o==="tool-name"?l=((w=t.name)==null?void 0:w.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Ri(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ri(t,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},yu=(e,n,t)=>{var u;let r=ls.has(e),o=(u=t==null?void 0:t.toolCall)!=null?u:{},s=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=o.toggleTextColor||o.headerTextColor||"currentColor",f=me(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")},Zi=(e,n)=>{var J,se,Ie,ke,Qe,ge,pe,Le,qe;let t=e.toolCall,r=(J=n==null?void 0:n.toolCall)!=null?J:{},o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),!t)return o;let s=(Ie=(se=n==null?void 0:n.features)==null?void 0:se.toolCallDisplay)!=null?Ie:{},a=s.expandable!==!1,i=a&&ls.has(e.id),{summary:d,previewText:l,isActive:u}=jg(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((ke=t.startedAt)!=null?ke:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",w),te.textContent=Hs(t),te},k=(ge=r.renderCollapsedSummary)==null?void 0:ge.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Qe=s.collapsedMode)!=null?Qe:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Hs(t),createElapsedElement:x});typeof k=="string"&&k.trim()?(g.textContent=k,f.appendChild(g)):k instanceof HTMLElement?f.appendChild(k):(g.textContent=d,f.appendChild(g));let S=(pe=s.loadingAnimation)!=null?pe:"none",L=r.activeTextTemplate,D=r.completeTextTemplate,N=u?L:D,P=k instanceof HTMLElement,E=(te,Se,X)=>{let ie=X;for(let He of Se){let de=h("span","persona-tool-char");de.style.setProperty("--char-index",String(ie)),de.textContent=He===" "?"\xA0":He,te.appendChild(de),ie++}return ie},O=(te,Se)=>{var de;g.textContent="";let X=((de=t.name)==null?void 0:de.trim())||"tool",ie=Ma(te,X),He=0;for(let Re of ie){let et=Re.styles.length>0?(()=>{let K=h("span",Re.styles.map(ae=>`persona-tool-text-${ae}`).join(" "));return g.appendChild(K),K})():g;if(Re.isDuration&&u)et.appendChild(x());else{let K=Re.isDuration?Hs(t):Re.text;Se?He=E(et,K,He):et.appendChild(document.createTextNode(K))}}};if(!P)if(u&&S!=="none"){let te=(Le=r.loadingAnimationDuration)!=null?Le:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),N&&O(N,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),S==="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)),N)O(N,!0);else{let Se=g.textContent||d;g.textContent="",E(g,Se,0)}}else N&&O(N,!1);let _=null;if(a){_=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",Se=me(i?"chevron-up":"chevron-down",16,te,2);Se?_.appendChild(Se):_.textContent=i?"Hide":"Show";let X=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(_),p.append(f,X)}else p.append(f);let U=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let te=(qe=r.renderCollapsedPreview)==null?void 0:qe.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});$g(U,te)||(U.textContent=l),U.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(p,U),o;let R=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.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,R.appendChild(te)}if(t.args!==void 0){let te=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Se.style.color=r.labelTextColor),Se.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=Yo(t.args),te.append(Se,X),R.appendChild(te)}if(t.chunks&&t.chunks.length){let te=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Se.style.color=r.labelTextColor),Se.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(Se,X),R.appendChild(te)}if(t.status==="complete"&&t.result!==void 0){let te=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Se.style.color=r.labelTextColor),Se.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=Yo(t.result),te.append(Se,X),R.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`,R.appendChild(te)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",Se=me(i?"chevron-up":"chevron-down",16,te,2);Se?_.appendChild(Se):_.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(p,U,R),o};var io=require("partial-json");var tl="ask_user_question",el=8,cs="data-persona-ask-sheet-for",Ug="Other",qg="Other\u2026",xu="Type your own answer here",vu="Send",zg="Next",Vg="Back",Jg="Submit all",Kg="Skip",Gg=3,nl="data-ask-current-index",rl="data-ask-question-count",Cu="data-ask-answers",ol="data-ask-grouped",wu="data-ask-layout",Qg=e=>e.layout==="pills"?"pills":"rows",Xg=e=>e.getAttribute(wu)==="pills"?"pills":"rows",bu=!1,Au=e=>e.replace(/["\\]/g,"\\$&"),Nr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===tl,ci=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},Fr=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 o=r.join(""),s=(0,io.parse)(o,io.STR|io.OBJ|io.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Xs=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>el&&!bu&&(bu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${el}.`)),n.slice(0,el)},Yg=e=>{var n;return(n=Xs(e)[0])!=null?n:null},Zg=(e,n)=>{var t;return(t=Xs(e)[n])!=null?t:null},Su=(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))},Eu=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let o=h("span","persona-ask-row-check");r.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},ef=(e,n,t,r)=>{let s=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(n)),s.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)}s.appendChild(a);let d=Eu(t,r,n);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},tf=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},nf=(e,n,t,r)=>{var u,p,f;let s=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");s.setAttribute("role","group"),s.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<Gg;g++)s.appendChild(tf(r));return s}if(d.forEach((g,w)=>{s.appendChild(ef(g,w,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Ug:qg;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"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(u=n.freeTextPlaceholder)!=null?u:xu,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:g),x.appendChild(k),w.appendChild(x);let S=Eu(r,a,d.length);S&&w.appendChild(S),s.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,s.appendChild(w)}}return s},Tu=(e,n)=>{var s,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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:xu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),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:vu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},rf=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:vu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},of=(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 o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=t.backLabel)!=null?l:Vg,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=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:Kg,a.setAttribute("data-ask-user-action","skip"),s.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:Jg:(f=t.nextLabel)!=null?f:zg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Fo=e=>{let n=e.getAttribute(Cu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Mu=(e,n)=>{e.setAttribute(Cu,JSON.stringify(n))},Yn=e=>{var t;let n=Number((t=e.getAttribute(nl))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},sf=(e,n)=>{e.setAttribute(nl,String(Math.max(0,Math.floor(n))))},ds=e=>{var t;let n=Number((t=e.getAttribute(rl))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},lo=e=>e.getAttribute(ol)==="true",af=(e,n)=>{var o;let t=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},lf=(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}=Fr(n),r=Xs(t),o=Fo(e),s={},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(o,d)&&(s[l]=o[d]))}),s},ku=e=>{let n=Fo(e),t=Yn(e),r=n[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=o.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).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=""},Lu=e=>{if(!lo(e))return;let n=Fo(e),t=Yn(e),r=n[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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}},sl=(e,n,t)=>{let r=ci(t),o=Xg(e),{payload:s,complete:a}=Fr(n),i=lo(e),d=Yn(e),l=ds(e),u=i?Zg(s,d):Yg(s),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 L=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=L,w.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=nf(u,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Tu(r,o))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(rf(r)):(!p||i)&&k&&k.remove(),e.setAttribute("data-multi-select",p?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=of(d,l,r);S?S.replaceWith(L):e.appendChild(L)}else S&&S.remove();ku(e),Lu(e)},cf=(e,n,t)=>{let r=ci(n),o=Qg(r),s=e.toolCall.id,a=Xs(t),i=Math.max(1,a.length),d=i>1,l=af(e,a),u=d?lf(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(cs,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(rl,String(i)),p.setAttribute(nl,String(u)),p.setAttribute(ol,d?"true":"false"),p.setAttribute(wu,o),Mu(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`),Su(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 k=h("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),p.appendChild(k),o!=="rows"&&p.appendChild(Tu(r,o)),sl(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},df=(e,n,t)=>{let{payload:r}=Fr(n),o=Math.max(1,Xs(r).length);o>ds(e)&&(e.setAttribute(rl,String(o)),o>1&&!lo(e)&&e.setAttribute(ol,"true")),sl(e,n,t)},Pu=(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);Su(t,r);let o=h("span","persona-ask-stub-label"),{complete:s}=Fr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},ps=(e,n,t)=>{if(!t||!Nr(e)||ci(n).enabled===!1)return;let o=e.toolCall.id;t.querySelectorAll(`[${cs}]`).forEach(l=>{l.getAttribute(cs)!==o&&l.remove()});let a=t.querySelector(`[${cs}="${Au(o)}"]`);if(a){df(a,e,n);return}let{payload:i}=Fr(e),d=cf(e,n,i);t.appendChild(d)},co=(e,n)=>{if(!e)return;let t=n?`[${cs}="${Au(n)}"]`:`[${cs}]`;e.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},al=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),po=(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,Mu(e,t),ku(e),Lu(e)},pi=(e,n,t,r)=>{let o=ds(e),s=Math.max(0,Math.min(o-1,r));sf(e,s),sl(e,n,t)};var il=(e,n)=>{var x,k,S,L,D,N,P,E,O,_,U,R;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(k=r==null?void 0:r.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return s;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)":(S=r==null?void 0:r.titleColor)!=null?S:"currentColor",u=me(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=(L=r==null?void 0:r.title)!=null?L:"Approval Required",f.appendChild(g),!o){let $=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",t.status),t.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):t.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):t.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),f.appendChild($)}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 $=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&&($.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&($.style.color=r.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=Yo(t.parameters),p.appendChild($)}if(o){let $=h("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let J=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");J.type="button",J.style.backgroundColor=(D=r==null?void 0:r.approveButtonColor)!=null?D:"var(--persona-approval-approve-bg, #22c55e)",J.style.color=(N=r==null?void 0:r.approveButtonTextColor)!=null?N:"#ffffff",J.setAttribute("data-approval-action","approve");let se=me("shield-check",14,(P=r==null?void 0:r.approveButtonTextColor)!=null?P:"#ffffff",2);se&&(se.style.marginRight="4px",J.appendChild(se));let Ie=document.createTextNode((E=r==null?void 0:r.approveLabel)!=null?E:"Approve");J.appendChild(Ie);let ke=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");ke.type="button",ke.style.backgroundColor=(O=r==null?void 0:r.denyButtonColor)!=null?O:"transparent",ke.style.color=(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",ke.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ke.setAttribute("data-approval-action","deny");let Qe=me("shield-x",14,(U=r==null?void 0:r.denyButtonTextColor)!=null?U:"var(--persona-feedback-error, #dc2626)",2);Qe&&(Qe.style.marginRight="4px",ke.appendChild(Qe));let ge=document.createTextNode((R=r==null?void 0:r.denyLabel)!=null?R:"Deny");ke.appendChild(ge),$.append(J,ke),p.appendChild($)}return a.append(i,p),s.appendChild(a),s};var Iu=e=>{let n=[];return{buttons:n,render:(r,o,s,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(g=>g.role==="user"))return;let u=document.createDocumentFragment(),p=o?o.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",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(g))}),u.appendChild(w),n.push(w)}),e.appendChild(u)}}};var Ys=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 Zs=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 o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,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 o of n)r.put(o)}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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((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 o of n)r.put(o)}catch{}}};function us(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var pf={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)"}},uf={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},mf=["flowName","stepName","reasoningText","text","name","tool","toolName"],gf=100;function ff(e,n){let t={...pf,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return uf}function hf(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function yf(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function bf(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function xf(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 vf(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 Cf(e,n,t){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=n.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:o});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 ll(e,n,t,r,o,s,a,i){var f;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");us(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:()=>s(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var J,se;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"),k=me(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&x.appendChild(k);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(J=r.timestampFormat)!=null?J:"relative";S.textContent=L==="relative"?hf(e.timestamp,t):yf(e.timestamp);let D=null;r.showSequenceNumbers!==!1&&(D=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(n+1));let N=ff(e.type,r.badgeColors),P=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");P.style.backgroundColor=N.bg,P.style.color=N.text,P.style.borderColor=N.text+"50",P.textContent=e.type;let E=(se=r.descriptionFields)!=null?se:mf,O=bf(e.payload,E),_=null;O&&(_=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=O);let U=h("div","persona-flex-1 persona-min-w-0"),R=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"),$=me("clipboard","12px","currentColor",1.5);return $&&R.appendChild($),R.addEventListener("click",async Ie=>{Ie.stopPropagation(),await xf(vf(e)),R.innerHTML="";let ke=me("check","12px","currentColor",1.5);ke&&R.appendChild(ke),setTimeout(()=>{R.innerHTML="";let Qe=me("clipboard","12px","currentColor",1.5);Qe&&R.appendChild(Qe)},1500)}),w.appendChild(x),w.appendChild(S),D&&w.appendChild(D),w.appendChild(P),_&&w.appendChild(_),w.appendChild(U),w.appendChild(R),g.appendChild(w),d&&g.appendChild(Cf(e,a,i)),g}}function Wu(e){var g,w,x,k,S;let{buffer:n,getFullHistory:t,onClose:r,config:o,plugins:s=[]}=e,a=(g=o==null?void 0:o.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=(S=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?S:{},p=s.find(L=>L.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&o){let L=p.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return f();function f(){let L=u.classNames,D=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");us(D,L==null?void 0:L.panel);let N=[],P="",E="",O=null,_=[],U={},R=0,$=Va(),J=0,se=0,Ie=!1,ke=null,Qe=!1,ge=0,pe=new Set,Le=new Map,qe="",te="",Se=null,X,ie,He,de,Re;function et(){let I=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),he=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");us(he,L==null?void 0:L.headerBar);let fe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");fe.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 dt=h("div","persona-flex-1");ie=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 ze=h("option","");ze.value="",ze.textContent="All events",ie.appendChild(ze),He=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),He.type="button",He.title="Copy All";let ln=me("clipboard-copy","12px","currentColor",1.5);ln&&He.appendChild(ln);let At=h("span","persona-text-xs");At.textContent="Copy All",He.appendChild(At),he.appendChild(fe),he.appendChild(X),he.appendChild(dt),he.appendChild(ie),he.appendChild(He);let xt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");us(xt,L==null?void 0:L.searchBar);let kt=me("search","14px","var(--persona-muted, #9ca3af)",1.5),ut=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");kt&&ut.appendChild(kt),de=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),us(de,L==null?void 0:L.searchInput),de.type="text",de.placeholder="Search event payloads...",Re=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Re.type="button",Re.style.display="none";let Kt=me("x","12px","currentColor",2);return Kt&&Re.appendChild(Kt),xt.appendChild(ut),xt.appendChild(de),xt.appendChild(Re),I.appendChild(he),I.appendChild(xt),I}let K,ae=s.find(I=>I.renderEventStreamToolbar);if(ae!=null&&ae.renderEventStreamToolbar&&o){let I=ae.renderEventStreamToolbar({config:o,defaultRenderer:()=>et(),eventCount:n.getSize(),filteredCount:0,onFilterChange:he=>{P=he,ne(),Jt()},onSearchChange:he=>{E=he,ne(),Jt()}});K=I!=null?I:et()}else K=et();let Oe=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";let G=h("div","persona-flex-1 persona-min-h-0 persona-relative"),V=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let ve=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");us(ve,L==null?void 0:L.scrollIndicator),ve.style.display="none",ve.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let $e=me(d,"14px","currentColor",2);$e&&ve.appendChild($e);let re=h("span","");re.textContent=l,ve.appendChild(re);let Ee=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ee.style.display="none",G.appendChild(V),G.appendChild(Ee),G.appendChild(ve),D.setAttribute("tabindex","0"),D.appendChild(K),D.appendChild(Oe),D.appendChild(G);function xe(){let I=n.getAll(),he={};for(let At of I)he[At.type]=(he[At.type]||0)+1;let fe=Object.keys(he).sort(),dt=fe.length!==_.length||!fe.every((At,xt)=>At===_[xt]),ze=!dt&&fe.some(At=>he[At]!==U[At]),Wt=I.length!==Object.values(U).reduce((At,xt)=>At+xt,0);if(!dt&&!ze&&!Wt||(_=fe,U=he,!ie))return;let ln=ie.value;if(ie.options[0].textContent="All events",dt){for(;ie.options.length>1;)ie.remove(1);for(let At of fe){let xt=h("option","");xt.value=At,xt.textContent=`${At} (${he[At]||0})`,ie.appendChild(xt)}ln&&fe.includes(ln)?ie.value=ln:ln&&(ie.value="",P="")}else for(let At=1;At<ie.options.length;At++){let xt=ie.options[At];xt.textContent=`${xt.value} (${he[xt.value]||0})`}}function Bt(){let I=n.getAll();if(P&&(I=I.filter(he=>he.type===P)),E){let he=E.toLowerCase();I=I.filter(fe=>fe.type.toLowerCase().includes(he)||fe.payload.toLowerCase().includes(he))}return I}function Pe(){return P!==""||E!==""}function ne(){R=0,J=0,$.resume(),ve.style.display="none"}function an(I){pe.has(I)?pe.delete(I):pe.add(I),Se=I;let he=V.scrollTop,fe=$.isFollowing();Qe=!0,$.pause(),Jt(),V.scrollTop=he,fe&&$.resume(),Qe=!1}function Ot(){return _s(V,50)}function Jt(){se=Date.now(),Ie=!1,xe();let I=n.getEvictedCount();I>0?(Oe.textContent=`${I.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",N=Bt();let he=N.length,fe=n.getSize()>0;X&&(X.textContent=String(n.getSize())),he===0&&fe&&Pe()?(Ee.textContent=E?`No events matching '${E}'`:"No events matching filter",Ee.style.display="",V.style.display="none"):(Ee.style.display="none",V.style.display=""),He&&(He.title=Pe()?`Copy Filtered (${he})`:"Copy All"),i&&!$.isFollowing()&&he>R&&(J+=he-R,re.textContent=l?`${l}${J>0?` (${J})`:""}`:"",ve.style.display=""),R=he;let dt=n.getAll(),ze=dt.length>0?dt[0].timestamp:0,Wt=new Set(N.map(xt=>xt.id));for(let xt of pe)Wt.has(xt)||pe.delete(xt);let ln=P!==qe||E!==te,At=Le.size===0&&N.length>0;if(ln||At||N.length===0){V.innerHTML="",Le.clear();let xt=document.createDocumentFragment();for(let kt=0;kt<N.length;kt++){let ut=ll(N[kt],kt,ze,u,pe,an,s,o);Le.set(N[kt].id,ut),xt.appendChild(ut)}V.appendChild(xt),qe=P,te=E,Se=null}else{if(Se!==null){let kt=Le.get(Se);if(kt&&kt.parentNode===V){let ut=N.findIndex(Kt=>Kt.id===Se);if(ut>=0){let Kt=ll(N[ut],ut,ze,u,pe,an,s,o);V.insertBefore(Kt,kt),kt.remove(),Le.set(Se,Kt)}}Se=null}let xt=new Set(N.map(kt=>kt.id));for(let[kt,ut]of Le)xt.has(kt)||(ut.remove(),Le.delete(kt));for(let kt=0;kt<N.length;kt++){let ut=N[kt];if(!Le.has(ut.id)){let Kt=ll(ut,kt,ze,u,pe,an,s,o);Le.set(ut.id,Kt),V.appendChild(Kt)}}}$.isFollowing()&&(V.scrollTop=V.scrollHeight)}function Cr(){if(Date.now()-se>=gf){ke!==null&&(cancelAnimationFrame(ke),ke=null),Jt();return}Ie||(Ie=!0,ke=requestAnimationFrame(()=>{ke=null,Jt()}))}let pr=(I,he)=>{if(!He)return;He.innerHTML="";let fe=me(I,"12px","currentColor",1.5);fe&&He.appendChild(fe);let dt=h("span","persona-text-xs");dt.textContent="Copy All",He.appendChild(dt),setTimeout(()=>{He.innerHTML="";let ze=me("clipboard-copy","12px","currentColor",1.5);ze&&He.appendChild(ze);let Wt=h("span","persona-text-xs");Wt.textContent="Copy All",He.appendChild(Wt),He.disabled=!1},he)},je=async()=>{if(He){He.disabled=!0;try{let I;Pe()?I=N:t?(I=await t(),I.length===0&&(I=n.getAll())):I=n.getAll();let he=I.map(fe=>{try{return JSON.parse(fe.payload)}catch{return fe.payload}});await navigator.clipboard.writeText(JSON.stringify(he,null,2)),pr("check",1500)}catch{pr("x",1500)}}},q=()=>{ie&&(P=ie.value,ne(),Jt())},we=()=>{!de||!Re||(Re.style.display=de.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{E=de.value,ne(),Jt()},150))},Be=()=>{!de||!Re||(de.value="",E="",Re.style.display="none",O&&clearTimeout(O),ne(),Jt())},De=()=>{if(Qe)return;let I=V.scrollTop,{action:he,nextLastScrollTop:fe}=Ja({following:$.isFollowing(),currentScrollTop:I,lastScrollTop:ge,nearBottom:Ot(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ge=fe,he==="resume"?($.resume(),J=0,ve.style.display="none"):he==="pause"&&($.pause(),i&&(re.textContent=l,ve.style.display=""))},_e=I=>{let he=Ka({following:$.isFollowing(),deltaY:I.deltaY,nearBottom:Ot(),resumeWhenNearBottom:!0});he==="pause"?($.pause(),i&&(re.textContent=l,ve.style.display="")):he==="resume"&&($.resume(),J=0,ve.style.display="none")},ct=()=>{i&&(V.scrollTop=V.scrollHeight,$.resume(),J=0,ve.style.display="none")},tt=I=>{let he=I.target;if(!he||he.closest("button"))return;let fe=he.closest("[data-event-id]");if(!fe)return;let dt=fe.getAttribute("data-event-id");dt&&an(dt)},wt=I=>{if((I.metaKey||I.ctrlKey)&&I.key==="f"){I.preventDefault(),de==null||de.focus(),de==null||de.select();return}I.key==="Escape"&&(de&&document.activeElement===de?(Be(),de.blur(),D.focus()):r&&r())};He&&He.addEventListener("click",je),ie&&ie.addEventListener("change",q),de&&de.addEventListener("input",we),Re&&Re.addEventListener("click",Be),V.addEventListener("scroll",De),V.addEventListener("wheel",_e,{passive:!0}),V.addEventListener("click",tt),ve.addEventListener("click",ct),D.addEventListener("keydown",wt);function qt(){O&&clearTimeout(O),ke!==null&&(cancelAnimationFrame(ke),ke=null),Ie=!1,Le.clear(),He&&He.removeEventListener("click",je),ie&&ie.removeEventListener("change",q),de&&de.removeEventListener("input",we),Re&&Re.removeEventListener("click",Be),V.removeEventListener("scroll",De),V.removeEventListener("wheel",_e),V.removeEventListener("click",tt),ve.removeEventListener("click",ct),D.removeEventListener("keydown",wt)}return{element:D,update:Cr,destroy:qt}}}function Ru(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=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)",o==="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),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Hu=(e,n)=>{var r,o,s;let t=(s=(o=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>Ru(e,n)});if(u)return u}return Ru(e,n)};var cl=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)})}},Or=new cl;Or.register("PersonaArtifactCard",Hu);function wf(e){var o;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((o=e.props)!=null?o:{},null,2),n.appendChild(t),n.appendChild(r),n}function Bu(e,n){var He,de,Re,et;let t=(de=(He=e.features)==null?void 0:He.artifacts)==null?void 0:de.layout,o=((Re=t==null?void 0:t.toolbarPreset)!=null?Re:"default")==="document",s=(et=t==null?void 0:t.panePadding)==null?void 0:et.trim(),a=e.markdown?ko(e.markdown):null,i=Xo(e.sanitize),d=K=>{let ae=a?a(K):Lo(K);return i?i(ae):ae},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"),$==null||$.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"),o&&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"),o&&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",k=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=o?jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):jt({icon:"eye",label:"Rendered view"}),L=o?jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):jt({icon:"code-2",label:"Source"}),D=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),N=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,P=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,E=t==null?void 0:t.documentToolbarCopyMenuItems,O=!!(P&&E&&E.length>0),_=null,U,R=null,$=null;if(o&&(N||P)&&!O){if(U=N?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let K=me("chevron-down",14,"currentColor",2);K&&U.appendChild(K)}}else o&&O?(_=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),U=N?Gs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=jt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),_.append(U,R)):o?U=jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):U=jt({icon:"copy",label:"Copy"});let J=o?jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):jt({icon:"refresh-cw",label:"Refresh"}),se=o?jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):jt({icon:"x",label:"Close"}),Ie=()=>{var V,ve,$e;let K=(V=qe.find(re=>re.id===te))!=null?V:qe[qe.length-1],ae=(ve=K==null?void 0:K.id)!=null?ve:null,Oe=(K==null?void 0:K.artifactType)==="markdown"&&($e=K.markdown)!=null?$e:"",G=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Oe,jsonPayload:G,id:ae}},ke=async()=>{var V;let{markdown:K,jsonPayload:ae}=Ie(),Oe=(V=qe.find(ve=>ve.id===te))!=null?V:qe[qe.length-1],G=(Oe==null?void 0:Oe.artifactType)==="markdown"?K:Oe?ae:"";try{await navigator.clipboard.writeText(G)}catch{}};if(U.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&O){let{markdown:ae,jsonPayload:Oe,id:G}=Ie();try{await K({actionId:"primary",artifactId:G,markdown:ae,jsonPayload:Oe})}catch{}return}await ke()}),R&&(E!=null&&E.length)){let K=()=>{var Oe;return(Oe=p.closest("[data-persona-root]"))!=null?Oe:document.body},ae=()=>{$=ao({items:E.map(Oe=>({id:Oe.id,label:Oe.label})),onSelect:async Oe=>{let{markdown:G,jsonPayload:V,id:ve}=Ie(),$e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:Oe,artifactId:ve,markdown:G,jsonPayload:V}):Oe==="markdown"||Oe==="md"?await navigator.clipboard.writeText(G):Oe==="json"||Oe==="source"?await navigator.clipboard.writeText(V):await navigator.clipboard.writeText(G||V)}catch{}},anchor:_!=null?_:R,position:"bottom-right",portal:K()})};p.isConnected?ae():requestAnimationFrame(ae),R.addEventListener("click",Oe=>{Oe.stopPropagation(),$==null||$.toggle()})}J.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}X()}),se.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let Qe=()=>{o&&(S.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};S.addEventListener("click",()=>{x="rendered",Qe(),X()}),L.addEventListener("click",()=>{x="source",Qe(),X()});let ge=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");o?(f.replaceChildren(),k.append(S,L),_?D.append(_,J,se):D.append(U,J,se),f.append(k,ge,D),Qe()):(f.appendChild(g),f.appendChild(w)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let pe=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(pe.style.paddingLeft=s,pe.style.paddingRight=s,Le.style.padding=s),p.appendChild(f),p.appendChild(pe),p.appendChild(Le);let qe=[],te=null,Se=!1,X=()=>{var G,V,ve,$e;let K=o&&qe.length<=1;pe.classList.toggle("persona-hidden",K),pe.replaceChildren();for(let re of qe){let Ee=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");Ee.type="button",Ee.textContent=re.title||re.id.slice(0,8),re.id===te&&Ee.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ee.addEventListener("click",()=>n.onSelect(re.id)),pe.appendChild(Ee)}Le.replaceChildren();let ae=te&&qe.find(re=>re.id===te)||qe[qe.length-1];if(!ae)return;if(o){let re=ae.artifactType==="markdown"?"MD":(G=ae.component)!=null?G:"Component",xe=(ae.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${xe} \xB7 ${re}`}else g.textContent="Artifacts";if(ae.artifactType==="markdown"){if(o&&x==="source"){let Ee=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ee.textContent=(V=ae.markdown)!=null?V:"",Le.appendChild(Ee);return}let re=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");re.innerHTML=d((ve=ae.markdown)!=null?ve:""),Le.appendChild(re);return}let Oe=ae.component?Or.get(ae.component):void 0;if(Oe){let Ee={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let xe=Oe(($e=ae.props)!=null?$e:{},Ee);if(xe){Le.appendChild(xe);return}}catch{}}Le.appendChild(wf(ae))},ie=()=>{var ae;let K=qe.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Oe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,V=((ae=Oe==null?void 0:Oe.classList.contains("persona-artifact-narrow-host"))!=null?ae:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&V&&Se?(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 ae,Oe,G;qe=K.artifacts,te=(G=(Oe=K.selectedId)!=null?Oe:(ae=K.artifacts[K.artifacts.length-1])==null?void 0:ae.id)!=null?G:null,qe.length>0&&(Se=!0),X(),ie()},setMobileOpen(K){Se=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ie()}}}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 Du(e,n){var s,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=(s=n.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Af(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,k,S;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"),Af(e),Du(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(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 o=(w=t==null?void 0:t.panePadding)==null?void 0:w.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(k=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:k.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Du(e,n)}var Nu=["panel","seamless"];function mi(e,n){var i,d,l,u,p,f;for(let g of Nu)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",o=Nu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);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())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Fu(e,n){var t,r,o;return!n||!Zn(e)?!1:((o=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Sf(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 Ef(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 Tf(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Mf(e,n,t,r){let o=e-r-2*n-t;return Math.max(0,o)}function Ou(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function $u(e,n,t,r,o,s){let a=Sf(o,200),i=Mf(n,t,r,200);i=Math.max(a,i);let d=Ef(s);return d!==null&&(i=Math.min(i,d)),Tf(e,a,i)}var _u={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},dl=(e,n,t,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,x,k;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(x=_u[a])!=null?x:_u.init;s.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 S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,d.appendChild(S)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var E,O;let L=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${n.id}-${a}-${S.name}`;let D=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=S.label,L.appendChild(D);let N=(E=S.type)!=null?E:"text",P;N==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=N),P.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",P.id=`${n.id}-${a}-${S.name}`,P.name=S.name,P.placeholder=(O=S.placeholder)!=null?O:"",S.required&&(P.required=!0),L.appendChild(P),u.appendChild(L)});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=(k=i.submitLabel)!=null?k:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),s.replaceChildren(d,u),u.addEventListener("submit",async S=>{var P,E;S.preventDefault();let L=(P=t.formEndpoint)!=null?P:"/form",D=new FormData(u),N={};D.forEach((O,_)=>{N[_]=O}),N.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let O=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!O.ok)throw new Error(`Form submission failed (${O.status})`);let _=await O.json();f.textContent=(E=_.message)!=null?E:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(O){f.textContent=O instanceof Error?O.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var pl=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,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...n].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},ea=new pl;var ju=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:n,off:t,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var kf=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Lf=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<n.length;o+=1){let s=n[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return n.slice(t,o+1)}return null},ta=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=kf(e),t=Lf(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},ul=e=>typeof e=="string"?e:e==null?"":String(e),Oo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ul(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,r=ul(t.element);if(r&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ul(t.text)}}},Uu=e=>Array.isArray(e)?e.map(n=>String(n)):[],na=e=>{let n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;n.add(s.message.id),r();let d={action:i,message:s.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:s.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 Pf=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}},If=e=>e.map(n=>({...n,streaming:!1})),Wf=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?Pf(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let o={...t,messages:t.messages?If(t.messages):void 0,artifacts:t.artifacts?Wf(t.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},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 ms=require("partial-json");function Rf(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Hf(e,n){if(!Rf(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 o=(0,ms.parse)(t,ms.STR|ms.OBJ),s=Hf(o,t);s&&(e=s)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function qu(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:o}=n,s=Or.get(e.component);if(!s)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=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function zu(){let e=fi();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Vu(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function yi(e){let n=Vu(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function bi(e){let n=Vu(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var Bf=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xi(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Bf}=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=o,g.appendChild(x),f.appendChild(g);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let E=1;E<=5;E++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-star-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`${E} star${E>1?"s":""}: ${l[E-1]}`),O.title=l[E-1],O.dataset.rating=String(E),O.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
- `,O.addEventListener("click",()=>{p=E,S.forEach((_,U)=>{let R=U<E;_.classList.toggle("selected",R),_.setAttribute("aria-checked",U===E-1?"true":"false")})}),S.push(O),M.appendChild(O)}f.appendChild(M);let L=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),E.appendChild(L),f.appendChild(E)}let D=document.createElement("div");D.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{t==null||t(),u.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(p===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let E=(L==null?void 0:L.value.trim())||void 0;await n(p,E),u.remove()}catch(E){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",E)}}),D.appendChild(N),D.appendChild(P),f.appendChild(D),u.appendChild(f),u}function vi(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel: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=o,w.appendChild(M),g.appendChild(w);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=l;let N=document.createElement("span");N.className="persona-feedback-label-high",N.textContent=u,L.appendChild(D),L.appendChild(N);let P=document.createElement("div");P.className="persona-feedback-numbers";let E=[];for(let $=0;$<=10;$++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-number-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`Rating ${$} out of 10`),J.textContent=String($),J.dataset.rating=String($),$<=6?J.classList.add("persona-feedback-detractor"):$<=8?J.classList.add("persona-feedback-passive"):J.classList.add("persona-feedback-promoter"),J.addEventListener("click",()=>{f=$,E.forEach((se,Ie)=>{se.classList.toggle("selected",Ie===$),se.setAttribute("aria-checked",Ie===$?"true":"false")})}),E.push(J),P.appendChild(J)}S.appendChild(L),S.appendChild(P),g.appendChild(S);let O=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=s,O.rows=3,O.setAttribute("aria-label","Additional comments"),$.appendChild(O),g.appendChild($)}let _=document.createElement("div");_.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=i,U.addEventListener("click",()=>{t==null||t(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let $=(O==null?void 0:O.value.trim())||void 0;await n(f,$),p.remove()}catch($){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),_.appendChild(U),_.appendChild(R),g.appendChild(_),p.appendChild(g),p}var gs="persona-chat-history",Df=30*1e3,Nf={"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 Ff(e){var r,o,s;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=(o=Nf[i.type])!=null?o:"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((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&n.push(a);return n}function Ci(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 Of(e){var n,t,r,o,s,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:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.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 $f(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var ml=e=>!e||typeof e!="object"?{}:{...e},Ju=e=>e.map(n=>({...n,streaming:!1})),Ku=(e,n,t)=>{let r=e!=null&&e.markdown?ko(e.markdown):null,o=Xo(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(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."),s=>{var l,u,p;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):r?d=r(a):d=Lo(a),o?o(d):d}};function Gu(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",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=ge(t,r,o,s);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 wi=(e,n,t)=>{var Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,Ul,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,Cc,wc,Ac,Sc,Ec;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),o=ea.getForInstance(r.plugins);r.components&&Or.registerAll(r.components);let s=ju(),i=r.persistState===!1?null:(Rl=r.storageAdapter)!=null?Rl: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=ml(y.metadata)),(Hl=y.messages)!=null&&Hl.length&&(r={...r,initialMessages:y.messages}),(Bl=y.artifacts)!=null&&Bl.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Dl=y.selectedArtifactId)!=null?Dl: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:{}});(Nl=c.messages)!=null&&Nl.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:{},Uo()},w=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ta],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Oo.message,Oo.messageAndClick],M=na({parsers:w,handlers:x,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let S=(Ol=(Fl=r.launcher)==null?void 0:Fl.enabled)!=null?Ol:!0,L=(_l=($l=r.launcher)==null?void 0:$l.autoExpand)!=null?_l:!1,D=(jl=r.autoFocusInput)!=null?jl:!1,N=L,P=S,E=(ql=(Ul=r.layout)==null?void 0:Ul.header)==null?void 0:ql.layout,O=!1,_=()=>so(r),U=()=>S||_(),R=_()?!1:S?L:!0,$=!1,J=null,se=()=>{$=!0,J&&clearTimeout(J),J=setTimeout(()=>{$&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),$=!1)},1e4)},Ie=Ku(r,M,se),Le=(Vl=(zl=r.features)==null?void 0:zl.showReasoning)!=null?Vl:!0,Qe=(Kl=(Jl=r.features)==null?void 0:Jl.showToolCalls)!=null?Kl:!0,pe=(Ql=(Gl=r.features)==null?void 0:Gl.showEventStreamToggle)!=null?Ql:!1,ue=(Yl=(Xl=r.features)==null?void 0:Xl.scrollToBottom)!=null?Yl:{},je=`${(ec=typeof r.persistState=="object"?(Zl=r.persistState)==null?void 0:Zl.keyPrefix:void 0)!=null?ec:"persona-"}event-stream`,te=pe?new Zs(je):null,Se=(rc=(nc=(tc=r.features)==null?void 0:tc.eventStream)==null?void 0:nc.maxEvents)!=null?rc:2e3,X=pe?new Ys(Se,te):null,ie=null,He=!1,de=null,Re=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 et={onCopy:c=>{var m,y;s.emit("message:copy",c),j!=null&&j.isClientTokenMode()&&j.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;s.emit("message:feedback",c),j!=null&&j.isClientTokenMode()&&j.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=(oc=r.statusIndicator)!=null?oc:{},ae=c=>{var m,y,b,k;return c==="idle"?(m=K.idleText)!=null?m:fn.idle:c==="connecting"?(y=K.connectingText)!=null?y:fn.connecting:c==="connected"?(b=K.connectedText)!=null?b:fn.connected:c==="error"?(k=K.errorText)!=null?k:fn.error:fn[c]};function Oe(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:G,panel:V,pillRoot:ve}=pu(r),$e=uu(r,U()),{container:re,body:Ee,messagesWrapper:xe,suggestions:Bt,textarea:Pe,sendButton:ne,sendButtonWrapper:an,composerForm:Ot,statusText:Jt,introTitle:Cr,introSubtitle:pr,closeButton:Ue,iconHolder:q,headerTitle:we,headerSubtitle:Be,header:De,footer:_e,actionsRow:ct,leftActions:tt,rightActions:wt}=$e,qt=$e.setSendButtonMode,I=$e.micButton,he=$e.micButtonWrapper,fe=$e.attachmentButton,dt=$e.attachmentButtonWrapper,ze=$e.attachmentInput,Wt=$e.attachmentPreviewsContainer;re.classList.add("persona-relative"),Ee.classList.add("persona-relative");let ln=12,At=()=>{var c;return(c=ue.label)!=null?c:""},xt=()=>{var c;return(c=ue.iconName)!=null?c:"arrow-down"},kt=()=>ue.enabled!==!1,ut=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");ut.type="button",ut.style.display="none",ut.setAttribute("data-persona-scroll-to-bottom","true");let Kt=h("span","persona-flex persona-items-center"),wr=h("span","");ut.append(Kt,wr),re.appendChild(ut);let qn=()=>{let m=_e.style.display==="none"?0:_e.offsetHeight;ut.style.bottom=`${m+ln}px`};qn();let _r=()=>{let c=!!At();ut.setAttribute("aria-label",At()||"Jump to latest"),ut.title=At(),ut.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Kt.innerHTML="";let m=ge(xt(),"14px","currentColor",2);m?(Kt.appendChild(m),Kt.style.display=""):Kt.style.display="none",wr.textContent=At(),wr.style.display=c?"":"none"};_r();let Ct=null,ur=null,mr=o.find(c=>c.renderHeader);if(mr!=null&&mr.renderHeader){let c=mr.renderHeader({config:r,defaultRenderer:()=>{let m=Dr({config:r,showClose:U()});return Do(re,m,r),m.header},onClose:()=>Ht(!1,"user")});if(c){let m=re.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),De=c)}}let Ar=()=>{var m,y,b,k;if(!X)return;if(He=!0,!ie&&X&&(ie=Wu({buffer:X,getFullHistory:()=>X.getAllFromStore(),onClose:()=>er(),config:r,plugins:o})),ie&&(Ee.style.display="none",(m=_e.parentNode)==null||m.insertBefore(ie.element,_e),ie.update()),gt){gt.style.boxShadow=`inset 0 0 0 1.5px ${Sn.actionIconColor}`;let B=(k=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:k.toggleButtonActive;B&&B.split(/\s+/).forEach(F=>F&&gt.classList.add(F))}let c=()=>{if(!He)return;let B=Date.now();B-Re>=200&&(ie==null||ie.update(),Re=B),de=requestAnimationFrame(c)};Re=0,de=requestAnimationFrame(c),Lr(),s.emit("eventStream:opened",{timestamp:Date.now()})},er=()=>{var c,m,y;if(He){if(He=!1,ie&&ie.element.remove(),Ee.style.display="",gt){gt.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&&gt.classList.remove(k))}de!==null&&(cancelAnimationFrame(de),de=null),Lr(),s.emit("eventStream:closed",{timestamp:Date.now()})}},gt=null;if(pe){let c=(ac=(sc=r.features)==null?void 0:sc.eventStream)==null?void 0:ac.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:"");gt=h("button",m),gt.style.width="28px",gt.style.height="28px",gt.style.color=Sn.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let y=ge("activity","18px","currentColor",1.5);y&&gt.appendChild(y);let b=$e.clearChatButtonWrapper,k=$e.closeButtonWrapper,B=b||k;B&&B.parentNode===De?De.insertBefore(gt,B):De.appendChild(gt),gt.addEventListener("click",()=>{He?er():Ar()})}let mo=c=>{var b,k,B;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:Br).join(","),F.multiple=((k=m.maxFiles)!=null?k:4)>1,F.style.display="none",F.setAttribute("aria-label",(B=m.buttonTooltipText)!=null?B:"Attach files"),c.appendChild(F)}},gr=o.find(c=>c.renderComposer);if(gr!=null&&gr.renderComposer){let c=r.composer,m=gr.renderComposer({config:r,defaultRenderer:()=>ss({config:r}).footer,onSubmit:y=>{var F;if(!j||j.isStreaming())return;let b=y.trim(),k=(F=Ct==null?void 0:Ct.hasAttachments())!=null?F:!1;if(!b&&!k)return;Ss();let B;k&&(B=[],B.push(...Ct.getContentParts()),b&&B.push(Bs(b))),j.sendMessage(b,{contentParts:B}),k&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ze==null||ze.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:((ic=r.voiceRecognition)==null?void 0:ic.enabled)===!0?()=>{ur==null||ur()}:void 0});m&&(_e.replaceWith(m),_e=m)}let go=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]"),B=c.querySelector("[data-persona-composer-status]");m&&(Ot=m),y&&(Pe=y),b&&(ne=b),k&&(I=k,he=k.parentElement),B&&(Jt=B);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Bt=F);let z=c.querySelector(".persona-attachment-button");z&&(fe=z,dt=z.parentElement),ze=c.querySelector('input[type="file"]'),Wt=c.querySelector(".persona-attachment-previews");let W=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");W&&(ct=W)};mo(_e),go(_e);let En=(uc=(lc=r.layout)==null?void 0:lc.contentMaxWidth)!=null?uc:_()?(pc=(dc=(cc=r.launcher)==null?void 0:cc.composerBar)==null?void 0:dc.contentMaxWidth)!=null?pc:"720px":void 0;if(En&&(xe.style.maxWidth=En,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%"),En&&Ot&&!_()&&(Ot.style.maxWidth=En,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),En&&Bt&&!_()&&(Bt.style.maxWidth=En,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),En&&Wt&&!_()&&(Wt.style.maxWidth=En,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),(mc=r.attachments)!=null&&mc.enabled&&ze&&Wt){Ct=Bo.fromConfig(r.attachments),Ct.setPreviewsContainer(Wt),ze.addEventListener("change",y=>{let b=y.target;Ct==null||Ct.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=Gu(c);re.appendChild(m)}(()=>{var b,k;let c=(k=(b=r.layout)==null?void 0:b.slots)!=null?k:{},m=B=>{switch(B){case"body-top":return re.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return xe;case"footer-top":return Bt;case"composer":return Ot;case"footer-bottom":return Jt;default:return null}},y=(B,F)=>{var z;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")De.insertBefore(F,De.firstChild);else if(B==="header-right")De.appendChild(F);else{let W=De.querySelector(".persona-flex-col");W?(z=W.parentNode)==null||z.insertBefore(F,W.nextSibling):De.appendChild(F)}break;case"body-top":{let W=Ee.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");W?W.replaceWith(F):Ee.insertBefore(F,Ee.firstChild);break}case"body-bottom":Ee.appendChild(F);break;case"footer-top":Bt.replaceWith(F);break;case"footer-bottom":Jt.replaceWith(F);break;default:break}};for(let[B,F]of Object.entries(c))if(F)try{let z=F({config:r,defaultContent:()=>m(B)});z&&y(B,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,z)}})();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 B=y.getAttribute("data-bubble-type");B==="reasoning"?(is.has(k)?is.delete(k):is.add(k),hu(k,b)):B==="tool"&&(ls.has(k)?ls.delete(k):ls.add(k),yu(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 B=y.getAttribute("data-action");if(B==="copy"){let W=j.getMessages().find(be=>be.id===k);if(W&&et.onCopy){let be=W.content||"";navigator.clipboard.writeText(be).then(()=>{y.classList.add("persona-message-action-success");let le=ge("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ee=ge("copy",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),et.onCopy(W)}}else if(B==="upvote"||B==="downvote"){let W=((F=Sr.get(k))!=null?F:null)===B,be=B==="upvote"?"thumbs-up":"thumbs-down";if(W){Sr.delete(k),y.classList.remove("persona-message-action-active");let le=ge(be,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=B==="upvote"?"downvote":"upvote",ee=b.querySelector(`[data-action="${le}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ge=ge(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(ee.innerHTML="",ee.appendChild(Ge))}Sr.set(k,B),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 Fe=j.getMessages().find(Ze=>Ze.id===k);Fe&&et.onFeedback&&et.onFeedback({type:B,messageId:Fe.id,message:Fe})}}}),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 B=y.getAttribute("data-approval-action");if(!B)return;let F=B==="approve"?"approved":"denied",W=j.getMessages().find(le=>le.id===k);if(!(W!=null&&W.approval))return;let be=b.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),j.resolveApproval(W.approval,F)});let bt=null,Wn=null,Rn={artifacts:[],selectedId:null},yn=!1,Lt={current:null};xe.addEventListener("click",c=>{var ee,me,Ce,Fe,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||((Ce=(me=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:me.onArtifactAction)==null?void 0:Ce.call(me,{type:"download",artifactId:b}))===!0)return;let B=j.getArtifactById(b),F=B==null?void 0:B.markdown,z=(B==null?void 0:B.title)||"artifact";if(!F){let Ge=y.closest("[data-open-artifact]"),st=Ge==null?void 0:Ge.closest("[data-message-id]"),at=st==null?void 0:st.getAttribute("data-message-id");if(at){let Te=j.getMessages().find(qe=>qe.id===at);if(Te!=null&&Te.rawContent)try{let qe=JSON.parse(Te.rawContent);F=(Fe=qe==null?void 0:qe.props)==null?void 0:Fe.markdown,z=((Ze=qe==null?void 0:qe.props)==null?void 0:Ze.title)||z}catch{}}}if(!F)return;let W=new Blob([F],{type:"text/markdown"}),be=URL.createObjectURL(W),le=document.createElement("a");le.href=be,le.download=`${z}.md`,le.click(),URL.revokeObjectURL(be)}),xe.addEventListener("click",c=>{var B,F,z;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((z=(F=(B=r.features)==null?void 0:B.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:z.call(F,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),yn=!1,j.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=$e.composerOverlay,Vn=(c,m,y)=>{var z,W,be,le;let b=m.trim();if(!b||!Lt.current)return;let k=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",B=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:B,source:y.source},bubbles:!0,composed:!0})),co(zn,k);let F=Lt.current.getMessages().find(ee=>{var me;return((me=ee.toolCall)==null?void 0:me.id)===k});(be=F==null?void 0:F.agentMetadata)!=null&&be.awaitingLocalTool?Lt.current.resolveAskUserQuestion(F,(le=y.structured)!=null?le:b):Lt.current.sendMessage(b)},Hn=c=>{var k;let m=Lt.current;if(!m)return;let y=(k=c.getAttribute("data-tool-call-id"))!=null?k:"",b=m.getMessages().find(B=>{var F;return((F=B.toolCall)==null?void 0:F.id)===y});b&&m.persistAskUserQuestionProgress(b,{answers:di(c,b),currentIndex:Yn(c)})},Ur=c=>Object.entries(c).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Er=c=>{var k,B,F;if(((B=(k=r.features)==null?void 0:k.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let m=Yn(c),y=ds(c);if(m>=y-1)return;let b=(F=Lt.current)==null?void 0:F.getMessages().find(z=>{var W;return((W=z.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 B,F,z,W,be,le,ee,me,Ce,Fe,Ze,Ge,st,at;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let k=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),k==="dismiss"){let Me=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),co(zn,Me);let Te=(F=Lt.current)==null?void 0:F.getMessages().find(qe=>{var T;return((T=qe.toolCall)==null?void 0:T.id)===Me});(z=Te==null?void 0:Te.agentMetadata)!=null&&z.awaitingLocalTool&&((W=Lt.current)==null||W.markAskUserQuestionResolved(Te),(be=Lt.current)==null||be.resolveAskUserQuestion(Te,"(dismissed)"));return}if(k==="pick"){let Me=y.getAttribute("data-option-label");if(!Me)return;let Te=b.getAttribute("data-multi-select")==="true",qe=lo(b);if(qe&&Te){let T=Fo(b)[Yn(b)],Ae=new Set(Array.isArray(T)?T:[]);Ae.has(Me)?Ae.delete(Me):Ae.add(Me),po(b,Array.from(Ae)),Hn(b);return}if(qe){po(b,Me),Hn(b),Er(b);return}if(Te){let T=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",T?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!T);let Ae=b.querySelector('[data-ask-user-action="submit-multi"]');Ae&&(Ae.disabled=al(b).length===0);return}Vn(b,Me,{source:"pick",values:[Me]});return}if(k==="submit-multi"){let Me=al(b);if(Me.length===0)return;Vn(b,Me.join(", "),{source:"multi",values:Me});return}if(k==="open-free-text"){let Me=b.querySelector('[data-ask-free-text-row="true"]');if(Me){Me.classList.remove("persona-hidden");let Te=Me.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus()}return}if(k==="focus-free-text"){let Me=b.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus();return}if(k==="submit-free-text"){let Me=b.querySelector('[data-ask-free-text-input="true"]'),Te=(le=Me==null?void 0:Me.value)!=null?le:"";if(!Te.trim())return;if(lo(b)){po(b,Te.trim()),Hn(b),Er(b);return}Vn(b,Te,{source:"free-text"});return}if(k==="next"||k==="back"){if(!Lt.current)return;let Me=(ee=b.getAttribute("data-tool-call-id"))!=null?ee:"",Te=Lt.current.getMessages().find(Ve=>{var ye;return((ye=Ve.toolCall)==null?void 0:ye.id)===Me});if(!Te)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),T=(Ce=(me=qe==null?void 0:qe.value)==null?void 0:me.trim())!=null?Ce:"";if(T){let Ve=Fo(b)[Yn(b)];(typeof Ve!="string"||Ve!==T)&&po(b,T)}let Ae=k==="next"?1:-1,We=Yn(b)+Ae;pi(b,Te,r,We),Hn(b);return}if(k==="submit-all"){if(!Lt.current)return;let Me=(Fe=b.getAttribute("data-tool-call-id"))!=null?Fe:"",Te=Lt.current.getMessages().find(Ve=>{var ye;return((ye=Ve.toolCall)==null?void 0:ye.id)===Me});if(!Te)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),T=(Ge=(Ze=qe==null?void 0:qe.value)==null?void 0:Ze.trim())!=null?Ge:"";T&&po(b,T);let Ae=di(b,Te);Lt.current.persistAskUserQuestionProgress(Te,{answers:Ae,currentIndex:Yn(b)});let We=Ur(Ae);Vn(b,We||"(submitted)",{source:"submit-all",structured:Ae});return}if(k==="skip"){if(!Lt.current)return;let Me=(st=b.getAttribute("data-tool-call-id"))!=null?st:"",Te=Lt.current.getMessages().find(ye=>{var Mt;return((Mt=ye.toolCall)==null?void 0:Mt.id)===Me});if(!Te)return;let qe=lo(b),T=Yn(b),Ae=ds(b),We=T>=Ae-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),co(zn,Me),(at=Te.agentMetadata)!=null&&at.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Te),Lt.current.resolveAskUserQuestion(Te,"(dismissed)"));return}po(b,"");let Ve=b.querySelector('[data-ask-free-text-input="true"]');if(Ve&&(Ve.value=""),We){let ye=di(b,Te),Mt=Ur(ye);Vn(b,Mt||"(skipped)",{source:"submit-all",structured:ye});return}pi(b,Te,r,T+1),Hn(b);return}}),zn.addEventListener("keydown",c=>{var B;if(c.key!=="Enter")return;let y=c.target;if(!((B=y.matches)!=null&&B.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(lo(b)){po(b,k.trim()),Hn(b),Er(b);return}Vn(b,k,{source:"free-text"})}});let qr=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),B=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];B&&(c.preventDefault(),B.click())};document.addEventListener("keydown",qr);let Bn=null,Rt=null,bn=null,Jn=null,zr=()=>{};function Tr(){Jn==null||Jn(),Jn=null}let Vr=()=>{var F;if(!Bn||!Rt)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){Rt.style.removeProperty("position"),Rt.style.removeProperty("left"),Rt.style.removeProperty("top"),Rt.style.removeProperty("bottom"),Rt.style.removeProperty("width"),Rt.style.removeProperty("z-index");return}let b=Bn.firstElementChild;if(!b||b===Rt)return;let k=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${k}px`,Rt.style.zIndex="5";let B=b.offsetWidth-k/2;Rt.style.left=`${Math.max(0,B)}px`},fr=()=>{},Dn=()=>{var y,b,k,B,F;if(!bt||!Zn(r))return;ui(e,r),mi(e,r),fr();let c=(B=(k=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:k.narrowHostMaxWidth)!=null?B:520,m=V.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),bt.update(Rn),yn?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(F=bt.backdrop)==null||F.classList.add("persona-hidden")):Rn.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),zr()};if(Zn(r)){V.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(re),bt=Bu(r,{onSelect:y=>{var b;return(b=Lt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{yn=!0,Dn()}}),bt.element.classList.add("persona-hidden"),Bn=m,m.appendChild(c),m.appendChild(bt.element),bt.backdrop&&V.appendChild(bt.backdrop),V.appendChild(m),zr=()=>{var b,k,B,F;if(!Bn||!bt)return;if(!(((B=(k=(b=r.features)==null?void 0:b.artifacts)==null?void 0:k.layout)==null?void 0:B.resizable)===!0)){bn==null||bn(),bn=null,Tr(),Rt&&(Rt.remove(),Rt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Rt){let z=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let W=e.ownerDocument,be=(F=W.defaultView)!=null?F:window,le=ee=>{var st,at;if(!bt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||be.innerWidth<=640)return;ee.preventDefault(),Tr();let me=ee.clientX,Ce=bt.element.getBoundingClientRect().width,Fe=(at=(st=r.features)==null?void 0:st.artifacts)==null?void 0:at.layout,Ze=Me=>{let Te=Bn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),T=qe?0:Ou(Bn,be),Ae=qe?0:z.getBoundingClientRect().width||6,We=Ce-(Me.clientX-me),Ve=$u(We,Te,T,Ae,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);bt.element.style.width=`${Ve}px`,bt.element.style.maxWidth="none",Vr()},Ge=()=>{W.removeEventListener("pointermove",Ze),W.removeEventListener("pointerup",Ge),W.removeEventListener("pointercancel",Ge),Jn=null;try{z.releasePointerCapture(ee.pointerId)}catch{}};Jn=Ge,W.addEventListener("pointermove",Ze),W.addEventListener("pointerup",Ge),W.addEventListener("pointercancel",Ge);try{z.setPointerCapture(ee.pointerId)}catch{}};z.addEventListener("pointerdown",le),Rt=z,Bn.insertBefore(z,bt.element),bn=()=>{z.removeEventListener("pointerdown",le)}}if(Rt){let z=Rn.artifacts.length>0&&!yn;Rt.classList.toggle("persona-hidden",!z),Vr()}},fr=()=>{var be,le,ee,me,Ce,Fe,Ze,Ge,st,at,Me,Te,qe,T;if(!S||!bt||((le=(be=r.launcher)==null?void 0:be.sidebarMode)!=null?le:!1)||nn(r)&&Xn(r).reveal==="emerge")return;let b=(ee=e.ownerDocument.defaultView)!=null?ee:window,k=(Ce=(me=r.launcher)==null?void 0:me.mobileFullscreen)!=null?Ce:!0,B=(Ze=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?Ze:640;if(k&&b.innerWidth<=B||!Fu(r,S))return;let F=(at=(st=(Ge=r.launcher)==null?void 0:Ge.width)!=null?st:r.launcherWidth)!=null?at:Un,z=(T=(qe=(Te=(Me=r.features)==null?void 0:Me.artifacts)==null?void 0:Te.layout)==null?void 0:qe.expandedPanelWidth)!=null?T:"min(720px, calc(100vw - 24px))";Rn.artifacts.length>0&&!yn?(V.style.width=z,V.style.maxWidth=z):(V.style.width=F,V.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Wn=new ResizeObserver(()=>{Dn()}),Wn.observe(V))}else V.appendChild(re),_()&&ve&&($e.peekBanner&&ve.appendChild($e.peekBanner),ve.appendChild(_e));e.appendChild(G),ve&&e.appendChild(ve);let tr=()=>{var Ve,ye,Mt,ot,Xt,dn,It,vn,pn,Xe,it,Cn,mn,Co,wo,Ao,Go,Qo,zt,So,to,yt,kn,Wr,wn,Ln,Dt,Ut;if(_()){V.style.width="100%",V.style.maxWidth="100%";let Nt=(ye=(Ve=r.launcher)==null?void 0:Ve.composerBar)!=null?ye:{},Vt=G.dataset.state==="expanded",Pn=(Mt=Nt.expandedSize)!=null?Mt:"anchored";if(!(Vt&&Pn!=="fullscreen")){re.style.background="",re.style.border="",re.style.borderRadius="",re.style.overflow="",re.style.boxShadow="";return}let tn=(Xt=(ot=r.theme)==null?void 0:ot.components)==null?void 0:Xt.panel,br=rs(r),Rr=(Eo,wa)=>{var Ls;return Eo==null||Eo===""?wa:(Ls=ts(br,Eo))!=null?Ls:Eo},xa="1px solid var(--persona-border)",va="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ca="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";re.style.background="var(--persona-surface, #ffffff)",re.style.border=Rr(tn==null?void 0:tn.border,xa),re.style.borderRadius=Rr(tn==null?void 0:tn.borderRadius,Ca),re.style.boxShadow=Rr(tn==null?void 0:tn.shadow,va),re.style.overflow="hidden";return}let c=nn(r),m=(It=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?It:!1,y=c||m||((pn=(vn=r.launcher)==null?void 0:vn.fullHeight)!=null?pn:!1),b=((Xe=r.launcher)==null?void 0:Xe.enabled)===!1,k=(Cn=(it=r.theme)==null?void 0:it.components)==null?void 0:Cn.panel,B=rs(r),F=(Nt,Vt)=>{var Pn;return Nt==null||Nt===""?Vt:(Pn=ts(B,Nt))!=null?Pn:Nt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,W=(wo=(Co=r.launcher)==null?void 0:Co.mobileFullscreen)!=null?wo:!0,be=(Go=(Ao=r.launcher)==null?void 0:Ao.mobileBreakpoint)!=null?Go:640,le=z.innerWidth<=be,ee=W&&le&&S,me=(zt=(Qo=r.launcher)==null?void 0:Qo.position)!=null?zt:"bottom-left",Ce=me==="bottom-left"||me==="top-left",Fe=(to=(So=r.launcher)==null?void 0:So.zIndex)!=null?to:hn,Ze=m||ee?"none":"1px solid var(--persona-border)",Ge=ee?"none":m?Ce?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ge="none",Ze="none");let st=m||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=F(k==null?void 0:k.border,Ze),Me=F(k==null?void 0:k.shadow,Ge),Te=F(k==null?void 0:k.borderRadius,st),qe=Ee.scrollTop;e.style.cssText="",G.style.cssText="",V.style.cssText="",re.style.cssText="",Ee.style.cssText="",_e.style.cssText="";let T=()=>{var Vt;if(qe<=0)return;((Vt=Ee.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(Ee.scrollTop===qe)return;let Pn=Ee.scrollHeight-Ee.clientHeight;Pn<=0||(Ee.scrollTop=Math.min(qe,Pn))})};if(ee){G.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),G.style.cssText=`
23
+ `,O.addEventListener("click",()=>{p=E,S.forEach((_,U)=>{let R=U<E;_.classList.toggle("selected",R),_.setAttribute("aria-checked",U===E-1?"true":"false")})}),S.push(O),k.appendChild(O)}f.appendChild(k);let L=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),E.appendChild(L),f.appendChild(E)}let D=document.createElement("div");D.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{t==null||t(),u.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(p===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let E=(L==null?void 0:L.value.trim())||void 0;await n(p,E),u.remove()}catch(E){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",E)}}),D.appendChild(N),D.appendChild(P),f.appendChild(D),u.appendChild(f),u}function vi(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel: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 k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=o,w.appendChild(k),g.appendChild(w);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=l;let N=document.createElement("span");N.className="persona-feedback-label-high",N.textContent=u,L.appendChild(D),L.appendChild(N);let P=document.createElement("div");P.className="persona-feedback-numbers";let E=[];for(let $=0;$<=10;$++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-number-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`Rating ${$} out of 10`),J.textContent=String($),J.dataset.rating=String($),$<=6?J.classList.add("persona-feedback-detractor"):$<=8?J.classList.add("persona-feedback-passive"):J.classList.add("persona-feedback-promoter"),J.addEventListener("click",()=>{f=$,E.forEach((se,Ie)=>{se.classList.toggle("selected",Ie===$),se.setAttribute("aria-checked",Ie===$?"true":"false")})}),E.push(J),P.appendChild(J)}S.appendChild(L),S.appendChild(P),g.appendChild(S);let O=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=s,O.rows=3,O.setAttribute("aria-label","Additional comments"),$.appendChild(O),g.appendChild($)}let _=document.createElement("div");_.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=i,U.addEventListener("click",()=>{t==null||t(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let $=(O==null?void 0:O.value.trim())||void 0;await n(f,$),p.remove()}catch($){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),_.appendChild(U),_.appendChild(R),g.appendChild(_),p.appendChild(g),p}var gs="persona-chat-history",Df=30*1e3,Nf={"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 Ff(e){var r,o,s;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=(o=Nf[i.type])!=null?o:"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((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&n.push(a);return n}function Ci(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 Of(e){var n,t,r,o,s,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:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.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 $f(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var ml=e=>!e||typeof e!="object"?{}:{...e},Ju=e=>e.map(n=>({...n,streaming:!1})),Ku=(e,n,t)=>{let r=e!=null&&e.markdown?ko(e.markdown):null,o=Xo(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(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."),s=>{var l,u,p;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):r?d=r(a):d=Lo(a),o?o(d):d}};function Gu(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",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=me(t,r,o,s);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 wi=(e,n,t)=>{var Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,Ul,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,Cc,wc,Ac,Sc,Ec;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),o=ea.getForInstance(r.plugins);r.components&&Or.registerAll(r.components);let s=ju(),i=r.persistState===!1?null:(Rl=r.storageAdapter)!=null?Rl: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=ml(y.metadata)),(Hl=y.messages)!=null&&Hl.length&&(r={...r,initialMessages:y.messages}),(Bl=y.artifacts)!=null&&Bl.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Dl=y.selectedArtifactId)!=null?Dl: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:{}});(Nl=c.messages)!=null&&Nl.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:{},Uo()},w=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ta],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Oo.message,Oo.messageAndClick],k=na({parsers:w,handlers:x,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let S=(Ol=(Fl=r.launcher)==null?void 0:Fl.enabled)!=null?Ol:!0,L=(_l=($l=r.launcher)==null?void 0:$l.autoExpand)!=null?_l:!1,D=(jl=r.autoFocusInput)!=null?jl:!1,N=L,P=S,E=(ql=(Ul=r.layout)==null?void 0:Ul.header)==null?void 0:ql.layout,O=!1,_=()=>so(r),U=()=>S||_(),R=_()?!1:S?L:!0,$=!1,J=null,se=()=>{$=!0,J&&clearTimeout(J),J=setTimeout(()=>{$&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),$=!1)},1e4)},Ie=Ku(r,k,se),ke=(Vl=(zl=r.features)==null?void 0:zl.showReasoning)!=null?Vl:!0,Qe=(Kl=(Jl=r.features)==null?void 0:Jl.showToolCalls)!=null?Kl:!0,ge=(Ql=(Gl=r.features)==null?void 0:Gl.showEventStreamToggle)!=null?Ql:!1,pe=(Yl=(Xl=r.features)==null?void 0:Xl.scrollToBottom)!=null?Yl:{},qe=`${(ec=typeof r.persistState=="object"?(Zl=r.persistState)==null?void 0:Zl.keyPrefix:void 0)!=null?ec:"persona-"}event-stream`,te=ge?new Zs(qe):null,Se=(rc=(nc=(tc=r.features)==null?void 0:tc.eventStream)==null?void 0:nc.maxEvents)!=null?rc:2e3,X=ge?new Ys(Se,te):null,ie=null,He=!1,de=null,Re=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 et={onCopy:c=>{var m,y;s.emit("message:copy",c),j!=null&&j.isClientTokenMode()&&j.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;s.emit("message:feedback",c),j!=null&&j.isClientTokenMode()&&j.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=(oc=r.statusIndicator)!=null?oc:{},ae=c=>{var m,y,b,M;return c==="idle"?(m=K.idleText)!=null?m:fn.idle:c==="connecting"?(y=K.connectingText)!=null?y:fn.connecting:c==="connected"?(b=K.connectedText)!=null?b:fn.connected:c==="error"?(M=K.errorText)!=null?M:fn.error:fn[c]};function Oe(c,m,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let M=document.createElement("a");M.href=y.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=m,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=m}let{wrapper:G,panel:V,pillRoot:ve}=pu(r),$e=uu(r,U()),{container:re,body:Ee,messagesWrapper:xe,suggestions:Bt,textarea:Pe,sendButton:ne,sendButtonWrapper:an,composerForm:Ot,statusText:Jt,introTitle:Cr,introSubtitle:pr,closeButton:je,iconHolder:q,headerTitle:we,headerSubtitle:Be,header:De,footer:_e,actionsRow:ct,leftActions:tt,rightActions:wt}=$e,qt=$e.setSendButtonMode,I=$e.micButton,he=$e.micButtonWrapper,fe=$e.attachmentButton,dt=$e.attachmentButtonWrapper,ze=$e.attachmentInput,Wt=$e.attachmentPreviewsContainer;re.classList.add("persona-relative"),Ee.classList.add("persona-relative");let ln=12,At=()=>{var c;return(c=pe.label)!=null?c:""},xt=()=>{var c;return(c=pe.iconName)!=null?c:"arrow-down"},kt=()=>pe.enabled!==!1,ut=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");ut.type="button",ut.style.display="none",ut.setAttribute("data-persona-scroll-to-bottom","true");let Kt=h("span","persona-flex persona-items-center"),wr=h("span","");ut.append(Kt,wr),re.appendChild(ut);let qn=()=>{let m=_e.style.display==="none"?0:_e.offsetHeight;ut.style.bottom=`${m+ln}px`};qn();let _r=()=>{let c=!!At();ut.setAttribute("aria-label",At()||"Jump to latest"),ut.title=At(),ut.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Kt.innerHTML="";let m=me(xt(),"14px","currentColor",2);m?(Kt.appendChild(m),Kt.style.display=""):Kt.style.display="none",wr.textContent=At(),wr.style.display=c?"":"none"};_r();let Ct=null,ur=null,mr=o.find(c=>c.renderHeader);if(mr!=null&&mr.renderHeader){let c=mr.renderHeader({config:r,defaultRenderer:()=>{let m=Dr({config:r,showClose:U()});return Do(re,m,r),m.header},onClose:()=>Ht(!1,"user")});if(c){let m=re.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),De=c)}}let Ar=()=>{var m,y,b,M;if(!X)return;if(He=!0,!ie&&X&&(ie=Wu({buffer:X,getFullHistory:()=>X.getAllFromStore(),onClose:()=>er(),config:r,plugins:o})),ie&&(Ee.style.display="none",(m=_e.parentNode)==null||m.insertBefore(ie.element,_e),ie.update()),gt){gt.style.boxShadow=`inset 0 0 0 1.5px ${Sn.actionIconColor}`;let B=(M=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:M.toggleButtonActive;B&&B.split(/\s+/).forEach(F=>F&&gt.classList.add(F))}let c=()=>{if(!He)return;let B=Date.now();B-Re>=200&&(ie==null||ie.update(),Re=B),de=requestAnimationFrame(c)};Re=0,de=requestAnimationFrame(c),Lr(),s.emit("eventStream:opened",{timestamp:Date.now()})},er=()=>{var c,m,y;if(He){if(He=!1,ie&&ie.element.remove(),Ee.style.display="",gt){gt.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(M=>M&&gt.classList.remove(M))}de!==null&&(cancelAnimationFrame(de),de=null),Lr(),s.emit("eventStream:closed",{timestamp:Date.now()})}},gt=null;if(ge){let c=(ac=(sc=r.features)==null?void 0:sc.eventStream)==null?void 0:ac.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:"");gt=h("button",m),gt.style.width="28px",gt.style.height="28px",gt.style.color=Sn.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&gt.appendChild(y);let b=$e.clearChatButtonWrapper,M=$e.closeButtonWrapper,B=b||M;B&&B.parentNode===De?De.insertBefore(gt,B):De.appendChild(gt),gt.addEventListener("click",()=>{He?er():Ar()})}let mo=c=>{var b,M,B;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:Br).join(","),F.multiple=((M=m.maxFiles)!=null?M:4)>1,F.style.display="none",F.setAttribute("aria-label",(B=m.buttonTooltipText)!=null?B:"Attach files"),c.appendChild(F)}},gr=o.find(c=>c.renderComposer);if(gr!=null&&gr.renderComposer){let c=r.composer,m=gr.renderComposer({config:r,defaultRenderer:()=>ss({config:r}).footer,onSubmit:y=>{var F;if(!j||j.isStreaming())return;let b=y.trim(),M=(F=Ct==null?void 0:Ct.hasAttachments())!=null?F:!1;if(!b&&!M)return;Ss();let B;M&&(B=[],B.push(...Ct.getContentParts()),b&&B.push(Bs(b))),j.sendMessage(b,{contentParts:B}),M&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ze==null||ze.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:((ic=r.voiceRecognition)==null?void 0:ic.enabled)===!0?()=>{ur==null||ur()}:void 0});m&&(_e.replaceWith(m),_e=m)}let go=c=>{let m=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),B=c.querySelector("[data-persona-composer-status]");m&&(Ot=m),y&&(Pe=y),b&&(ne=b),M&&(I=M,he=M.parentElement),B&&(Jt=B);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Bt=F);let z=c.querySelector(".persona-attachment-button");z&&(fe=z,dt=z.parentElement),ze=c.querySelector('input[type="file"]'),Wt=c.querySelector(".persona-attachment-previews");let W=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");W&&(ct=W)};mo(_e),go(_e);let En=(uc=(lc=r.layout)==null?void 0:lc.contentMaxWidth)!=null?uc:_()?(pc=(dc=(cc=r.launcher)==null?void 0:cc.composerBar)==null?void 0:dc.contentMaxWidth)!=null?pc:"720px":void 0;if(En&&(xe.style.maxWidth=En,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%"),En&&Ot&&!_()&&(Ot.style.maxWidth=En,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),En&&Bt&&!_()&&(Bt.style.maxWidth=En,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),En&&Wt&&!_()&&(Wt.style.maxWidth=En,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),(mc=r.attachments)!=null&&mc.enabled&&ze&&Wt){Ct=Bo.fromConfig(r.attachments),Ct.setPreviewsContainer(Wt),ze.addEventListener("change",y=>{let b=y.target;Ct==null||Ct.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=Gu(c);re.appendChild(m)}(()=>{var b,M;let c=(M=(b=r.layout)==null?void 0:b.slots)!=null?M:{},m=B=>{switch(B){case"body-top":return re.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return xe;case"footer-top":return Bt;case"composer":return Ot;case"footer-bottom":return Jt;default:return null}},y=(B,F)=>{var z;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")De.insertBefore(F,De.firstChild);else if(B==="header-right")De.appendChild(F);else{let W=De.querySelector(".persona-flex-col");W?(z=W.parentNode)==null||z.insertBefore(F,W.nextSibling):De.appendChild(F)}break;case"body-top":{let W=Ee.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");W?W.replaceWith(F):Ee.insertBefore(F,Ee.firstChild);break}case"body-bottom":Ee.appendChild(F);break;case"footer-top":Bt.replaceWith(F);break;case"footer-bottom":Jt.replaceWith(F);break;default:break}};for(let[B,F]of Object.entries(c))if(F)try{let z=F({config:r,defaultContent:()=>m(B)});z&&y(B,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,z)}})();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 M=b.getAttribute("data-message-id");if(!M)return;let B=y.getAttribute("data-bubble-type");B==="reasoning"?(is.has(M)?is.delete(M):is.add(M),hu(M,b)):B==="tool"&&(ls.has(M)?ls.delete(M):ls.add(M),yu(M,b,r)),On.delete(M)};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 M=b.getAttribute("data-actions-for");if(!M)return;let B=y.getAttribute("data-action");if(B==="copy"){let W=j.getMessages().find(be=>be.id===M);if(W&&et.onCopy){let be=W.content||"";navigator.clipboard.writeText(be).then(()=>{y.classList.add("persona-message-action-success");let le=me("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ee=me("copy",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),et.onCopy(W)}}else if(B==="upvote"||B==="downvote"){let W=((F=Sr.get(M))!=null?F:null)===B,be=B==="upvote"?"thumbs-up":"thumbs-down";if(W){Sr.delete(M),y.classList.remove("persona-message-action-active");let le=me(be,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=B==="upvote"?"downvote":"upvote",ee=b.querySelector(`[data-action="${le}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ge=me(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(ee.innerHTML="",ee.appendChild(Ge))}Sr.set(M,B),y.classList.add("persona-message-action-active");let ue=me(be,14,"currentColor",2);ue&&(ue.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ue)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Fe=j.getMessages().find(Ze=>Ze.id===M);Fe&&et.onFeedback&&et.onFeedback({type:B,messageId:Fe.id,message:Fe})}}}),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 M=b.getAttribute("data-message-id");if(!M)return;let B=y.getAttribute("data-approval-action");if(!B)return;let F=B==="approve"?"approved":"denied",W=j.getMessages().find(le=>le.id===M);if(!(W!=null&&W.approval))return;let be=b.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),j.resolveApproval(W.approval,F)});let bt=null,Wn=null,Rn={artifacts:[],selectedId:null},yn=!1,Lt={current:null};xe.addEventListener("click",c=>{var ee,ue,Ce,Fe,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||((Ce=(ue=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:ue.onArtifactAction)==null?void 0:Ce.call(ue,{type:"download",artifactId:b}))===!0)return;let B=j.getArtifactById(b),F=B==null?void 0:B.markdown,z=(B==null?void 0:B.title)||"artifact";if(!F){let Ge=y.closest("[data-open-artifact]"),st=Ge==null?void 0:Ge.closest("[data-message-id]"),at=st==null?void 0:st.getAttribute("data-message-id");if(at){let Te=j.getMessages().find(Ue=>Ue.id===at);if(Te!=null&&Te.rawContent)try{let Ue=JSON.parse(Te.rawContent);F=(Fe=Ue==null?void 0:Ue.props)==null?void 0:Fe.markdown,z=((Ze=Ue==null?void 0:Ue.props)==null?void 0:Ze.title)||z}catch{}}}if(!F)return;let W=new Blob([F],{type:"text/markdown"}),be=URL.createObjectURL(W),le=document.createElement("a");le.href=be,le.download=`${z}.md`,le.click(),URL.revokeObjectURL(be)}),xe.addEventListener("click",c=>{var B,F,z;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((z=(F=(B=r.features)==null?void 0:B.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:z.call(F,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),yn=!1,j.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=$e.composerOverlay,Vn=(c,m,y)=>{var z,W,be,le;let b=m.trim();if(!b||!Lt.current)return;let M=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",B=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:b,answers:y.structured,values:(W=y.values)!=null?W:y.source==="multi"?b.split(", "):[b],isFreeText:B,source:y.source},bubbles:!0,composed:!0})),co(zn,M);let F=Lt.current.getMessages().find(ee=>{var ue;return((ue=ee.toolCall)==null?void 0:ue.id)===M});(be=F==null?void 0:F.agentMetadata)!=null&&be.awaitingLocalTool?Lt.current.resolveAskUserQuestion(F,(le=y.structured)!=null?le:b):Lt.current.sendMessage(b)},Hn=c=>{var M;let m=Lt.current;if(!m)return;let y=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",b=m.getMessages().find(B=>{var F;return((F=B.toolCall)==null?void 0:F.id)===y});b&&m.persistAskUserQuestionProgress(b,{answers:di(c,b),currentIndex:Yn(c)})},Ur=c=>Object.entries(c).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Er=c=>{var M,B,F;if(((B=(M=r.features)==null?void 0:M.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let m=Yn(c),y=ds(c);if(m>=y-1)return;let b=(F=Lt.current)==null?void 0:F.getMessages().find(z=>{var W;return((W=z.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 B,F,z,W,be,le,ee,ue,Ce,Fe,Ze,Ge,st,at;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let M=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Me=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),co(zn,Me);let Te=(F=Lt.current)==null?void 0:F.getMessages().find(Ue=>{var T;return((T=Ue.toolCall)==null?void 0:T.id)===Me});(z=Te==null?void 0:Te.agentMetadata)!=null&&z.awaitingLocalTool&&((W=Lt.current)==null||W.markAskUserQuestionResolved(Te),(be=Lt.current)==null||be.resolveAskUserQuestion(Te,"(dismissed)"));return}if(M==="pick"){let Me=y.getAttribute("data-option-label");if(!Me)return;let Te=b.getAttribute("data-multi-select")==="true",Ue=lo(b);if(Ue&&Te){let T=Fo(b)[Yn(b)],Ae=new Set(Array.isArray(T)?T:[]);Ae.has(Me)?Ae.delete(Me):Ae.add(Me),po(b,Array.from(Ae)),Hn(b);return}if(Ue){po(b,Me),Hn(b),Er(b);return}if(Te){let T=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",T?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!T);let Ae=b.querySelector('[data-ask-user-action="submit-multi"]');Ae&&(Ae.disabled=al(b).length===0);return}Vn(b,Me,{source:"pick",values:[Me]});return}if(M==="submit-multi"){let Me=al(b);if(Me.length===0)return;Vn(b,Me.join(", "),{source:"multi",values:Me});return}if(M==="open-free-text"){let Me=b.querySelector('[data-ask-free-text-row="true"]');if(Me){Me.classList.remove("persona-hidden");let Te=Me.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus()}return}if(M==="focus-free-text"){let Me=b.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus();return}if(M==="submit-free-text"){let Me=b.querySelector('[data-ask-free-text-input="true"]'),Te=(le=Me==null?void 0:Me.value)!=null?le:"";if(!Te.trim())return;if(lo(b)){po(b,Te.trim()),Hn(b),Er(b);return}Vn(b,Te,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Lt.current)return;let Me=(ee=b.getAttribute("data-tool-call-id"))!=null?ee:"",Te=Lt.current.getMessages().find(Ve=>{var ye;return((ye=Ve.toolCall)==null?void 0:ye.id)===Me});if(!Te)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),T=(Ce=(ue=Ue==null?void 0:Ue.value)==null?void 0:ue.trim())!=null?Ce:"";if(T){let Ve=Fo(b)[Yn(b)];(typeof Ve!="string"||Ve!==T)&&po(b,T)}let Ae=M==="next"?1:-1,We=Yn(b)+Ae;pi(b,Te,r,We),Hn(b);return}if(M==="submit-all"){if(!Lt.current)return;let Me=(Fe=b.getAttribute("data-tool-call-id"))!=null?Fe:"",Te=Lt.current.getMessages().find(Ve=>{var ye;return((ye=Ve.toolCall)==null?void 0:ye.id)===Me});if(!Te)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),T=(Ge=(Ze=Ue==null?void 0:Ue.value)==null?void 0:Ze.trim())!=null?Ge:"";T&&po(b,T);let Ae=di(b,Te);Lt.current.persistAskUserQuestionProgress(Te,{answers:Ae,currentIndex:Yn(b)});let We=Ur(Ae);Vn(b,We||"(submitted)",{source:"submit-all",structured:Ae});return}if(M==="skip"){if(!Lt.current)return;let Me=(st=b.getAttribute("data-tool-call-id"))!=null?st:"",Te=Lt.current.getMessages().find(ye=>{var Mt;return((Mt=ye.toolCall)==null?void 0:Mt.id)===Me});if(!Te)return;let Ue=lo(b),T=Yn(b),Ae=ds(b),We=T>=Ae-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),co(zn,Me),(at=Te.agentMetadata)!=null&&at.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Te),Lt.current.resolveAskUserQuestion(Te,"(dismissed)"));return}po(b,"");let Ve=b.querySelector('[data-ask-free-text-input="true"]');if(Ve&&(Ve.value=""),We){let ye=di(b,Te),Mt=Ur(ye);Vn(b,Mt||"(skipped)",{source:"submit-all",structured:ye});return}pi(b,Te,r,T+1),Hn(b);return}}),zn.addEventListener("keydown",c=>{var B;if(c.key!=="Enter")return;let y=c.target;if(!((B=y.matches)!=null&&B.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let M=y.value;if(M.trim()){if(lo(b)){po(b,M.trim()),Hn(b),Er(b);return}Vn(b,M,{source:"free-text"})}});let qr=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),B=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];B&&(c.preventDefault(),B.click())};document.addEventListener("keydown",qr);let Bn=null,Rt=null,bn=null,Jn=null,zr=()=>{};function Tr(){Jn==null||Jn(),Jn=null}let Vr=()=>{var F;if(!Bn||!Rt)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){Rt.style.removeProperty("position"),Rt.style.removeProperty("left"),Rt.style.removeProperty("top"),Rt.style.removeProperty("bottom"),Rt.style.removeProperty("width"),Rt.style.removeProperty("z-index");return}let b=Bn.firstElementChild;if(!b||b===Rt)return;let M=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${M}px`,Rt.style.zIndex="5";let B=b.offsetWidth-M/2;Rt.style.left=`${Math.max(0,B)}px`},fr=()=>{},Dn=()=>{var y,b,M,B,F;if(!bt||!Zn(r))return;ui(e,r),mi(e,r),fr();let c=(B=(M=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:M.narrowHostMaxWidth)!=null?B:520,m=V.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),bt.update(Rn),yn?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(F=bt.backdrop)==null||F.classList.add("persona-hidden")):Rn.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),zr()};if(Zn(r)){V.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(re),bt=Bu(r,{onSelect:y=>{var b;return(b=Lt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{yn=!0,Dn()}}),bt.element.classList.add("persona-hidden"),Bn=m,m.appendChild(c),m.appendChild(bt.element),bt.backdrop&&V.appendChild(bt.backdrop),V.appendChild(m),zr=()=>{var b,M,B,F;if(!Bn||!bt)return;if(!(((B=(M=(b=r.features)==null?void 0:b.artifacts)==null?void 0:M.layout)==null?void 0:B.resizable)===!0)){bn==null||bn(),bn=null,Tr(),Rt&&(Rt.remove(),Rt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Rt){let z=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let W=e.ownerDocument,be=(F=W.defaultView)!=null?F:window,le=ee=>{var st,at;if(!bt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||be.innerWidth<=640)return;ee.preventDefault(),Tr();let ue=ee.clientX,Ce=bt.element.getBoundingClientRect().width,Fe=(at=(st=r.features)==null?void 0:st.artifacts)==null?void 0:at.layout,Ze=Me=>{let Te=Bn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),T=Ue?0:Ou(Bn,be),Ae=Ue?0:z.getBoundingClientRect().width||6,We=Ce-(Me.clientX-ue),Ve=$u(We,Te,T,Ae,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);bt.element.style.width=`${Ve}px`,bt.element.style.maxWidth="none",Vr()},Ge=()=>{W.removeEventListener("pointermove",Ze),W.removeEventListener("pointerup",Ge),W.removeEventListener("pointercancel",Ge),Jn=null;try{z.releasePointerCapture(ee.pointerId)}catch{}};Jn=Ge,W.addEventListener("pointermove",Ze),W.addEventListener("pointerup",Ge),W.addEventListener("pointercancel",Ge);try{z.setPointerCapture(ee.pointerId)}catch{}};z.addEventListener("pointerdown",le),Rt=z,Bn.insertBefore(z,bt.element),bn=()=>{z.removeEventListener("pointerdown",le)}}if(Rt){let z=Rn.artifacts.length>0&&!yn;Rt.classList.toggle("persona-hidden",!z),Vr()}},fr=()=>{var be,le,ee,ue,Ce,Fe,Ze,Ge,st,at,Me,Te,Ue,T;if(!S||!bt||((le=(be=r.launcher)==null?void 0:be.sidebarMode)!=null?le:!1)||nn(r)&&Xn(r).reveal==="emerge")return;let b=(ee=e.ownerDocument.defaultView)!=null?ee:window,M=(Ce=(ue=r.launcher)==null?void 0:ue.mobileFullscreen)!=null?Ce:!0,B=(Ze=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?Ze:640;if(M&&b.innerWidth<=B||!Fu(r,S))return;let F=(at=(st=(Ge=r.launcher)==null?void 0:Ge.width)!=null?st:r.launcherWidth)!=null?at:Un,z=(T=(Ue=(Te=(Me=r.features)==null?void 0:Me.artifacts)==null?void 0:Te.layout)==null?void 0:Ue.expandedPanelWidth)!=null?T:"min(720px, calc(100vw - 24px))";Rn.artifacts.length>0&&!yn?(V.style.width=z,V.style.maxWidth=z):(V.style.width=F,V.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Wn=new ResizeObserver(()=>{Dn()}),Wn.observe(V))}else V.appendChild(re),_()&&ve&&($e.peekBanner&&ve.appendChild($e.peekBanner),ve.appendChild(_e));e.appendChild(G),ve&&e.appendChild(ve);let tr=()=>{var Ve,ye,Mt,ot,Xt,dn,It,vn,pn,Xe,it,Cn,mn,Co,wo,Ao,Go,Qo,zt,So,to,yt,kn,Wr,wn,Ln,Dt,Ut;if(_()){V.style.width="100%",V.style.maxWidth="100%";let Nt=(ye=(Ve=r.launcher)==null?void 0:Ve.composerBar)!=null?ye:{},Vt=G.dataset.state==="expanded",Pn=(Mt=Nt.expandedSize)!=null?Mt:"anchored";if(!(Vt&&Pn!=="fullscreen")){re.style.background="",re.style.border="",re.style.borderRadius="",re.style.overflow="",re.style.boxShadow="";return}let tn=(Xt=(ot=r.theme)==null?void 0:ot.components)==null?void 0:Xt.panel,br=rs(r),Rr=(Eo,wa)=>{var Ls;return Eo==null||Eo===""?wa:(Ls=ts(br,Eo))!=null?Ls:Eo},xa="1px solid var(--persona-border)",va="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ca="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";re.style.background="var(--persona-surface, #ffffff)",re.style.border=Rr(tn==null?void 0:tn.border,xa),re.style.borderRadius=Rr(tn==null?void 0:tn.borderRadius,Ca),re.style.boxShadow=Rr(tn==null?void 0:tn.shadow,va),re.style.overflow="hidden";return}let c=nn(r),m=(It=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?It:!1,y=c||m||((pn=(vn=r.launcher)==null?void 0:vn.fullHeight)!=null?pn:!1),b=((Xe=r.launcher)==null?void 0:Xe.enabled)===!1,M=(Cn=(it=r.theme)==null?void 0:it.components)==null?void 0:Cn.panel,B=rs(r),F=(Nt,Vt)=>{var Pn;return Nt==null||Nt===""?Vt:(Pn=ts(B,Nt))!=null?Pn:Nt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,W=(wo=(Co=r.launcher)==null?void 0:Co.mobileFullscreen)!=null?wo:!0,be=(Go=(Ao=r.launcher)==null?void 0:Ao.mobileBreakpoint)!=null?Go:640,le=z.innerWidth<=be,ee=W&&le&&S,ue=(zt=(Qo=r.launcher)==null?void 0:Qo.position)!=null?zt:"bottom-left",Ce=ue==="bottom-left"||ue==="top-left",Fe=(to=(So=r.launcher)==null?void 0:So.zIndex)!=null?to:hn,Ze=m||ee?"none":"1px solid var(--persona-border)",Ge=ee?"none":m?Ce?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ge="none",Ze="none");let st=m||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=F(M==null?void 0:M.border,Ze),Me=F(M==null?void 0:M.shadow,Ge),Te=F(M==null?void 0:M.borderRadius,st),Ue=Ee.scrollTop;e.style.cssText="",G.style.cssText="",V.style.cssText="",re.style.cssText="",Ee.style.cssText="",_e.style.cssText="";let T=()=>{var Vt;if(Ue<=0)return;((Vt=Ee.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(Ee.scrollTop===Ue)return;let Pn=Ee.scrollHeight-Ee.clientHeight;Pn<=0||(Ee.scrollTop=Math.min(Ue,Pn))})};if(ee){G.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),G.style.cssText=`
24
24
  position: fixed !important;
25
25
  inset: 0 !important;
26
26
  width: 100% !important;
@@ -56,7 +56,7 @@
56
56
  overflow: hidden !important;
57
57
  border-radius: 0 !important;
58
58
  border: none !important;
59
- `,Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.overflowY="auto",_e.style.flexShrink="0",O=!0,T();return}let Ae=(kn=(yt=r==null?void 0:r.launcher)==null?void 0:yt.width)!=null?kn:r==null?void 0:r.launcherWidth,We=Ae!=null?Ae:Un;if(!m&&!c)b&&y?(V.style.width="100%",V.style.maxWidth="100%"):(V.style.width=We,V.style.maxWidth=We);else if(c)if(Xn(r).reveal==="emerge"){let Vt=Xn(r).width;V.style.width=Vt,V.style.maxWidth=Vt}else V.style.width="100%",V.style.maxWidth="100%";if(fr(),V.style.boxShadow=Me,V.style.borderRadius=Te,re.style.border=at,re.style.borderRadius=Te,c&&!ee&&(k==null?void 0:k.border)===void 0&&(re.style.border="none",Xn(r).side==="right"?re.style.borderLeft="1px solid var(--persona-border)":re.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%"),G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.height="100%",b&&(G.style.overflow="hidden"),V.style.display="flex",V.style.flexDirection="column",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.maxHeight="100%",V.style.height="100%",V.style.overflow="hidden",re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.overflow="hidden",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.overflowY="auto",_e.style.flexShrink="0"),G.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&&((Wr=dr[me])!=null?Wr:dr["bottom-right"]).split(" ").forEach(Vt=>G.classList.add(Vt)),m){let Nt=(Ln=(wn=r.launcher)==null?void 0:wn.sidebarWidth)!=null?Ln:"420px";G.style.cssText=`
59
+ `,Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.overflowY="auto",_e.style.flexShrink="0",O=!0,T();return}let Ae=(kn=(yt=r==null?void 0:r.launcher)==null?void 0:yt.width)!=null?kn:r==null?void 0:r.launcherWidth,We=Ae!=null?Ae:Un;if(!m&&!c)b&&y?(V.style.width="100%",V.style.maxWidth="100%"):(V.style.width=We,V.style.maxWidth=We);else if(c)if(Xn(r).reveal==="emerge"){let Vt=Xn(r).width;V.style.width=Vt,V.style.maxWidth=Vt}else V.style.width="100%",V.style.maxWidth="100%";if(fr(),V.style.boxShadow=Me,V.style.borderRadius=Te,re.style.border=at,re.style.borderRadius=Te,c&&!ee&&(M==null?void 0:M.border)===void 0&&(re.style.border="none",Xn(r).side==="right"?re.style.borderLeft="1px solid var(--persona-border)":re.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%"),G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.height="100%",b&&(G.style.overflow="hidden"),V.style.display="flex",V.style.flexDirection="column",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.maxHeight="100%",V.style.height="100%",V.style.overflow="hidden",re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.overflow="hidden",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.overflowY="auto",_e.style.flexShrink="0"),G.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&&((Wr=dr[ue])!=null?Wr:dr["bottom-right"]).split(" ").forEach(Vt=>G.classList.add(Vt)),m){let Nt=(Ln=(wn=r.launcher)==null?void 0:wn.sidebarWidth)!=null?Ln:"420px";G.style.cssText=`
60
60
  position: fixed !important;
61
61
  top: 0 !important;
62
62
  bottom: 0 !important;
@@ -97,9 +97,9 @@
97
97
  flex-shrink: 0 !important;
98
98
  border-top: none !important;
99
99
  padding: 8px 16px 12px 16px !important;
100
- `}if(!b&&!c){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Vt=m?"":"padding-top: 1.25em !important;",Pn=m?"":`z-index: ${(Ut=(Dt=r.launcher)==null?void 0:Dt.zIndex)!=null?Ut:hn} !important;`;G.style.cssText+=Nt+Vt+Pn}T()};tr(),no(e,r),ui(e,r),mi(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",qr)});let Gt=null,Qt=null;ft.push(()=>{Gt==null||Gt(),Gt=null,Qt==null||Qt(),Qt=null}),Wn&&ft.push(()=>{Wn==null||Wn.disconnect(),Wn=null}),ft.push(()=>{bn==null||bn(),bn=null,Tr(),Rt&&(Rt.remove(),Rt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),pe&&ft.push(()=>{de!==null&&(cancelAnimationFrame(de),de=null),ie==null||ie.destroy(),ie=null,X==null||X.destroy(),X=null,te=null});let Nn=null,Jr=()=>{Nn&&(Nn(),Nn=null),r.colorScheme==="auto"&&(Nn=qa(()=>{no(e,r)}))};Jr(),ft.push(()=>{Nn&&(Nn(),Nn=null)});let Kn=(gc=r.features)==null?void 0:gc.streamAnimation;if(Kn!=null&&Kn.type&&Kn.type!=="none"){let c=qs(Kn.type,Kn.plugins);c&&(ji(c,e),ft.push(()=>lu(e)))}let nr=Iu(Bt),Fn=null,j,ce=!1,On=Zp(),rr=new Map,hr=new Map,fs=0,or=Va(),sr=0,ar=null,Mr=!1,fo=!1,oa=4,hs=24,sa=80,jo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ys=(hc=(fc=r.voiceRecognition)==null?void 0:fc.autoResume)!=null?hc:!1,Gn=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Tn=()=>{g(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var b,k;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=ml(d.voiceState),m=!!c.active,y=Number((k=c.timestamp)!=null?k:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-y<Df&&setTimeout(()=>{var B,F;mt.active||(mt.manuallyDeactivated=!1,((F=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:F.type)==="runtype"?j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),Gn("restore"),j.isVoiceActive()&&eo()}):bo("restore"))},1e3)},ia=()=>j?Ju(j.getMessages()).filter(c=>!c.__skipPersist):[];function Uo(c){if(!(i!=null&&i.save))return;let y={messages:c?Ju(c):j?ia():[],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 kr=null,la=()=>G.querySelector("#persona-scroll-container")||Ee,ho=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),Mr=!1},bs=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null),fo=!1,ho()},Lr=()=>{if(!kt()||He){ut.parentNode&&ut.remove(),ut.style.display="none";return}ut.parentNode!==re&&re.appendChild(ut),qn();let c=$s(Ee)>0;ut.style.display=or.isFollowing()||!c?"none":""},xs=()=>{or.pause()&&(bs(),Lr())},Kr=()=>{or.resume(),Lr()},Gr=(c=!1)=>{or.isFollowing()&&(!c&&!ce||(ar!==null&&(cancelAnimationFrame(ar),ar=null),fo=!0,ar=requestAnimationFrame(()=>{ar=null,fo=!1,or.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,m=500)=>{let y=c.scrollTop,b=$s(c),k=b-y;if(Math.abs(k)<1){sr=c.scrollTop;return}if(Math.abs(k)>=sa){ho(),Mr=!0,c.scrollTop=b,sr=c.scrollTop,Mr=!1;return}ho();let B=performance.now();Mr=!0;let F=W=>1-Math.pow(1-W,3),z=W=>{if(!or.isFollowing()){ho();return}let be=$s(c);be!==b&&(b=be,k=b-y);let le=W-B,ee=Math.min(le/m,1),me=F(ee),Ce=y+k*me;c.scrollTop=Ce,sr=c.scrollTop,ee<1?kr=requestAnimationFrame(z):(c.scrollTop=b,sr=c.scrollTop,kr=null,Mr=!1)};kr=requestAnimationFrame(z)},da=c=>{let m=new Map;c.forEach(y=>{let b=jo.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&s.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&s.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&s.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):s.emit("approval:requested",{approval:y.approval,message:y}))}),jo.clear(),m.forEach((y,b)=>{jo.set(b,y)})},yo=(c,m,y)=>{var Ge,st,at,Me,Te,qe;let b=document.createElement("div"),B=(()=>{var Ae;let T=o.find(We=>We.renderLoadingIndicator);if(T!=null&&T.renderLoadingIndicator)return T.renderLoadingIndicator;if((Ae=r.loadingIndicator)!=null&&Ae.render)return r.loadingIndicator.render})(),F=(T,Ae)=>Ae==null?!1:typeof Ae=="string"?(T.textContent=Ae,!0):(T.appendChild(Ae),!0),z=new Set,W=new Set,be=o.some(T=>T.renderAskUserQuestion),le=[],ee=[],me=r.enableComponentStreaming!==!1;if(m.forEach(T=>{var vn,pn,Xe,it,Cn,mn,Co,wo,Ao,Go,Qo,zt,So,to;z.add(T.id);let Ae=be&&Nr(T),We=!Ae&&T.role==="assistant"&&!T.variant&&me&&yi(T);if(!We&&hr.has(T.id)){let yt=c.querySelector(`#wrapper-${T.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),hr.delete(T.id)}let Ve=Nr(T)?`:${(vn=T.agentMetadata)!=null&&vn.askUserQuestionAnswered?"a":"u"}:${(pn=T.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(T.agentMetadata.askUserQuestionAnswers).length:0}`:"",ye=Yp(T,fs)+Ve,Mt=Ae||We?null:eu(On,T.id,ye);if(Mt){b.appendChild(Mt.cloneNode(!0)),Nr(T)&&((Xe=T.toolCall)!=null&&Xe.id)&&((it=T.agentMetadata)==null?void 0:it.awaitingLocalTool)===!0&&!((Cn=T.agentMetadata)!=null&&Cn.askUserQuestionAnswered)&&(W.add(T.toolCall.id),ps(T,r,$e.composerOverlay));return}let ot=null,Xt=o.find(yt=>!!(T.variant==="reasoning"&&yt.renderReasoning||T.variant==="tool"&&yt.renderToolCall||T.variant==="approval"&&yt.renderApproval||!T.variant&&yt.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if(Nr(T)&&((Co=T.agentMetadata)==null?void 0:Co.askUserQuestionAnswered)===!0){rr.delete(T.id);let yt=c.querySelector(`#wrapper-${T.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if(Nr(T)&&((Ao=(wo=r.features)==null?void 0:wo.askUserQuestion)==null?void 0:Ao.enabled)!==!1){let yt=o.find(kn=>typeof kn.renderAskUserQuestion=="function");if(yt&&Lt.current){let kn=rr.get(T.id),Wr=kn!==ye,wn=null;if(Wr){let{payload:Ut,complete:Nt}=Fr(T),Vt=T.id,Pn=()=>{var _n;return(_n=Lt.current)==null?void 0:_n.getMessages().find(tn=>tn.id===Vt)};wn=yt.renderAskUserQuestion({message:T,payload:Ut,complete:Nt,resolve:_n=>{var br;let tn=Pn();tn&&((br=Lt.current)==null||br.resolveAskUserQuestion(tn,_n))},dismiss:()=>{var tn,br,Rr;let _n=Pn();(tn=_n==null?void 0:_n.agentMetadata)!=null&&tn.awaitingLocalTool&&((br=Lt.current)==null||br.markAskUserQuestionResolved(_n),(Rr=Lt.current)==null||Rr.resolveAskUserQuestion(_n,"(dismissed)"))},config:r})}let Ln=kn!=null;if(Wr&&wn===null&&!Ln){((Go=T.agentMetadata)==null?void 0:Go.awaitingLocalTool)===!0&&!((Qo=T.agentMetadata)!=null&&Qo.askUserQuestionAnswered)&&(W.add(T.toolCall.id),ps(T,r,$e.composerOverlay));return}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${T.id}`,Dt.setAttribute("data-wrapper-id",T.id),Dt.setAttribute("data-ask-plugin-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),b.appendChild(Dt),le.push({messageId:T.id,fingerprint:ye,bubble:wn});return}else{((zt=T.agentMetadata)==null?void 0:zt.awaitingLocalTool)===!0&&!((So=T.agentMetadata)!=null&&So.askUserQuestionAnswered)&&(W.add(T.toolCall.id),ps(T,r,$e.composerOverlay));return}}else if(Xt)if(T.variant==="reasoning"&&T.reasoning&&Xt.renderReasoning){if(!Le)return;ot=Xt.renderReasoning({message:T,defaultRenderer:()=>Yi(T,r),config:r})}else if(T.variant==="tool"&&T.toolCall&&Xt.renderToolCall){if(!Qe)return;ot=Xt.renderToolCall({message:T,defaultRenderer:()=>Zi(T,r),config:r})}else if(T.variant==="approval"&&T.approval&&Xt.renderApproval){if(r.approval===!1)return;ot=Xt.renderApproval({message:T,defaultRenderer:()=>il(T,r),config:r})}else Xt.renderMessage&&(ot=Xt.renderMessage({message:T,defaultRenderer:()=>{let yt=as(T,y,dn,r.messageActions,et,{loadingIndicatorRenderer:B,widgetConfig:r});return T.role!=="user"&&dl(yt,T,r,j),yt},config:r}));if(!ot&&We){let yt=bi(T);if(yt){let kn=hr.get(T.id),Wr=kn!==ye,wn=r.wrapComponentDirectiveInBubble!==!1,Ln=null;if(Wr){let Dt=hi(yt,{config:r,message:T,transform:y});if(Dt)if(wn){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-${T.id}`,Ut.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let Nt=document.createElement("div");Nt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Nt.innerHTML=y({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),Ut.appendChild(Nt)}Ut.appendChild(Dt),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-${T.id}`,Ut.setAttribute("data-message-id",T.id),Ut.setAttribute("data-persona-component-directive","true"),T.content&&T.content.trim()){let Nt=document.createElement("div");Nt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Nt.innerHTML=y({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),Ut.appendChild(Nt)}Ut.appendChild(Dt),Ln=Ut}}if(Ln||kn!=null){let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${T.id}`,Dt.setAttribute("data-wrapper-id",T.id),Dt.setAttribute("data-component-directive-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),wn||Dt.classList.add("persona-w-full"),b.appendChild(Dt),ee.push({messageId:T.id,fingerprint:ye,bubble:Ln});return}}}if(!ot)if(T.variant==="reasoning"&&T.reasoning){if(!Le)return;ot=Yi(T,r)}else if(T.variant==="tool"&&T.toolCall){if(!Qe)return;ot=Zi(T,r)}else if(T.variant==="approval"&&T.approval){if(r.approval===!1)return;ot=il(T,r)}else{let yt=(to=r.layout)==null?void 0:to.messages;yt!=null&&yt.renderUserMessage&&T.role==="user"?ot=yt.renderUserMessage({message:T,config:r,streaming:!!T.streaming}):yt!=null&&yt.renderAssistantMessage&&T.role==="assistant"?ot=yt.renderAssistantMessage({message:T,config:r,streaming:!!T.streaming}):ot=as(T,y,yt,r.messageActions,et,{loadingIndicatorRenderer:B,widgetConfig:r}),T.role!=="user"&&ot&&dl(ot,T,r,j)}let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-${T.id}`,It.setAttribute("data-wrapper-id",T.id),T.role==="user"&&It.classList.add("persona-justify-end"),(ot==null?void 0:ot.getAttribute("data-persona-component-directive"))==="true"&&It.classList.add("persona-w-full"),It.appendChild(ot),tu(On,T.id,ye,It),b.appendChild(It)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ae=>{let We=Ae.getAttribute("data-persona-ask-sheet-for");We&&!W.has(We)&&co($e.composerOverlay,We)}),(st=(Ge=r.features)==null?void 0:Ge.toolCallDisplay)!=null&&st.grouped){let T=[],Ae=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Qe){Ae.push(We);return}Ae.length>1&&T.push(Ae),Ae=[]}),Ae.length>1&&T.push(Ae),T.forEach((We,Ve)=>{var pn,Xe;let ye=We.map(it=>Array.from(b.children).find(Cn=>Cn instanceof HTMLElement&&Cn.getAttribute("data-wrapper-id")===it.id)).filter(it=>!!it);if(ye.length<2)return;let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id=`wrapper-tool-group-${Ve}-${We[0].id}`,Mt.setAttribute("data-wrapper-id",`tool-group-${Ve}-${We[0].id}`);let ot=document.createElement("div");ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",ot.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${We.length} tools`,It=(Xe=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Xe.call(pn,{messages:We,toolCalls:We.map(it=>it.toolCall).filter(it=>!!it),defaultSummary:dn,config:r});F(Xt,It)||(Xt.textContent=dn);let vn=document.createElement("div");vn.className="persona-tool-group-stack persona-flex persona-flex-col",ot.append(Xt,vn),Mt.appendChild(ot),ye[0].before(Mt),ye.forEach((it,Cn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Cn<ye.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(it),vn.appendChild(mn)})})}nu(On,z);let Ce=m.some(T=>T.role==="assistant"&&T.streaming),Fe=m[m.length-1],Ze=(Fe==null?void 0:Fe.role)==="assistant"&&!Fe.streaming&&Fe.variant!=="approval";if(ce&&m.some(T=>T.role==="user")&&!Ce&&!Ze){let T={config:r,streaming:!0,location:"standalone",defaultRenderer:No},Ae=o.find(Ve=>Ve.renderLoadingIndicator),We=null;if(Ae!=null&&Ae.renderLoadingIndicator&&(We=Ae.renderLoadingIndicator(T)),We===null&&((at=r.loadingIndicator)!=null&&at.render)&&(We=r.loadingIndicator.render(T)),We===null&&(We=No()),We){let Ve=document.createElement("div"),ye=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;Ve.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(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ve.appendChild(We);let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id="wrapper-typing-indicator",Mt.setAttribute("data-wrapper-id","typing-indicator"),Mt.appendChild(Ve),b.appendChild(Mt)}}if(!ce&&m.length>0){let T=m[m.length-1],Ae={config:r,lastMessage:T,messageCount:m.length},We=o.find(ye=>ye.renderIdleIndicator),Ve=null;if(We!=null&&We.renderIdleIndicator&&(Ve=We.renderIdleIndicator(Ae)),Ve===null&&((Te=r.loadingIndicator)!=null&&Te.renderIdle)&&(Ve=r.loadingIndicator.renderIdle(Ae)),Ve){let ye=document.createElement("div"),Mt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;ye.className=Mt?["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(Ve);let ot=document.createElement("div");ot.className="persona-flex",ot.id="wrapper-idle-indicator",ot.setAttribute("data-wrapper-id","idle-indicator"),ot.appendChild(ye),b.appendChild(ot)}}if(za(c,b),le.length>0)for(let{messageId:T,fingerprint:Ae,bubble:We}of le){let Ve=c.querySelector(`#wrapper-${T}`);Ve&&We!==null&&(Ve.replaceChildren(We),Ve.setAttribute("data-bubble-fp",Ae),rr.set(T,Ae))}if(rr.size>0)for(let T of rr.keys())z.has(T)||rr.delete(T);if(ee.length>0)for(let{messageId:T,fingerprint:Ae,bubble:We}of ee){let Ve=c.querySelector(`#wrapper-${T}`);Ve&&We!==null&&(Ve.replaceChildren(We),Ve.setAttribute("data-bubble-fp",Ae),hr.set(T,Ae))}if(hr.size>0)for(let T of hr.keys())z.has(T)||hr.delete(T)},Qr=null,pa=()=>{var y;if(Qr)return;let c=b=>{let k=b.composedPath();k.includes(G)||ve&&k.includes(ve)||Ht(!1,"user")};Qr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},vs=()=>{var m;if(!Qr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Qr,!0),Qr=null};ft.push(()=>vs());let Xr=null,ua=()=>{var y;if(Xr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Ht(!1,"user"))};Xr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},Cs=()=>{var m;if(!Xr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Xr,!0),Xr=null};ft.push(()=>Cs());let Yr=!1,ws=new Set,ma=()=>{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 st,at,Me,Te;if(!_())return;let c=$e.peekBanner,m=$e.peekTextNode;if(!c||!m)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let y=(st=j==null?void 0:j.getMessages())!=null?st:[],b;for(let qe=y.length-1;qe>=0;qe--){let T=y[qe];if(T.role==="assistant"&&T.content){b=T;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let k=b.content,B=!!b.streaming,F=ma(),z=Ga(F),W=z.type!=="none"?qs(z.type,F==null?void 0:F.plugins):null,be=((at=W==null?void 0:W.isAnimating)==null?void 0:at.call(W,b))===!0,le=W!==null&&(B||be);le&&W&&!ws.has(W.name)&&(ji(W,e),ws.add(W.name));let ee=le&&(W!=null&&W.containerClass)?W.containerClass:null,me=(Me=m.dataset.personaPeekStreamClass)!=null?Me:null;me&&me!==ee&&(m.classList.remove(me),delete m.dataset.personaPeekStreamClass),ee&&me!==ee&&(m.classList.add(ee),m.dataset.personaPeekStreamClass=ee),le?(m.style.setProperty("--persona-stream-step",`${z.speed}ms`),m.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Ce=le?Qa(k,z.buffer,W,b,B):k;if(le&&z.placeholder==="skeleton"&&B&&(!Ce||!Ce.trim())){let qe=document.createElement("div"),T=Vs();T.classList.add("persona-pill-peek__skeleton"),qe.appendChild(T),za(m,qe)}else{let qe=Math.max(0,Ce.length-100),T=Ce.length>100?Ce.slice(-100):Ce,Ae=Lo(T);if(!le||!W){let We=Ce.length>100?`\u2026${T}`:T;m.textContent!==We&&(m.textContent=We)}else{let We=Ae;(W.wrap==="char"||W.wrap==="word")&&(We=zs(Ae,W.wrap,`peek-${b.id}`,{skipTags:W.skipTags,startIndex:qe}));let Ve=document.createElement("div");if(Ve.innerHTML=We,W.useCaret&&T.length>0){let ye=Xa(),Mt=Ve.querySelectorAll(".persona-stream-char, .persona-stream-word"),ot=Mt[Mt.length-1];ot!=null&&ot.parentNode?ot.parentNode.insertBefore(ye,ot.nextSibling):Ve.appendChild(ye)}za(m,Ve),(Te=W.onAfterRender)==null||Te.call(W,{container:m,bubble:c,messageId:b.id,message:b,speed:z.speed,duration:z.duration})}}let Ge=ce||Yr;c.classList.toggle("persona-pill-peek--visible",Ge)};if(_()){let c=$e.peekBanner;if(c){let b=k=>{k.preventDefault(),k.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Yr||(Yr=!0,Pr())},y=()=>{Yr&&(Yr=!1,Pr())};V.addEventListener("pointerenter",m),V.addEventListener("pointerleave",y),ft.push(()=>{V.removeEventListener("pointerenter",m),V.removeEventListener("pointerleave",y)}),ve&&(ve.addEventListener("pointerenter",m),ve.addEventListener("pointerleave",y),ft.push(()=>{ve.removeEventListener("pointerenter",m),ve.removeEventListener("pointerleave",y)}))}let ga=c=>{var me,Ce,Fe,Ze,Ge,st,at,Me;let m=(Ce=(me=r.launcher)==null?void 0:me.composerBar)!=null?Ce:{},y=(Fe=m.expandedSize)!=null?Fe:"anchored",b=(Ze=m.bottomOffset)!=null?Ze:"16px",k=m.collapsedMaxWidth,B=(Ge=m.expandedMaxWidth)!=null?Ge:"880px",F=(st=m.expandedTopOffset)!=null?st:"5vh",z=(at=m.modalMaxWidth)!=null?at:"880px",W=(Me=m.modalMaxHeight)!=null?Me:"min(90vh, 800px)",be="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",ee=G.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",ve){let Te=ve.style;Te.bottom=b,Te.width=k!=null?k:""}if(c&&y!=="fullscreen"){if(y==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=z,ee.maxWidth=be,ee.maxHeight=W,ee.height=W;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${b} + ${le})`,ee.top=F,ee.width=B,ee.maxWidth=be}},Zr=()=>{var W,be,le,ee,me,Ce,Fe,Ze;if(!U())return;if(_()){let st=(le=((be=(W=r.launcher)==null?void 0:W.composerBar)!=null?be:{}).expandedSize)!=null?le:"anchored",at=R?"expanded":"collapsed";G.dataset.state=at,G.dataset.expandedSize=st,ve&&(ve.dataset.state=at,ve.dataset.expandedSize=st),G.style.removeProperty("display"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ga(R),re.style.display=R?"flex":"none",tr(),R?(pa(),ua()):(vs(),Cs()),Pr();return}let c=nn(r),m=(ee=e.ownerDocument.defaultView)!=null?ee:window,y=(Ce=(me=r.launcher)==null?void 0:me.mobileBreakpoint)!=null?Ce:640,b=(Ze=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ze:!0,k=m.innerWidth<=y,B=b&&k&&S,F=Xn(r).reveal;R?(G.style.removeProperty("display"),G.style.display=c?"flex":"",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0"),V.classList.add("persona-scale-100","persona-opacity-100"),H?H.element.style.display="none":A&&(A.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!B?(G.style.removeProperty("display"),G.style.display="flex",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.setProperty("display","none","important"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.display="",G.classList.add("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100"),V.classList.add("persona-scale-95","persona-opacity-0")),H?H.element.style.display=c?"none":"":A&&(A.style.display=c?"none":""))},Ht=(c,m="user")=>{var B,F;if(!U()||R===c)return;let y=R;R=c,Zr();let b=(()=>{var Fe,Ze,Ge,st,at,Me,Te,qe,T,Ae;let z=(Ze=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?Ze:!1,W=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,be=(at=(st=r.launcher)==null?void 0:st.mobileFullscreen)!=null?at:!0,le=(Te=(Me=r.launcher)==null?void 0:Me.mobileBreakpoint)!=null?Te:640,ee=W.innerWidth<=le,me=nn(r)&&be&&ee,Ce=_()&&((Ae=(T=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:T.expandedSize)!=null?Ae:"fullscreen")==="fullscreen";return z||be&&ee&&S||me||Ce})();if(R&&b){if(!Gt){let z=e.getRootNode(),W=z instanceof ShadowRoot?z.host:e.closest(".persona-host");W&&(Gt=Ui(W,(F=(B=r.launcher)==null?void 0:B.zIndex)!=null?F:hn))}Qt||(Qt=qi(e.ownerDocument))}else R||(Gt==null||Gt(),Gt=null,Qt==null||Qt(),Qt=null);R&&(Q(),Gr(!0));let k={open:R,source:m,timestamp:Date.now()};R&&!y?s.emit("widget:opened",k):!R&&y&&s.emit("widget:closed",k),s.emit("widget:state",{open:R,launcherEnabled:S,voiceActive:mt.active,streaming:j.isStreaming()})},qo=c=>{qt(c?"stop":"send"),I&&(I.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=()=>{mt.active||Pe&&Pe.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>zo(),200)});let As=()=>{var y,b,k,B,F,z,W,be,le,ee,me;Cr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",pr.textContent=(B=(k=r.copy)==null?void 0:k.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",Pe.placeholder=(z=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?z:"How can I help...";let c=Ee.querySelector("[data-persona-intro-card]");if(c){let Ce=((W=r.copy)==null?void 0:W.showWelcomeCard)!==!1;c.style.display=Ce?"":"none",Ce?(Ee.classList.remove("persona-gap-3"),Ee.classList.add("persona-gap-6")):(Ee.classList.remove("persona-gap-6"),Ee.classList.add("persona-gap-3"))}!((le=(be=r.sendButton)==null?void 0:be.useIcon)!=null&&le)&&!(j!=null&&j.isStreaming())&&(ne.textContent=(me=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?me:"Send"),Pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Pe.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,fa=()=>{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(j=new es(r,{onMessagesChanged(c){yo(xe,c,Ie),fa(),j&&(c.some(k=>k.role==="user")?nr.render([],j,Pe,c):nr.render(r.suggestionChips,j,Pe,c,r.suggestionChipsConfig)),Gr(!ce),da(c);let m=[...c].reverse().find(b=>b.role==="user"),y=mt.lastUserMessageId;m&&m.id!==y&&(mt.lastUserMessageId=m.id,s.emit("user:message",m)),mt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Uo(c),Pr()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Oe(Jt,(k=>{var B,F,z,W;return k==="idle"?(B=m.idleText)!=null?B:fn.idle:k==="connecting"?(F=m.connectingText)!=null?F:fn.connecting:k==="connected"?(z=m.connectedText)!=null?z:fn.connected:k==="error"?(W=m.errorText)!=null?W:fn.error:fn[k]})(c),m,c)},onStreamingChanged(c){ce=c,qo(c),j&&yo(xe,j.getMessages(),Ie),c||Gr(!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(),ya();break;case"speaking":lr(),ba();break;default:c==="idle"&&j.isBargeInActive()?(lr(),eo(),I==null||I.setAttribute("aria-label","End voice session")):(mt.active=!1,lr(),Gn("system"),Tn());break}},onArtifactsState(c){Rn=c,Dn(),Uo()}}),Lt.current=j,((bc=(yc=r.voiceRecognition)==null?void 0:yc.provider)==null?void 0:bc.type)==="runtype")try{j.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&j.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(X||r.onSSEEvent)&&j.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=ml(c.metadata),M.syncFromMetadata()),(m=c.messages)!=null&&m.length&&j.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&j.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Ss=()=>{var m,y,b;!_()||R||!((b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Ht(!0,"auto")},Es=c=>{var k;if(c.preventDefault(),j.isStreaming()){j.cancel();return}let m=Pe.value.trim(),y=(k=Ct==null?void 0:Ct.hasAttachments())!=null?k:!1;if(!m&&!y)return;Ss();let b;y&&(b=[],b.push(...Ct.getContentParts()),m&&b.push(Bs(m))),Pe.value="",Pe.style.height="auto",j.sendMessage(m,{contentParts:b}),y&&Ct.clearAttachments()},Ts=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),ne.click())},Ms=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!Ct)return;let m=Ff(c.clipboardData);m.length!==0&&(c.preventDefault(),await Ct.handleFiles(m))},xn=null,$n=!1,Ir=null,nt=null,ks=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,bo=(c="user")=>{var B,F,z,W,be,le,ee;if($n||j.isStreaming())return;let m=ks();if(!m)return;xn=new m;let b=(F=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?F:2e3;xn.continuous=!0,xn.interimResults=!0,xn.lang="en-US";let k=Pe.value;xn.onresult=me=>{let Ce="",Fe="";for(let Ge=0;Ge<me.results.length;Ge++){let st=me.results[Ge],at=st[0].transcript;st.isFinal?Ce+=at+" ":Fe=at}let Ze=k+Ce+Fe;Pe.value=Ze,Ir&&clearTimeout(Ir),(Ce||Fe)&&(Ir=window.setTimeout(()=>{let Ge=Pe.value.trim();Ge&&xn&&$n&&(ir(),Pe.value="",Pe.style.height="auto",j.sendMessage(Ge,{viaVoice:!0}))},b))},xn.onerror=me=>{me.error!=="no-speech"&&ir()},xn.onend=()=>{if($n){let me=Pe.value.trim();me&&me!==k.trim()&&(Pe.value="",Pe.style.height="auto",j.sendMessage(me,{viaVoice:!0})),ir()}};try{if(xn.start(),$n=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),Gn(c),Tn(),I){let me=(z=r.voiceRecognition)!=null?z:{};nt={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(W=me.iconName)!=null?W:"mic",iconSize:parseFloat((ee=(le=me.iconSize)!=null?le:(be=r.sendButton)==null?void 0:be.size)!=null?ee:"40")||24};let Ce=me.recordingBackgroundColor,Fe=me.recordingIconColor,Ze=me.recordingBorderColor;if(I.classList.add("persona-voice-recording"),I.style.backgroundColor=Ce!=null?Ce:"var(--persona-voice-recording-bg, #ef4444)",I.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let Ge=I.querySelector("svg");Ge&&Ge.setAttribute("stroke",Fe)}Ze&&(I.style.borderColor=Ze),I.setAttribute("aria-label","Stop voice recognition")}}catch{ir("system")}},ir=(c="user")=>{if($n){if($n=!1,Ir&&(clearTimeout(Ir),Ir=null),xn){try{xn.stop()}catch{}xn=null}if(mt.active=!1,Gn(c),Tn(),I){if(I.classList.remove("persona-voice-recording"),nt){I.style.backgroundColor=nt.backgroundColor,I.style.color=nt.color,I.style.borderColor=nt.borderColor;let m=I.querySelector("svg");m&&m.setAttribute("stroke",nt.color||"currentColor"),nt=null}I.setAttribute("aria-label","Start voice recognition")}}},ha=(c,m)=>{var st,at,Me,Te,qe,T,Ae,We;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((st=c==null?void 0:c.provider)==null?void 0:st.type)==="runtype";if(!(y||b))return null;let B=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 z=(at=c==null?void 0:c.iconName)!=null?at:"mic",W=(Me=m==null?void 0:m.size)!=null?Me:"40px",be=(Te=c==null?void 0:c.iconSize)!=null?Te:W,le=parseFloat(be)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:m==null?void 0:m.backgroundColor,me=(T=c==null?void 0:c.iconColor)!=null?T: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 Fe=ge(z,le,me||"currentColor",1.5);Fe?F.appendChild(Fe):F.textContent="\u{1F3A4}",ee?F.style.backgroundColor=ee: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),B.appendChild(F);let Ze=(Ae=c==null?void 0:c.tooltipText)!=null?Ae:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&Ze){let Ve=h("div","persona-send-button-tooltip");Ve.textContent=Ze,B.appendChild(Ve)}return{micButton:F,micButtonWrapper:B}},Vo=()=>{var m,y,b,k,B;if(!I||nt)return;let c=(m=r.voiceRecognition)!=null?m:{};nt={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((B=(k=c.iconSize)!=null?k:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Jo=(c,m)=>{var B,F,z,W,be;if(!I)return;let y=I.querySelector("svg");y&&y.remove();let b=(be=nt==null?void 0:nt.iconSize)!=null?be:parseFloat((W=(z=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?z:(F=r.sendButton)==null?void 0:F.size)!=null?W:"40")||24,k=ge(c,b,m,1.5);k&&I.appendChild(k)},xo=()=>{I&&I.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},eo=()=>{var k;if(!I)return;Vo();let c=(k=r.voiceRecognition)!=null?k:{},m=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(xo(),I.classList.add("persona-voice-recording"),I.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",I.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let B=I.querySelector("svg");B&&B.setAttribute("stroke",y)}b&&(I.style.borderColor=b),I.setAttribute("aria-label","Stop voice recognition")},ya=()=>{var z,W,be,le,ee,me,Ce,Fe;if(!I)return;Vo();let c=(z=r.voiceRecognition)!=null?z:{},m=j.getVoiceInterruptionMode(),y=(W=c.processingIconName)!=null?W:"loader",b=(le=(be=c.processingIconColor)!=null?be:nt==null?void 0:nt.color)!=null?le:"",k=(me=(ee=c.processingBackgroundColor)!=null?ee:nt==null?void 0:nt.backgroundColor)!=null?me:"",B=(Fe=(Ce=c.processingBorderColor)!=null?Ce:nt==null?void 0:nt.borderColor)!=null?Fe:"";xo(),I.classList.add("persona-voice-processing"),I.style.backgroundColor=k,I.style.borderColor=B;let F=b||"currentColor";I.style.color=F,Jo(y,F),I.setAttribute("aria-label","Processing voice input"),m==="none"&&(I.style.cursor="default")},ba=()=>{var be,le,ee,me,Ce,Fe,Ze,Ge,st,at,Me,Te;if(!I)return;Vo();let c=(be=r.voiceRecognition)!=null?be:{},m=j.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:y,k=(Fe=c.speakingIconColor)!=null?Fe:m==="barge-in"?(me=(ee=c.recordingIconColor)!=null?ee:nt==null?void 0:nt.color)!=null?me:"":(Ce=nt==null?void 0:nt.color)!=null?Ce:"",B=(st=c.speakingBackgroundColor)!=null?st:m==="barge-in"?(Ze=c.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(Ge=nt==null?void 0:nt.backgroundColor)!=null?Ge:"",F=(Te=c.speakingBorderColor)!=null?Te:m==="barge-in"?(at=c.recordingBorderColor)!=null?at:"":(Me=nt==null?void 0:nt.borderColor)!=null?Me:"";xo(),I.classList.add("persona-voice-speaking"),I.style.backgroundColor=B,I.style.borderColor=F;let z=k||"currentColor";I.style.color=z,Jo(b,z);let W=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";I.setAttribute("aria-label",W),m==="none"&&(I.style.cursor="default"),m==="barge-in"&&I.classList.add("persona-voice-recording")},lr=()=>{var c,m,y;I&&(xo(),nt&&(I.style.backgroundColor=(c=nt.backgroundColor)!=null?c:"",I.style.color=(m=nt.color)!=null?m:"",I.style.borderColor=(y=nt.borderColor)!=null?y:"",Jo(nt.iconName,nt.color||"currentColor"),nt=null),I.style.cursor="",I.setAttribute("aria-label","Start voice recognition"))},vo=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let y=j.getVoiceStatus(),b=j.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){j.stopVoicePlayback();return}if(j.isBargeInActive()){j.stopVoicePlayback(),j.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Tn(),Gn("user"),lr()});return}j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),mt.manuallyDeactivated=!j.isVoiceActive(),Tn(),Gn("user"),j.isVoiceActive()?eo():lr()});return}if($n){let y=Pe.value.trim();mt.manuallyDeactivated=!0,Tn(),ir("user"),y&&(Pe.value="",Pe.style.height="auto",j.sendMessage(y))}else mt.manuallyDeactivated=!1,Tn(),bo("user")};ur=vo,I&&(I.addEventListener("click",vo),ft.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(j.isVoiceActive()&&j.toggleVoice(),lr()):ir("system"),I&&I.removeEventListener("click",vo)}));let Ko=s.on("assistant:complete",()=>{ys&&(mt.active||mt.manuallyDeactivated||ys==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!mt.active&&!mt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),Gn("auto"),j.isVoiceActive()&&eo()}):bo("auto"))},600))});ft.push(Ko);let Je=s.on("action:resubmit",()=>{setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)});ft.push(Je);let C=()=>{Ht(!R,"user")},H=null,A=null;if(S&&!_()){let c=o.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Ks(r,C).element,onToggle:C});m&&(A=m)}A||(H=Ks(r,C))}H?e.appendChild(H.element):A&&e.appendChild(A),Zr(),nr.render(r.suggestionChips,j,Pe,void 0,r.suggestionChipsConfig),As(),qo(j.isStreaming()),Gr(!0),aa(),D&&(!S||_()?setTimeout(()=>zo(),0):R&&setTimeout(()=>zo(),200));let Q=()=>{var W,be,le,ee,me,Ce,Fe,Ze,Ge,st,at,Me,Te,qe,T,Ae,We,Ve,ye,Mt,ot,Xt;if(_()){qn(),Zr();return}let c=nn(r),m=(be=(W=r.launcher)==null?void 0:W.sidebarMode)!=null?be:!1,y=c||m||((ee=(le=r.launcher)==null?void 0:le.fullHeight)!=null?ee:!1),b=(me=e.ownerDocument.defaultView)!=null?me:window,k=(Fe=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Fe:!0,B=(Ge=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?Ge:640,F=b.innerWidth<=B,z=k&&F&&S;try{if(z){tr(),no(e,r);return}if(O&&(O=!1,tr(),no(e,r)),!S&&!c){V.style.height="",V.style.width="";return}if(!m&&!c){let dn=(at=(st=r==null?void 0:r.launcher)==null?void 0:st.width)!=null?at:r==null?void 0:r.launcherWidth,It=dn!=null?dn:Un;V.style.width=It,V.style.maxWidth=It}if(fr(),!y){let dn=b.innerHeight,It=64,vn=(Te=(Me=r.launcher)==null?void 0:Me.heightOffset)!=null?Te:0,pn=Math.max(200,dn-It),Xe=Math.min(640,pn),it=Math.max(200,Xe-vn);V.style.height=`${it}px`}}finally{if(qn(),Zr(),R&&S){let It=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Ae=(T=r.launcher)==null?void 0:T.mobileBreakpoint)!=null?Ae:640),vn=(Ve=(We=r.launcher)==null?void 0:We.sidebarMode)!=null?Ve:!1,pn=(Mt=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Mt:!0,Xe=nn(r)&&pn&&It,it=vn||pn&&It&&S||Xe;if(it&&!Qt){let Cn=e.getRootNode(),mn=Cn instanceof ShadowRoot?Cn.host:e.closest(".persona-host");mn&&!Gt&&(Gt=Ui(mn,(Xt=(ot=r.launcher)==null?void 0:ot.zIndex)!=null?Xt:hn)),Qt=qi(e.ownerDocument)}else it||(Gt==null||Gt(),Gt=null,Qt==null||Qt(),Qt=null)}}};Q();let oe=(xc=e.ownerDocument.defaultView)!=null?xc:window;if(oe.addEventListener("resize",Q),ft.push(()=>oe.removeEventListener("resize",Q)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{qn()});c.observe(_e),ft.push(()=>c.disconnect())}sr=Ee.scrollTop;let Y=Ee.scrollHeight,Ke=()=>{let c=Ee.scrollTop,m=Ee.scrollHeight,y=m<Y;Y=m;let{action:b,nextLastScrollTop:k}=Ja({following:or.isFollowing(),currentScrollTop:c,lastScrollTop:sr,nearBottom:_s(Ee,hs),userScrollThreshold:oa,isAutoScrolling:Mr||fo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(sr=k,b==="resume"){Kr();return}b==="pause"&&xs()};Ee.addEventListener("scroll",Ke,{passive:!0}),ft.push(()=>Ee.removeEventListener("scroll",Ke));let Ne=c=>{let m=Ka({following:or.isFollowing(),deltaY:c.deltaY,nearBottom:_s(Ee,hs),resumeWhenNearBottom:!0});m==="pause"?xs():m==="resume"&&Kr()};Ee.addEventListener("wheel",Ne,{passive:!0}),ft.push(()=>Ee.removeEventListener("wheel",Ne)),ut.addEventListener("click",()=>{Ee.scrollTop=Ee.scrollHeight,sr=Ee.scrollTop,Kr(),Gr(!0)}),ft.push(()=>ut.remove()),ft.push(()=>{bs()});let rt=()=>{Ue&&(Fn&&(Ue.removeEventListener("click",Fn),Fn=null),U()?(Ue.style.display="",Fn=()=>{Ht(!1,"user")},Ue.addEventListener("click",Fn)):Ue.style.display="none")};rt(),(()=>{let{clearChatButton:c}=$e;c&&c.addEventListener("click",()=>{j.clearMessages(),On.clear(),Kr(),co($e.composerOverlay);try{localStorage.removeItem(gs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==gs)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(),ie==null||ie.update()})})(),Ot&&Ot.addEventListener("submit",Es),Pe==null||Pe.addEventListener("keydown",Ts),Pe==null||Pe.addEventListener("paste",Ms);let Et="persona-attachment-drop-active",Pt=0,Zt=()=>{Pt=0,re.classList.remove(Et)},ht=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&Ct!==null},Tt=c=>{!Ci(c.dataTransfer)||!ht()||(Pt++,Pt===1&&re.classList.add(Et))},rn=c=>{!Ci(c.dataTransfer)||!ht()||(Pt--,Pt<=0&&Zt())},un=c=>{!Ci(c.dataTransfer)||!ht()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},cn=c=>{var y;if(!Ci(c.dataTransfer)||!ht())return;c.preventDefault(),c.stopPropagation(),Zt();let m=Array.from((y=c.dataTransfer.files)!=null?y:[]);m.length!==0&&Ct.handleFiles(m)},$t=!0;re.addEventListener("dragenter",Tt,$t),re.addEventListener("dragleave",rn,$t),e.addEventListener("dragover",un,$t),e.addEventListener("drop",cn,$t);let Mn=e.ownerDocument,Il=c=>{ht()&&c.preventDefault()},Wl=c=>{ht()&&c.preventDefault()};Mn.addEventListener("dragover",Il),Mn.addEventListener("drop",Wl),ft.push(()=>{Ot&&Ot.removeEventListener("submit",Es),Pe==null||Pe.removeEventListener("keydown",Ts),Pe==null||Pe.removeEventListener("paste",Ms)}),ft.push(()=>{re.removeEventListener("dragenter",Tt,$t),re.removeEventListener("dragleave",rn,$t),e.removeEventListener("dragover",un,$t),e.removeEventListener("drop",cn,$t),Mn.removeEventListener("dragover",Il),Mn.removeEventListener("drop",Wl),Zt()}),ft.push(()=>{j.cancel()}),H?ft.push(()=>{H==null||H.destroy()}):A&&ft.push(()=>{A==null||A.remove()});let en={update(c){var tn,br,Rr,xa,va,Ca,Eo,wa,Ls,Tc,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,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,Cd,wd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,jd,Ud,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,vp,Cp;let m=r.toolCall,y=r.messageActions,b=(tn=r.layout)==null?void 0:tn.messages,k=r.colorScheme,B=r.loadingIndicator,F=r.iterationDisplay,z=(br=r.features)==null?void 0:br.showReasoning,W=(Rr=r.features)==null?void 0:Rr.showToolCalls,be=(xa=r.features)==null?void 0:xa.toolCallDisplay,le=(va=r.features)==null?void 0:va.reasoningDisplay;r={...r,...c},tr(),no(e,r),ui(e,r),mi(e,r),Dn(),r.colorScheme!==k&&Jr();let ee=ea.getForInstance(r.plugins);o.length=0,o.push(...ee),S=(Eo=(Ca=r.launcher)==null?void 0:Ca.enabled)!=null?Eo:!0,L=(Ls=(wa=r.launcher)==null?void 0:wa.autoExpand)!=null?Ls:!1,Le=(Mc=(Tc=r.features)==null?void 0:Tc.showReasoning)!=null?Mc:!0,Qe=(Lc=(kc=r.features)==null?void 0:kc.showToolCalls)!=null?Lc:!0,ue=(Ic=(Pc=r.features)==null?void 0:Pc.scrollToBottom)!=null?Ic:{},_r(),Lr();let me=pe;if(pe=(Rc=(Wc=r.features)==null?void 0:Wc.showEventStreamToggle)!=null?Rc:!1,pe&&!me){if(X||(te=new Zs(je),X=new Ys(Se,te),te.open().then(()=>X==null?void 0:X.restore()).catch(()=>{}),j.setSSEEventCallback((Z,vt)=>{var _t;(_t=r.onSSEEvent)==null||_t.call(r,Z,vt),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!gt&&De){let Z=(Bc=(Hc=r.features)==null?void 0:Hc.eventStream)==null?void 0:Bc.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Z!=null&&Z.toggleButton?" "+Z.toggleButton:"");gt=h("button",vt),gt.style.width="28px",gt.style.height="28px",gt.style.color=Sn.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let _t=ge("activity","18px","currentColor",1.5);_t&&gt.appendChild(_t);let lt=$e.clearChatButtonWrapper,St=$e.closeButtonWrapper,on=lt||St;on&&on.parentNode===De?De.insertBefore(gt,on):De.appendChild(gt),gt.addEventListener("click",()=>{He?er():Ar()})}}else!pe&&me&&(er(),gt&&(gt.remove(),gt=null),X==null||X.clear(),te==null||te.destroy(),X=null,te=null);if(((Dc=r.launcher)==null?void 0:Dc.enabled)===!1&&H&&(H.destroy(),H=null),((Nc=r.launcher)==null?void 0:Nc.enabled)===!1&&A&&(A.remove(),A=null),((Fc=r.launcher)==null?void 0:Fc.enabled)!==!1&&!H&&!A){let Z=o.find(vt=>vt.renderLauncher);if(Z!=null&&Z.renderLauncher){let vt=Z.renderLauncher({config:r,defaultRenderer:()=>Ks(r,C).element,onToggle:C});vt&&(A=vt,e.appendChild(A))}A||(H=Ks(r,C),e.appendChild(H.element))}H&&H.update(r),we&&((Oc=r.launcher)==null?void 0:Oc.title)!==void 0&&(we.textContent=r.launcher.title),Be&&(($c=r.launcher)==null?void 0:$c.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Ce=(_c=r.layout)==null?void 0:_c.header;if((Ce==null?void 0:Ce.layout)!==E&&De){let Z=Ce?os(r,Ce,{showClose:U(),onClose:()=>Ht(!1,"user")}):Dr({config:r,showClose:U(),onClose:()=>Ht(!1,"user")});De.replaceWith(Z.header),De=Z.header,q=Z.iconHolder,we=Z.headerTitle,Be=Z.headerSubtitle,Ue=Z.closeButton,E=Ce==null?void 0:Ce.layout}else if(Ce&&(q&&(q.style.display=Ce.showIcon===!1?"none":""),we&&(we.style.display=Ce.showTitle===!1?"none":""),Be&&(Be.style.display=Ce.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=Ce.showCloseButton===!1?"none":""),$e.clearChatButtonWrapper)){let Z=Ce.showClearChat;if(Z!==void 0){$e.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:vt}=$e;vt&&!vt.classList.contains("persona-absolute")&&(Z?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let Ze=((jc=r.layout)==null?void 0:jc.showHeader)!==!1;De&&(De.style.display=Ze?"":"none");let Ge=((Uc=r.layout)==null?void 0:Uc.showFooter)!==!1;_e&&(_e.style.display=Ge?"":"none"),qn(),Lr(),S!==P?S?Ht(L,"auto"):(R=!0,Zr()):L!==N&&Ht(L,"auto"),N=L,P=S,Q(),rt();let Me=JSON.stringify(c.toolCall)!==JSON.stringify(m),Te=JSON.stringify(r.messageActions)!==JSON.stringify(y),qe=JSON.stringify((qc=r.layout)==null?void 0:qc.messages)!==JSON.stringify(b),T=((zc=r.loadingIndicator)==null?void 0:zc.render)!==(B==null?void 0:B.render)||((Vc=r.loadingIndicator)==null?void 0:Vc.renderIdle)!==(B==null?void 0:B.renderIdle)||((Jc=r.loadingIndicator)==null?void 0:Jc.showBubble)!==(B==null?void 0:B.showBubble),Ae=r.iterationDisplay!==F,We=((Gc=(Kc=r.features)==null?void 0:Kc.showReasoning)!=null?Gc:!0)!==(z!=null?z:!0)||((Xc=(Qc=r.features)==null?void 0:Qc.showToolCalls)!=null?Xc:!0)!==(W!=null?W:!0)||JSON.stringify((Yc=r.features)==null?void 0:Yc.toolCallDisplay)!==JSON.stringify(be)||JSON.stringify((Zc=r.features)==null?void 0:Zc.reasoningDisplay)!==JSON.stringify(le);(Me||Te||qe||T||Ae||We)&&j&&(fs++,yo(xe,j.getMessages(),Ie));let ye=(ed=r.launcher)!=null?ed:{},Mt=(td=ye.headerIconHidden)!=null?td:!1,ot=(rd=(nd=r.layout)==null?void 0:nd.header)==null?void 0:rd.showIcon,Xt=Mt||ot===!1,dn=ye.headerIconName,It=(od=ye.headerIconSize)!=null?od:"48px";if(q){let Z=re.querySelector(".persona-border-b-persona-divider"),vt=Z==null?void 0:Z.querySelector(".persona-flex-col");if(Xt)q.style.display="none",Z&&vt&&!Z.contains(vt)&&Z.insertBefore(vt,Z.firstChild);else{if(q.style.display="",q.style.height=It,q.style.width=It,Z&&vt&&(Z.contains(q)?q.nextSibling!==vt&&(q.remove(),Z.insertBefore(q,vt)):Z.insertBefore(q,vt)),dn){let lt=parseFloat(It)||24,St=ge(dn,lt*.6,"#ffffff",2);St?q.replaceChildren(St):q.textContent=(sd=ye.agentIconText)!=null?sd:"\u{1F4AC}"}else if(ye.iconUrl){let lt=q.querySelector("img");if(lt)lt.src=ye.iconUrl,lt.style.height=It,lt.style.width=It;else{let St=document.createElement("img");St.src=ye.iconUrl,St.alt="",St.className="persona-rounded-xl persona-object-cover",St.style.height=It,St.style.width=It,q.replaceChildren(St)}}else{let lt=q.querySelector("svg"),St=q.querySelector("img");(lt||St)&&q.replaceChildren(),q.textContent=(ad=ye.agentIconText)!=null?ad:"\u{1F4AC}"}let _t=q.querySelector("img");_t&&(_t.style.height=It,_t.style.width=It)}}let vn=(ld=(id=r.layout)==null?void 0:id.header)==null?void 0:ld.showTitle,pn=(dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.showSubtitle;if(we&&(we.style.display=vn===!1?"none":""),Be&&(Be.style.display=pn===!1?"none":""),Ue){((ud=(pd=r.layout)==null?void 0:pd.header)==null?void 0:ud.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let vt=(md=ye.closeButtonSize)!=null?md:"32px",_t=(gd=ye.closeButtonPlacement)!=null?gd:"inline";Ue.style.height=vt,Ue.style.width=vt;let{closeButtonWrapper:lt}=$e,St=_t==="top-right",on=lt==null?void 0:lt.classList.contains("persona-absolute");if(lt&&St!==on)if(lt.remove(),St)lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",re.style.position="relative",re.appendChild(lt);else{let pt=(hd=(fd=ye.clearChat)==null?void 0:fd.placement)!=null?hd:"inline",sn=(bd=(yd=ye.clearChat)==null?void 0:yd.enabled)!=null?bd:!0;lt.className=sn&&pt==="inline"?"":"persona-ml-auto";let In=re.querySelector(".persona-border-b-persona-divider");In&&In.appendChild(lt)}if(Ue.style.color=ye.closeButtonColor||Sn.actionIconColor,ye.closeButtonBackgroundColor?(Ue.style.backgroundColor=ye.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let pt=ye.closeButtonBorderWidth||"0px",sn=ye.closeButtonBorderColor||"transparent";Ue.style.border=`${pt} solid ${sn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");ye.closeButtonBorderRadius?(Ue.style.borderRadius=ye.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(Ue.style.paddingLeft=ye.closeButtonPaddingX,Ue.style.paddingRight=ye.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),ye.closeButtonPaddingY?(Ue.style.paddingTop=ye.closeButtonPaddingY,Ue.style.paddingBottom=ye.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let gn=(xd=ye.closeButtonIconName)!=null?xd:"x",cr=(vd=ye.closeButtonIconText)!=null?vd:"\xD7";Ue.innerHTML="";let An=ge(gn,"28px","currentColor",1);An?Ue.appendChild(An):Ue.textContent=cr;let Yt=(Cd=ye.closeButtonTooltipText)!=null?Cd:"Close chat",jn=(wd=ye.closeButtonShowTooltip)!=null?wd:!0;if(Ue.setAttribute("aria-label",Yt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),jn&&Yt)){let pt=null,sn=()=>{if(pt||!Ue)return;let To=Ue.ownerDocument,Ps=To.body;if(!Ps)return;pt=xr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Is=xr(To,"div");Is.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Is);let Mo=Ue.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(ro),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ps.appendChild(pt)},In=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",In),Ue.addEventListener("focus",sn),Ue.addEventListener("blur",In),lt._cleanupTooltip=()=>{In(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",In)),Ue&&(Ue.removeEventListener("focus",sn),Ue.removeEventListener("blur",In))}}}let{clearChatButton:Xe,clearChatButtonWrapper:it}=$e;if(Xe){let Z=(Ad=ye.clearChat)!=null?Ad:{},vt=(Sd=Z.enabled)!=null?Sd:!0,_t=(Td=(Ed=r.layout)==null?void 0:Ed.header)==null?void 0:Td.showClearChat,lt=_t!==void 0?_t:vt,St=(Md=Z.placement)!=null?Md:"inline";if(it){it.style.display=lt?"":"none";let{closeButtonWrapper:on}=$e;!_()&&on&&!on.classList.contains("persona-absolute")&&(lt?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let gn=St==="top-right",cr=it.classList.contains("persona-absolute");if(!_()&&gn!==cr&&lt){if(it.remove(),gn)it.className="persona-absolute persona-top-4 persona-z-50",it.style.right="48px",re.style.position="relative",re.appendChild(it);else{it.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",it.style.right="";let Yt=re.querySelector(".persona-border-b-persona-divider"),jn=$e.closeButtonWrapper;Yt&&jn&&jn.parentElement===Yt?Yt.insertBefore(it,jn):Yt&&Yt.appendChild(it)}let An=$e.closeButtonWrapper;An&&!An.classList.contains("persona-absolute")&&(gn?An.classList.add("persona-ml-auto"):An.classList.remove("persona-ml-auto"))}}if(lt){if(!_()){let pt=(kd=Z.size)!=null?kd:"32px";Xe.style.height=pt,Xe.style.width=pt}let on=(Ld=Z.iconName)!=null?Ld:"refresh-cw",gn=(Pd=Z.iconColor)!=null?Pd:"";Xe.style.color=gn||Sn.actionIconColor,Xe.innerHTML="";let cr=_()?"14px":"20px",An=ge(on,cr,"currentColor",2);if(An&&Xe.appendChild(An),Z.backgroundColor?(Xe.style.backgroundColor=Z.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let pt=Z.borderWidth||"0px",sn=Z.borderColor||"transparent";Xe.style.border=`${pt} solid ${sn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");Z.borderRadius?(Xe.style.borderRadius=Z.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),Z.paddingX?(Xe.style.paddingLeft=Z.paddingX,Xe.style.paddingRight=Z.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),Z.paddingY?(Xe.style.paddingTop=Z.paddingY,Xe.style.paddingBottom=Z.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let Yt=(Id=Z.tooltipText)!=null?Id:"Clear chat",jn=(Wd=Z.showTooltip)!=null?Wd:!0;if(Xe.setAttribute("aria-label",Yt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),jn&&Yt)){let pt=null,sn=()=>{if(pt||!Xe)return;let To=Xe.ownerDocument,Ps=To.body;if(!Ps)return;pt=xr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Is=xr(To,"div");Is.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Is);let Mo=Xe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(ro),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ps.appendChild(pt)},In=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",sn),it.addEventListener("mouseleave",In),Xe.addEventListener("focus",sn),Xe.addEventListener("blur",In),it._cleanupTooltip=()=>{In(),it&&(it.removeEventListener("mouseenter",sn),it.removeEventListener("mouseleave",In)),Xe&&(Xe.removeEventListener("focus",sn),Xe.removeEventListener("blur",In))}}}}let Cn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ta],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Oo.message,Oo.messageAndClick];M=na({parsers:Cn,handlers:mn,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Ku(r,M,se),j.updateConfig(r),yo(xe,j.getMessages(),Ie),nr.render(r.suggestionChips,j,Pe,void 0,r.suggestionChipsConfig),As(),qo(j.isStreaming());let Co=((Rd=r.voiceRecognition)==null?void 0:Rd.enabled)===!0,wo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ao=((Bd=(Hd=r.voiceRecognition)==null?void 0:Hd.provider)==null?void 0:Bd.type)==="runtype";if(Co&&(wo||Ao))if(!I||!he){let Z=ha(r.voiceRecognition,r.sendButton);Z&&(I=Z.micButton,he=Z.micButtonWrapper,wt.insertBefore(he,an),I.addEventListener("click",vo),I.disabled=j.isStreaming())}else{let Z=(Dd=r.voiceRecognition)!=null?Dd:{},vt=(Nd=r.sendButton)!=null?Nd:{},_t=(Fd=Z.iconName)!=null?Fd:"mic",lt=(Od=vt.size)!=null?Od:"40px",St=($d=Z.iconSize)!=null?$d:lt,on=parseFloat(St)||24;I.style.width=St,I.style.height=St,I.style.minWidth=St,I.style.minHeight=St;let gn=(jd=(_d=Z.iconColor)!=null?_d:vt.textColor)!=null?jd:"currentColor";I.innerHTML="";let cr=ge(_t,on,gn,2);cr?I.appendChild(cr):I.textContent="\u{1F3A4}";let An=(Ud=Z.backgroundColor)!=null?Ud:vt.backgroundColor;An?I.style.backgroundColor=An:I.style.backgroundColor="",gn?I.style.color=gn:I.style.color="var(--persona-text, #111827)",Z.borderWidth?(I.style.borderWidth=Z.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),Z.borderColor?I.style.borderColor=Z.borderColor:I.style.borderColor="",Z.paddingX?(I.style.paddingLeft=Z.paddingX,I.style.paddingRight=Z.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),Z.paddingY?(I.style.paddingTop=Z.paddingY,I.style.paddingBottom=Z.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),jn=(qd=Z.tooltipText)!=null?qd:"Start voice recognition";if(((zd=Z.showTooltip)!=null?zd:!1)&&jn)if(Yt)Yt.textContent=jn,Yt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=jn,he==null||he.insertBefore(sn,I)}else Yt&&(Yt.style.display="none");he.style.display="",I.disabled=j.isStreaming()}else I&&he&&(he.style.display="none",((Jd=(Vd=r.voiceRecognition)==null?void 0:Vd.provider)==null?void 0:Jd.type)==="runtype"?j.isVoiceActive()&&j.toggleVoice():$n&&ir());if(((Kd=r.attachments)==null?void 0:Kd.enabled)===!0)if(!dt||!fe){let Z=(Gd=r.attachments)!=null?Gd:{},_t=(Xd=((Qd=r.sendButton)!=null?Qd:{}).size)!=null?Xd:"40px";Wt||(Wt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Wt.style.display="none",Ot.insertBefore(Wt,Pe)),ze||(ze=document.createElement("input"),ze.type="file",ze.accept=((Yd=Z.allowedTypes)!=null?Yd:Br).join(","),ze.multiple=((Zd=Z.maxFiles)!=null?Zd:4)>1,ze.style.display="none",ze.setAttribute("aria-label","Attach files"),Ot.insertBefore(ze,Pe)),dt=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",(ep=Z.buttonTooltipText)!=null?ep:"Attach file");let lt=(tp=Z.buttonIconName)!=null?tp:"paperclip",St=_t,on=parseFloat(St)||40,gn=Math.round(on*.6);fe.style.width=St,fe.style.height=St,fe.style.minWidth=St,fe.style.minHeight=St,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 cr=ge(lt,gn,"currentColor",1.5);cr?fe.appendChild(cr):fe.textContent="\u{1F4CE}",fe.addEventListener("click",jn=>{jn.preventDefault(),ze==null||ze.click()}),dt.appendChild(fe);let An=(np=Z.buttonTooltipText)!=null?np:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=An,dt.appendChild(Yt),tt.append(dt),!Ct&&ze&&Wt&&(Ct=Bo.fromConfig(Z),Ct.setPreviewsContainer(Wt),ze.addEventListener("change",async()=>{Ct&&(ze!=null&&ze.files)&&(await Ct.handleFileSelect(ze.files),ze.value="")})),re.querySelector(".persona-attachment-drop-overlay")||re.appendChild(Gu(Z.dropOverlay))}else{dt.style.display="";let Z=(rp=r.attachments)!=null?rp:{};ze&&(ze.accept=((op=Z.allowedTypes)!=null?op:Br).join(","),ze.multiple=((sp=Z.maxFiles)!=null?sp:4)>1),Ct&&Ct.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}else dt&&(dt.style.display="none"),Ct&&Ct.clearAttachments(),(ap=re.querySelector(".persona-attachment-drop-overlay"))==null||ap.remove();let zt=(ip=r.sendButton)!=null?ip:{},So=(lp=zt.useIcon)!=null?lp:!1,to=(cp=zt.iconText)!=null?cp:"\u2191",yt=zt.iconName,kn=(dp=zt.tooltipText)!=null?dp:"Send message",Wr=(pp=zt.showTooltip)!=null?pp:!1,wn=(up=zt.size)!=null?up:"40px",Ln=zt.backgroundColor,Dt=zt.textColor;if(So){if(ne.style.width=wn,ne.style.height=wn,ne.style.minWidth=wn,ne.style.minHeight=wn,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.innerHTML="",Dt?ne.style.color=Dt:ne.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Z=parseFloat(wn)||24,vt=(Dt==null?void 0:Dt.trim())||"currentColor",_t=ge(yt,Z,vt,2);_t?ne.appendChild(_t):ne.textContent=to}else ne.textContent=to;ne.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ln?(ne.style.backgroundColor=Ln,ne.classList.remove("persona-bg-persona-primary")):(ne.style.backgroundColor="",ne.classList.add("persona-bg-persona-primary"))}else ne.textContent=(gp=(mp=r.copy)==null?void 0:mp.sendButtonLabel)!=null?gp:"Send",ne.style.width="",ne.style.height="",ne.style.minWidth="",ne.style.minHeight="",ne.style.fontSize="",ne.style.lineHeight="",ne.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?(ne.style.backgroundColor=Ln,ne.classList.remove("persona-bg-persona-accent")):ne.classList.add("persona-bg-persona-accent"),Dt?ne.style.color=Dt:ne.classList.add("persona-text-white");zt.borderWidth?(ne.style.borderWidth=zt.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),zt.borderColor?ne.style.borderColor=zt.borderColor:ne.style.borderColor="",zt.paddingX?(ne.style.paddingLeft=zt.paddingX,ne.style.paddingRight=zt.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),zt.paddingY?(ne.style.paddingTop=zt.paddingY,ne.style.paddingBottom=zt.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Ut=an==null?void 0:an.querySelector(".persona-send-button-tooltip");if(Wr&&kn)if(Ut)Ut.textContent=kn,Ut.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=kn,an==null||an.insertBefore(Z,ne)}else Ut&&(Ut.style.display="none");let Nt=(xp=(fp=r.layout)==null?void 0:fp.contentMaxWidth)!=null?xp:_()?(bp=(yp=(hp=r.launcher)==null?void 0:hp.composerBar)==null?void 0:yp.contentMaxWidth)!=null?bp:"720px":void 0;Nt?(xe.style.maxWidth=Nt,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",Ot&&(Ot.style.maxWidth=Nt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Bt&&(Bt.style.maxWidth=Nt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto")):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""));let Vt=(vp=r.statusIndicator)!=null?vp:{},Pn=(Cp=Vt.visible)!=null?Cp:!0;if(Jt.style.display=Pn?"":"none",j){let Z=j.getStatus();Oe(Jt,(_t=>{var lt,St,on,gn;return _t==="idle"?(lt=Vt.idleText)!=null?lt:fn.idle:_t==="connecting"?(St=Vt.connectingText)!=null?St:fn.connecting:_t==="connected"?(on=Vt.connectedText)!=null?on:fn.connected:_t==="error"?(gn=Vt.errorText)!=null?gn:fn.error:fn[_t]})(Z),Vt,Z)}Jt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let _n=Vt.align==="left"?"persona-text-left":Vt.align==="center"?"persona-text-center":"persona-text-right";Jt.classList.add(_n)},open(){U()&&Ht(!0,"api")},close(){U()&&Ht(!1,"api")},toggle(){U()&&Ht(!R,"api")},clearChat(){yn=!1,j.clearMessages(),On.clear(),Kr();try{localStorage.removeItem(gs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==gs)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(),ie==null||ie.update()},setMessage(c){return!Pe||j.isStreaming()?!1:(!R&&U()&&Ht(!0,"system"),Pe.value=c,Pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(j.isStreaming())return!1;let m=(c==null?void 0:c.trim())||Pe.value.trim();return m?(!R&&U()&&Ht(!0,"system"),Pe.value="",Pe.style.height="auto",j.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return j.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(j.isVoiceActive()||(!R&&U()&&Ht(!0,"system"),mt.manuallyDeactivated=!1,Tn(),j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),Gn("user"),j.isVoiceActive()&&eo()})),!0):$n?!0:ks()?(!R&&U()&&Ht(!0,"system"),mt.manuallyDeactivated=!1,Tn(),bo("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.isVoiceActive()?(j.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Tn(),Gn("user"),lr()}),!0):!1:$n?(mt.manuallyDeactivated=!0,Tn(),ir("user"),!0):!1},injectMessage(c){return!R&&U()&&Ht(!0,"system"),j.injectMessage(c)},injectAssistantMessage(c){!R&&U()&&Ht(!0,"system");let m=j.injectAssistantMessage(c);return $&&($=!1,J&&(clearTimeout(J),J=null),setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)),m},injectUserMessage(c){return!R&&U()&&Ht(!0,"system"),j.injectUserMessage(c)},injectSystemMessage(c){return!R&&U()&&Ht(!0,"system"),j.injectSystemMessage(c)},injectMessageBatch(c){return!R&&U()&&Ht(!0,"system"),j.injectMessageBatch(c)},injectComponentDirective(c){return!R&&U()&&Ht(!0,"system"),j.injectComponentDirective(c)},injectTestMessage(c){!R&&U()&&Ht(!0,"system"),j.injectTestEvent(c)},async connectStream(c,m){return j.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(){!pe||!X||Ar()},hideEventStream(){He&&er()},isEventStreamVisible(){return He},showArtifacts(){Zn(r)&&(yn=!1,Dn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){Zn(r)&&(yn=!0,Dn())},upsertArtifact(c){return Zn(r)?(yn=!1,j.upsertArtifact(c)):null},selectArtifact(c){Zn(r)&&j.selectArtifact(c)},clearArtifacts(){Zn(r)&&j.clearArtifacts()},getArtifacts(){var c;return(c=j==null?void 0:j.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=j==null?void 0:j.getSelectedArtifactId())!=null?c:null},focusInput(){return S&&!R&&!_()||!Pe?!1:(Pe.focus(),!0)},async resolveApproval(c,m){let b=j.getMessages().find(k=>{var B;return k.variant==="approval"&&((B=k.approval)==null?void 0:B.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);return j.resolveApproval(b.approval,m)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return U()&&R},isVoiceActive(){return mt.active},getState(){return{open:U()&&R,launcherEnabled:S,voiceActive:mt.active,streaming:j.isStreaming()}},showCSATFeedback(c){!R&&U()&&Ht(!0,"system");let m=xe.querySelector(".persona-feedback-container");m&&m.remove();let y=xi({onSubmit:async(b,k)=>{var B;j.isClientTokenMode()&&await j.submitCSATFeedback(b,k),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});xe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&U()&&Ht(!0,"system");let m=xe.querySelector(".persona-feedback-container");m&&m.remove();let y=vi({onSubmit:async(b,k)=>{var B;j.isClientTokenMode()&&await j.submitNPSFeedback(b,k),(B=c==null?void 0:c.onSubmit)==null||B.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 j.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return j.submitNPSFeedback(c,m)},destroy(){yr!=null&&(clearInterval(yr),yr=null),ft.forEach(c=>c()),G.remove(),ve==null||ve.remove(),H==null||H.destroy(),A==null||A.remove(),Fn&&Ue.removeEventListener("click",Fn)}};if((((vc=t==null?void 0:t.debugTools)!=null?vc:!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,ft.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=z=>{let W=z.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",m),ft.push(()=>{window.removeEventListener("persona:focusInput",m)}),pe){let z=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&en.showEventStream()},W=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",W),ft.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",W)})}let y=z=>{let W=z.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.showArtifacts()},b=z=>{let W=z.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.hideArtifacts()},k=z=>{let W=z.detail;W!=null&&W.instanceId&&W.instanceId!==c||W!=null&&W.artifact&&en.upsertArtifact(W.artifact)},B=z=>{let W=z.detail;W!=null&&W.instanceId&&W.instanceId!==c||typeof(W==null?void 0:W.id)=="string"&&en.selectArtifact(W.id)},F=z=>{let W=z.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",B),window.addEventListener("persona:clearArtifacts",F),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",F)})}let Qn=Of(r.persistState);if(Qn&&U()){let c=$f(Qn.storage),m=`${Qn.keyPrefix}widget-open`,y=`${Qn.keyPrefix}widget-voice`,b=`${Qn.keyPrefix}widget-voice-mode`;if(c){let k=((Cc=Qn.persist)==null?void 0:Cc.openState)&&c.getItem(m)==="true",B=((wc=Qn.persist)==null?void 0:wc.voiceState)&&c.getItem(y)==="true",F=((Ac=Qn.persist)==null?void 0:Ac.voiceState)&&c.getItem(b)==="true";if(k&&setTimeout(()=>{en.open(),setTimeout(()=>{var z;if(B||F)en.startVoiceRecognition();else if((z=Qn.persist)!=null&&z.focusInput){let W=e.querySelector("textarea");W&&W.focus()}},100)},0),(Sc=Qn.persist)!=null&&Sc.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Ec=Qn.persist)!=null&&Ec.voiceState&&(s.on("voice:state",z=>{c.setItem(y,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(b,z.viaVoice?"true":"false")})),Qn.clearOnChatClear){let z=()=>{c.removeItem(m),c.removeItem(y),c.removeItem(b)},W=()=>z();window.addEventListener("persona:clear-chat",W),ft.push(()=>{window.removeEventListener("persona:clear-chat",W)})}}}return u&&U()&&setTimeout(()=>{en.open()},0),Pr(),en};var _f=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,n*parseFloat(o[1])/100):420},Qu=(e,n)=>{var r,o;let t=(o=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?o:!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"},yl=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=""},Xu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",yl(e)},gl=e=>{e.style.transition=""},fl=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=""},hl=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=""},jf=(e,n,t,r,o)=>{o?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Uf=(e,n,t,r,o,s)=>{let a=s?n:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Yu=(e,n,t,r,o,s,a)=>{var w,x,M,S,L,D;let i=Xn(s),d=i.reveal==="push";jf(e,n,t,r,d),Uf(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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?x:!0,p=(S=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?S:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fl(n),gl(r),Xu(r),hl(t),Ai(o,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((D=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?D:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Xu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",fl(n),gl(r),hl(t),Ai(o,r);let N=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",E=a?"translateX(0)":P;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=N,r.style.transform=E,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",gl(r),yl(r),Ai(o,r);let N=_f(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),E=i.animate?"transform 180ms ease":"none",O=i.side==="right"?a?`translateX(-${N}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${N}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=`${P+N}px`,n.style.transition=E,n.style.transform=O,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${P}px`,t.style.maxWidth=`${P}px`,t.style.minWidth=`${P}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="",fl(n),yl(r),hl(t),Ai(o,r);let N=i.reveal==="emerge";N?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",E=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",O=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",r.style.position="relative",r.style.overflow=N||O?"hidden":"visible",r.style.transition=E,N&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},qf=(e,n)=>{let t=e.ownerDocument.createElement("div");return Qu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Qu(t,r)},destroy(){t.remove()}}},zf=(e,n)=>{var L,D,N,P;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(D=(L=n==null?void 0:n.launcher)==null?void 0:L.enabled)==null||D?(P=(N=n==null?void 0:n.launcher)==null?void 0:N.autoExpand)!=null?P:!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(()=>{Yu(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{Yu(a,i,d,l,u,n,p),w()},M=a.ownerDocument.defaultView,S=()=>{x()};return M==null||M.addEventListener("resize",S),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(E){let O=E.launcherEnabled?E.open:!0;p!==O&&(p=O,x())},updateConfig(E){var O,_;n=E,((_=(O=n==null?void 0:n.launcher)==null?void 0:O.enabled)!=null?_:!0)===!1&&(p=!0),x()},destroy(){M==null||M.removeEventListener("resize",S),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},ra=(e,n)=>nn(n)?zf(e,n):qf(e,n);var bl={},Vf=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},Jf=()=>{try{if(typeof bl!="undefined"&&bl.url)return new URL("../widget.css",bl.url).href}catch{}return null},Zu=(e,n)=>{let t=Jf(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=n.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),n.head.appendChild(s)}},xl=e=>{var M;let n=Vf(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,o=e.config,s=ra(n,o),a,i=[],d=(S,L)=>{var E,O;let N=!((O=(E=L==null?void 0:L.launcher)==null?void 0:E.enabled)!=null?O:!0)||nn(L),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),N&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),t){let _=S.attachShadow({mode:"open"});_.appendChild(P),Zu(_,r)}else S.appendChild(P),Zu(S,r);return n.id&&P.setAttribute("data-persona-instance",n.id),P},l=()=>{s.syncWidgetState(a.getState())},u=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let S=d(s.host,o);a=wi(S,o,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};p(),(M=e.onReady)==null||M.call(e);let g=S=>{f(),s.destroy(),s=ra(n,S),o=S,p()},w={update(S){var O,_,U,R,$,J;let L={...o,...S,launcher:{...(O=o==null?void 0:o.launcher)!=null?O:{},...(_=S==null?void 0:S.launcher)!=null?_:{},dock:{...(R=(U=o==null?void 0:o.launcher)==null?void 0:U.dock)!=null?R:{},...(J=($=S==null?void 0:S.launcher)==null?void 0:$.dock)!=null?J:{}}}},D=nn(o),N=nn(L),P=so(o),E=so(L);if(D!==N||P!==E){g(L);return}o=L,s.updateConfig(o),a.update(S),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(w,{get(S,L,D){if(L==="host")return s.host;if(L in S)return Reflect.get(S,L,D);let N=a[L];return typeof N=="function"?N.bind(a):N}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var om=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Kf=new Set(["button","a","input","select","textarea","details","summary"]),Gf=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),vl=/\b(product|card|item|listing|result)\b/i,wl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Qf=3e3,Xf=100;function sm(e){let n=typeof e.className=="string"?e.className:"";if(vl.test(n)||e.id&&vl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&vl.test(r.value))return!0}return!1}function am(e){var n;return wl.test(((n=e.textContent)!=null?n:"").trim())}function im(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let o=(t=n[r].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yf(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function em(e){let n=e.match(wl);return n?n[0]:null}function tm(e){var r,o,s;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&&((o=n.textContent)!=null&&o.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(s=t==null?void 0:t.textContent)!=null&&s.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Zf(e){let n=[],t=r=>{let o=r.trim();o&&!n.includes(o)&&n.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;t((o=r.value)!=null?o:"")}),n.slice(0,6)}var eh="commerce-card",th="result-card";function nm(e){return!sm(e)||!am(e)||!im(e)&&!Yf(e)?0:5200}function rm(e){var r;return!sm(e)||am(e)||!im(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 Al=[{id:eh,scoreElement(e){return nm(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||wl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(nm(e)===0)return null;let{title:t,href:r}=tm(e),o=(u=(l=em(((d=e.textContent)!=null?d:"").trim()))!=null?l:em(n.text))!=null?u:"",s=Zf(e);return[r&&t?`[${t}](${r})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||n.text.trim().slice(0,120),`selector: ${n.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
100
+ `}if(!b&&!c){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Vt=m?"":"padding-top: 1.25em !important;",Pn=m?"":`z-index: ${(Ut=(Dt=r.launcher)==null?void 0:Dt.zIndex)!=null?Ut:hn} !important;`;G.style.cssText+=Nt+Vt+Pn}T()};tr(),no(e,r),ui(e,r),mi(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",qr)});let Gt=null,Qt=null;ft.push(()=>{Gt==null||Gt(),Gt=null,Qt==null||Qt(),Qt=null}),Wn&&ft.push(()=>{Wn==null||Wn.disconnect(),Wn=null}),ft.push(()=>{bn==null||bn(),bn=null,Tr(),Rt&&(Rt.remove(),Rt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),ge&&ft.push(()=>{de!==null&&(cancelAnimationFrame(de),de=null),ie==null||ie.destroy(),ie=null,X==null||X.destroy(),X=null,te=null});let Nn=null,Jr=()=>{Nn&&(Nn(),Nn=null),r.colorScheme==="auto"&&(Nn=qa(()=>{no(e,r)}))};Jr(),ft.push(()=>{Nn&&(Nn(),Nn=null)});let Kn=(gc=r.features)==null?void 0:gc.streamAnimation;if(Kn!=null&&Kn.type&&Kn.type!=="none"){let c=qs(Kn.type,Kn.plugins);c&&(ji(c,e),ft.push(()=>lu(e)))}let nr=Iu(Bt),Fn=null,j,ce=!1,On=Zp(),rr=new Map,hr=new Map,fs=0,or=Va(),sr=0,ar=null,Mr=!1,fo=!1,oa=4,hs=24,sa=80,jo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ys=(hc=(fc=r.voiceRecognition)==null?void 0:fc.autoResume)!=null?hc:!1,Gn=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Tn=()=>{g(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var b,M;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=ml(d.voiceState),m=!!c.active,y=Number((M=c.timestamp)!=null?M:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-y<Df&&setTimeout(()=>{var B,F;mt.active||(mt.manuallyDeactivated=!1,((F=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:F.type)==="runtype"?j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),Gn("restore"),j.isVoiceActive()&&eo()}):bo("restore"))},1e3)},ia=()=>j?Ju(j.getMessages()).filter(c=>!c.__skipPersist):[];function Uo(c){if(!(i!=null&&i.save))return;let y={messages:c?Ju(c):j?ia():[],metadata:d,artifacts:Rn.artifacts,selectedArtifactId:Rn.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let kr=null,la=()=>G.querySelector("#persona-scroll-container")||Ee,ho=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),Mr=!1},bs=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null),fo=!1,ho()},Lr=()=>{if(!kt()||He){ut.parentNode&&ut.remove(),ut.style.display="none";return}ut.parentNode!==re&&re.appendChild(ut),qn();let c=$s(Ee)>0;ut.style.display=or.isFollowing()||!c?"none":""},xs=()=>{or.pause()&&(bs(),Lr())},Kr=()=>{or.resume(),Lr()},Gr=(c=!1)=>{or.isFollowing()&&(!c&&!ce||(ar!==null&&(cancelAnimationFrame(ar),ar=null),fo=!0,ar=requestAnimationFrame(()=>{ar=null,fo=!1,or.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,m=500)=>{let y=c.scrollTop,b=$s(c),M=b-y;if(Math.abs(M)<1){sr=c.scrollTop;return}if(Math.abs(M)>=sa){ho(),Mr=!0,c.scrollTop=b,sr=c.scrollTop,Mr=!1;return}ho();let B=performance.now();Mr=!0;let F=W=>1-Math.pow(1-W,3),z=W=>{if(!or.isFollowing()){ho();return}let be=$s(c);be!==b&&(b=be,M=b-y);let le=W-B,ee=Math.min(le/m,1),ue=F(ee),Ce=y+M*ue;c.scrollTop=Ce,sr=c.scrollTop,ee<1?kr=requestAnimationFrame(z):(c.scrollTop=b,sr=c.scrollTop,kr=null,Mr=!1)};kr=requestAnimationFrame(z)},da=c=>{let m=new Map;c.forEach(y=>{let b=jo.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&s.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&s.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&s.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):s.emit("approval:requested",{approval:y.approval,message:y}))}),jo.clear(),m.forEach((y,b)=>{jo.set(b,y)})},yo=(c,m,y)=>{var Ge,st,at,Me,Te,Ue;let b=document.createElement("div"),B=(()=>{var Ae;let T=o.find(We=>We.renderLoadingIndicator);if(T!=null&&T.renderLoadingIndicator)return T.renderLoadingIndicator;if((Ae=r.loadingIndicator)!=null&&Ae.render)return r.loadingIndicator.render})(),F=(T,Ae)=>Ae==null?!1:typeof Ae=="string"?(T.textContent=Ae,!0):(T.appendChild(Ae),!0),z=new Set,W=new Set,be=o.some(T=>T.renderAskUserQuestion),le=[],ee=[],ue=r.enableComponentStreaming!==!1;if(m.forEach(T=>{var vn,pn,Xe,it,Cn,mn,Co,wo,Ao,Go,Qo,zt,So,to;z.add(T.id);let Ae=be&&Nr(T),We=!Ae&&T.role==="assistant"&&!T.variant&&ue&&yi(T);if(!We&&hr.has(T.id)){let yt=c.querySelector(`#wrapper-${T.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),hr.delete(T.id)}let Ve=Nr(T)?`:${(vn=T.agentMetadata)!=null&&vn.askUserQuestionAnswered?"a":"u"}:${(pn=T.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(T.agentMetadata.askUserQuestionAnswers).length:0}`:"",ye=Yp(T,fs)+Ve,Mt=Ae||We?null:eu(On,T.id,ye);if(Mt){b.appendChild(Mt.cloneNode(!0)),Nr(T)&&((Xe=T.toolCall)!=null&&Xe.id)&&((it=T.agentMetadata)==null?void 0:it.awaitingLocalTool)===!0&&!((Cn=T.agentMetadata)!=null&&Cn.askUserQuestionAnswered)&&(W.add(T.toolCall.id),ps(T,r,$e.composerOverlay));return}let ot=null,Xt=o.find(yt=>!!(T.variant==="reasoning"&&yt.renderReasoning||T.variant==="tool"&&yt.renderToolCall||T.variant==="approval"&&yt.renderApproval||!T.variant&&yt.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if(Nr(T)&&((Co=T.agentMetadata)==null?void 0:Co.askUserQuestionAnswered)===!0){rr.delete(T.id);let yt=c.querySelector(`#wrapper-${T.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if(Nr(T)&&((Ao=(wo=r.features)==null?void 0:wo.askUserQuestion)==null?void 0:Ao.enabled)!==!1){let yt=o.find(kn=>typeof kn.renderAskUserQuestion=="function");if(yt&&Lt.current){let kn=rr.get(T.id),Wr=kn!==ye,wn=null;if(Wr){let{payload:Ut,complete:Nt}=Fr(T),Vt=T.id,Pn=()=>{var _n;return(_n=Lt.current)==null?void 0:_n.getMessages().find(tn=>tn.id===Vt)};wn=yt.renderAskUserQuestion({message:T,payload:Ut,complete:Nt,resolve:_n=>{var br;let tn=Pn();tn&&((br=Lt.current)==null||br.resolveAskUserQuestion(tn,_n))},dismiss:()=>{var tn,br,Rr;let _n=Pn();(tn=_n==null?void 0:_n.agentMetadata)!=null&&tn.awaitingLocalTool&&((br=Lt.current)==null||br.markAskUserQuestionResolved(_n),(Rr=Lt.current)==null||Rr.resolveAskUserQuestion(_n,"(dismissed)"))},config:r})}let Ln=kn!=null;if(Wr&&wn===null&&!Ln){((Go=T.agentMetadata)==null?void 0:Go.awaitingLocalTool)===!0&&!((Qo=T.agentMetadata)!=null&&Qo.askUserQuestionAnswered)&&(W.add(T.toolCall.id),ps(T,r,$e.composerOverlay));return}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${T.id}`,Dt.setAttribute("data-wrapper-id",T.id),Dt.setAttribute("data-ask-plugin-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),b.appendChild(Dt),le.push({messageId:T.id,fingerprint:ye,bubble:wn});return}else{((zt=T.agentMetadata)==null?void 0:zt.awaitingLocalTool)===!0&&!((So=T.agentMetadata)!=null&&So.askUserQuestionAnswered)&&(W.add(T.toolCall.id),ps(T,r,$e.composerOverlay));return}}else if(Xt)if(T.variant==="reasoning"&&T.reasoning&&Xt.renderReasoning){if(!ke)return;ot=Xt.renderReasoning({message:T,defaultRenderer:()=>Yi(T,r),config:r})}else if(T.variant==="tool"&&T.toolCall&&Xt.renderToolCall){if(!Qe)return;ot=Xt.renderToolCall({message:T,defaultRenderer:()=>Zi(T,r),config:r})}else if(T.variant==="approval"&&T.approval&&Xt.renderApproval){if(r.approval===!1)return;ot=Xt.renderApproval({message:T,defaultRenderer:()=>il(T,r),config:r})}else Xt.renderMessage&&(ot=Xt.renderMessage({message:T,defaultRenderer:()=>{let yt=as(T,y,dn,r.messageActions,et,{loadingIndicatorRenderer:B,widgetConfig:r});return T.role!=="user"&&dl(yt,T,r,j),yt},config:r}));if(!ot&&We){let yt=bi(T);if(yt){let kn=hr.get(T.id),Wr=kn!==ye,wn=r.wrapComponentDirectiveInBubble!==!1,Ln=null;if(Wr){let Dt=hi(yt,{config:r,message:T,transform:y});if(Dt)if(wn){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-${T.id}`,Ut.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let Nt=document.createElement("div");Nt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Nt.innerHTML=y({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),Ut.appendChild(Nt)}Ut.appendChild(Dt),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-${T.id}`,Ut.setAttribute("data-message-id",T.id),Ut.setAttribute("data-persona-component-directive","true"),T.content&&T.content.trim()){let Nt=document.createElement("div");Nt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Nt.innerHTML=y({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),Ut.appendChild(Nt)}Ut.appendChild(Dt),Ln=Ut}}if(Ln||kn!=null){let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${T.id}`,Dt.setAttribute("data-wrapper-id",T.id),Dt.setAttribute("data-component-directive-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),wn||Dt.classList.add("persona-w-full"),b.appendChild(Dt),ee.push({messageId:T.id,fingerprint:ye,bubble:Ln});return}}}if(!ot)if(T.variant==="reasoning"&&T.reasoning){if(!ke)return;ot=Yi(T,r)}else if(T.variant==="tool"&&T.toolCall){if(!Qe)return;ot=Zi(T,r)}else if(T.variant==="approval"&&T.approval){if(r.approval===!1)return;ot=il(T,r)}else{let yt=(to=r.layout)==null?void 0:to.messages;yt!=null&&yt.renderUserMessage&&T.role==="user"?ot=yt.renderUserMessage({message:T,config:r,streaming:!!T.streaming}):yt!=null&&yt.renderAssistantMessage&&T.role==="assistant"?ot=yt.renderAssistantMessage({message:T,config:r,streaming:!!T.streaming}):ot=as(T,y,yt,r.messageActions,et,{loadingIndicatorRenderer:B,widgetConfig:r}),T.role!=="user"&&ot&&dl(ot,T,r,j)}let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-${T.id}`,It.setAttribute("data-wrapper-id",T.id),T.role==="user"&&It.classList.add("persona-justify-end"),(ot==null?void 0:ot.getAttribute("data-persona-component-directive"))==="true"&&It.classList.add("persona-w-full"),It.appendChild(ot),tu(On,T.id,ye,It),b.appendChild(It)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ae=>{let We=Ae.getAttribute("data-persona-ask-sheet-for");We&&!W.has(We)&&co($e.composerOverlay,We)}),(st=(Ge=r.features)==null?void 0:Ge.toolCallDisplay)!=null&&st.grouped){let T=[],Ae=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Qe){Ae.push(We);return}Ae.length>1&&T.push(Ae),Ae=[]}),Ae.length>1&&T.push(Ae),T.forEach((We,Ve)=>{var pn,Xe;let ye=We.map(it=>Array.from(b.children).find(Cn=>Cn instanceof HTMLElement&&Cn.getAttribute("data-wrapper-id")===it.id)).filter(it=>!!it);if(ye.length<2)return;let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id=`wrapper-tool-group-${Ve}-${We[0].id}`,Mt.setAttribute("data-wrapper-id",`tool-group-${Ve}-${We[0].id}`);let ot=document.createElement("div");ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",ot.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${We.length} tools`,It=(Xe=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Xe.call(pn,{messages:We,toolCalls:We.map(it=>it.toolCall).filter(it=>!!it),defaultSummary:dn,config:r});F(Xt,It)||(Xt.textContent=dn);let vn=document.createElement("div");vn.className="persona-tool-group-stack persona-flex persona-flex-col",ot.append(Xt,vn),Mt.appendChild(ot),ye[0].before(Mt),ye.forEach((it,Cn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Cn<ye.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(it),vn.appendChild(mn)})})}nu(On,z);let Ce=m.some(T=>T.role==="assistant"&&T.streaming),Fe=m[m.length-1],Ze=(Fe==null?void 0:Fe.role)==="assistant"&&!Fe.streaming&&Fe.variant!=="approval";if(ce&&m.some(T=>T.role==="user")&&!Ce&&!Ze){let T={config:r,streaming:!0,location:"standalone",defaultRenderer:No},Ae=o.find(Ve=>Ve.renderLoadingIndicator),We=null;if(Ae!=null&&Ae.renderLoadingIndicator&&(We=Ae.renderLoadingIndicator(T)),We===null&&((at=r.loadingIndicator)!=null&&at.render)&&(We=r.loadingIndicator.render(T)),We===null&&(We=No()),We){let Ve=document.createElement("div"),ye=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;Ve.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(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ve.appendChild(We);let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id="wrapper-typing-indicator",Mt.setAttribute("data-wrapper-id","typing-indicator"),Mt.appendChild(Ve),b.appendChild(Mt)}}if(!ce&&m.length>0){let T=m[m.length-1],Ae={config:r,lastMessage:T,messageCount:m.length},We=o.find(ye=>ye.renderIdleIndicator),Ve=null;if(We!=null&&We.renderIdleIndicator&&(Ve=We.renderIdleIndicator(Ae)),Ve===null&&((Te=r.loadingIndicator)!=null&&Te.renderIdle)&&(Ve=r.loadingIndicator.renderIdle(Ae)),Ve){let ye=document.createElement("div"),Mt=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ye.className=Mt?["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(Ve);let ot=document.createElement("div");ot.className="persona-flex",ot.id="wrapper-idle-indicator",ot.setAttribute("data-wrapper-id","idle-indicator"),ot.appendChild(ye),b.appendChild(ot)}}if(za(c,b),le.length>0)for(let{messageId:T,fingerprint:Ae,bubble:We}of le){let Ve=c.querySelector(`#wrapper-${T}`);Ve&&We!==null&&(Ve.replaceChildren(We),Ve.setAttribute("data-bubble-fp",Ae),rr.set(T,Ae))}if(rr.size>0)for(let T of rr.keys())z.has(T)||rr.delete(T);if(ee.length>0)for(let{messageId:T,fingerprint:Ae,bubble:We}of ee){let Ve=c.querySelector(`#wrapper-${T}`);Ve&&We!==null&&(Ve.replaceChildren(We),Ve.setAttribute("data-bubble-fp",Ae),hr.set(T,Ae))}if(hr.size>0)for(let T of hr.keys())z.has(T)||hr.delete(T)},Qr=null,pa=()=>{var y;if(Qr)return;let c=b=>{let M=b.composedPath();M.includes(G)||ve&&M.includes(ve)||Ht(!1,"user")};Qr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},vs=()=>{var m;if(!Qr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Qr,!0),Qr=null};ft.push(()=>vs());let Xr=null,ua=()=>{var y;if(Xr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Ht(!1,"user"))};Xr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},Cs=()=>{var m;if(!Xr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Xr,!0),Xr=null};ft.push(()=>Cs());let Yr=!1,ws=new Set,ma=()=>{var m,y,b,M;let c=(b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((M=r.features)==null?void 0:M.streamAnimation)},Pr=()=>{var st,at,Me,Te;if(!_())return;let c=$e.peekBanner,m=$e.peekTextNode;if(!c||!m)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let y=(st=j==null?void 0:j.getMessages())!=null?st:[],b;for(let Ue=y.length-1;Ue>=0;Ue--){let T=y[Ue];if(T.role==="assistant"&&T.content){b=T;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let M=b.content,B=!!b.streaming,F=ma(),z=Ga(F),W=z.type!=="none"?qs(z.type,F==null?void 0:F.plugins):null,be=((at=W==null?void 0:W.isAnimating)==null?void 0:at.call(W,b))===!0,le=W!==null&&(B||be);le&&W&&!ws.has(W.name)&&(ji(W,e),ws.add(W.name));let ee=le&&(W!=null&&W.containerClass)?W.containerClass:null,ue=(Me=m.dataset.personaPeekStreamClass)!=null?Me:null;ue&&ue!==ee&&(m.classList.remove(ue),delete m.dataset.personaPeekStreamClass),ee&&ue!==ee&&(m.classList.add(ee),m.dataset.personaPeekStreamClass=ee),le?(m.style.setProperty("--persona-stream-step",`${z.speed}ms`),m.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Ce=le?Qa(M,z.buffer,W,b,B):M;if(le&&z.placeholder==="skeleton"&&B&&(!Ce||!Ce.trim())){let Ue=document.createElement("div"),T=Vs();T.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(T),za(m,Ue)}else{let Ue=Math.max(0,Ce.length-100),T=Ce.length>100?Ce.slice(-100):Ce,Ae=Lo(T);if(!le||!W){let We=Ce.length>100?`\u2026${T}`:T;m.textContent!==We&&(m.textContent=We)}else{let We=Ae;(W.wrap==="char"||W.wrap==="word")&&(We=zs(Ae,W.wrap,`peek-${b.id}`,{skipTags:W.skipTags,startIndex:Ue}));let Ve=document.createElement("div");if(Ve.innerHTML=We,W.useCaret&&T.length>0){let ye=Xa(),Mt=Ve.querySelectorAll(".persona-stream-char, .persona-stream-word"),ot=Mt[Mt.length-1];ot!=null&&ot.parentNode?ot.parentNode.insertBefore(ye,ot.nextSibling):Ve.appendChild(ye)}za(m,Ve),(Te=W.onAfterRender)==null||Te.call(W,{container:m,bubble:c,messageId:b.id,message:b,speed:z.speed,duration:z.duration})}}let Ge=ce||Yr;c.classList.toggle("persona-pill-peek--visible",Ge)};if(_()){let c=$e.peekBanner;if(c){let b=M=>{M.preventDefault(),M.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Yr||(Yr=!0,Pr())},y=()=>{Yr&&(Yr=!1,Pr())};V.addEventListener("pointerenter",m),V.addEventListener("pointerleave",y),ft.push(()=>{V.removeEventListener("pointerenter",m),V.removeEventListener("pointerleave",y)}),ve&&(ve.addEventListener("pointerenter",m),ve.addEventListener("pointerleave",y),ft.push(()=>{ve.removeEventListener("pointerenter",m),ve.removeEventListener("pointerleave",y)}))}let ga=c=>{var ue,Ce,Fe,Ze,Ge,st,at,Me;let m=(Ce=(ue=r.launcher)==null?void 0:ue.composerBar)!=null?Ce:{},y=(Fe=m.expandedSize)!=null?Fe:"anchored",b=(Ze=m.bottomOffset)!=null?Ze:"16px",M=m.collapsedMaxWidth,B=(Ge=m.expandedMaxWidth)!=null?Ge:"880px",F=(st=m.expandedTopOffset)!=null?st:"5vh",z=(at=m.modalMaxWidth)!=null?at:"880px",W=(Me=m.modalMaxHeight)!=null?Me:"min(90vh, 800px)",be="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",ee=G.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",ve){let Te=ve.style;Te.bottom=b,Te.width=M!=null?M:""}if(c&&y!=="fullscreen"){if(y==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=z,ee.maxWidth=be,ee.maxHeight=W,ee.height=W;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${b} + ${le})`,ee.top=F,ee.width=B,ee.maxWidth=be}},Zr=()=>{var W,be,le,ee,ue,Ce,Fe,Ze;if(!U())return;if(_()){let st=(le=((be=(W=r.launcher)==null?void 0:W.composerBar)!=null?be:{}).expandedSize)!=null?le:"anchored",at=R?"expanded":"collapsed";G.dataset.state=at,G.dataset.expandedSize=st,ve&&(ve.dataset.state=at,ve.dataset.expandedSize=st),G.style.removeProperty("display"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ga(R),re.style.display=R?"flex":"none",tr(),R?(pa(),ua()):(vs(),Cs()),Pr();return}let c=nn(r),m=(ee=e.ownerDocument.defaultView)!=null?ee:window,y=(Ce=(ue=r.launcher)==null?void 0:ue.mobileBreakpoint)!=null?Ce:640,b=(Ze=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ze:!0,M=m.innerWidth<=y,B=b&&M&&S,F=Xn(r).reveal;R?(G.style.removeProperty("display"),G.style.display=c?"flex":"",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0"),V.classList.add("persona-scale-100","persona-opacity-100"),H?H.element.style.display="none":A&&(A.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!B?(G.style.removeProperty("display"),G.style.display="flex",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.setProperty("display","none","important"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.display="",G.classList.add("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100"),V.classList.add("persona-scale-95","persona-opacity-0")),H?H.element.style.display=c?"none":"":A&&(A.style.display=c?"none":""))},Ht=(c,m="user")=>{var B,F;if(!U()||R===c)return;let y=R;R=c,Zr();let b=(()=>{var Fe,Ze,Ge,st,at,Me,Te,Ue,T,Ae;let z=(Ze=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?Ze:!1,W=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,be=(at=(st=r.launcher)==null?void 0:st.mobileFullscreen)!=null?at:!0,le=(Te=(Me=r.launcher)==null?void 0:Me.mobileBreakpoint)!=null?Te:640,ee=W.innerWidth<=le,ue=nn(r)&&be&&ee,Ce=_()&&((Ae=(T=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:T.expandedSize)!=null?Ae:"fullscreen")==="fullscreen";return z||be&&ee&&S||ue||Ce})();if(R&&b){if(!Gt){let z=e.getRootNode(),W=z instanceof ShadowRoot?z.host:e.closest(".persona-host");W&&(Gt=Ui(W,(F=(B=r.launcher)==null?void 0:B.zIndex)!=null?F:hn))}Qt||(Qt=qi(e.ownerDocument))}else R||(Gt==null||Gt(),Gt=null,Qt==null||Qt(),Qt=null);R&&(Q(),Gr(!0));let M={open:R,source:m,timestamp:Date.now()};R&&!y?s.emit("widget:opened",M):!R&&y&&s.emit("widget:closed",M),s.emit("widget:state",{open:R,launcherEnabled:S,voiceActive:mt.active,streaming:j.isStreaming()})},qo=c=>{qt(c?"stop":"send"),I&&(I.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=()=>{mt.active||Pe&&Pe.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>zo(),200)});let As=()=>{var y,b,M,B,F,z,W,be,le,ee,ue;Cr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",pr.textContent=(B=(M=r.copy)==null?void 0:M.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",Pe.placeholder=(z=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?z:"How can I help...";let c=Ee.querySelector("[data-persona-intro-card]");if(c){let Ce=((W=r.copy)==null?void 0:W.showWelcomeCard)!==!1;c.style.display=Ce?"":"none",Ce?(Ee.classList.remove("persona-gap-3"),Ee.classList.add("persona-gap-6")):(Ee.classList.remove("persona-gap-6"),Ee.classList.add("persona-gap-3"))}!((le=(be=r.sendButton)==null?void 0:be.useIcon)!=null&&le)&&!(j!=null&&j.isStreaming())&&(ne.textContent=(ue=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?ue:"Send"),Pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Pe.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,fa=()=>{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(j=new es(r,{onMessagesChanged(c){yo(xe,c,Ie),fa(),j&&(c.some(M=>M.role==="user")?nr.render([],j,Pe,c):nr.render(r.suggestionChips,j,Pe,c,r.suggestionChipsConfig)),Gr(!ce),da(c);let m=[...c].reverse().find(b=>b.role==="user"),y=mt.lastUserMessageId;m&&m.id!==y&&(mt.lastUserMessageId=m.id,s.emit("user:message",m)),mt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Uo(c),Pr()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Oe(Jt,(M=>{var B,F,z,W;return M==="idle"?(B=m.idleText)!=null?B:fn.idle:M==="connecting"?(F=m.connectingText)!=null?F:fn.connecting:M==="connected"?(z=m.connectedText)!=null?z:fn.connected:M==="error"?(W=m.errorText)!=null?W:fn.error:fn[M]})(c),m,c)},onStreamingChanged(c){ce=c,qo(c),j&&yo(xe,j.getMessages(),Ie),c||Gr(!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(),ya();break;case"speaking":lr(),ba();break;default:c==="idle"&&j.isBargeInActive()?(lr(),eo(),I==null||I.setAttribute("aria-label","End voice session")):(mt.active=!1,lr(),Gn("system"),Tn());break}},onArtifactsState(c){Rn=c,Dn(),Uo()}}),Lt.current=j,((bc=(yc=r.voiceRecognition)==null?void 0:yc.provider)==null?void 0:bc.type)==="runtype")try{j.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&j.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(X||r.onSSEEvent)&&j.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=ml(c.metadata),k.syncFromMetadata()),(m=c.messages)!=null&&m.length&&j.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&j.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Ss=()=>{var m,y,b;!_()||R||!((b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Ht(!0,"auto")},Es=c=>{var M;if(c.preventDefault(),j.isStreaming()){j.cancel();return}let m=Pe.value.trim(),y=(M=Ct==null?void 0:Ct.hasAttachments())!=null?M:!1;if(!m&&!y)return;Ss();let b;y&&(b=[],b.push(...Ct.getContentParts()),m&&b.push(Bs(m))),Pe.value="",Pe.style.height="auto",j.sendMessage(m,{contentParts:b}),y&&Ct.clearAttachments()},Ts=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),ne.click())},Ms=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!Ct)return;let m=Ff(c.clipboardData);m.length!==0&&(c.preventDefault(),await Ct.handleFiles(m))},xn=null,$n=!1,Ir=null,nt=null,ks=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,bo=(c="user")=>{var B,F,z,W,be,le,ee;if($n||j.isStreaming())return;let m=ks();if(!m)return;xn=new m;let b=(F=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?F:2e3;xn.continuous=!0,xn.interimResults=!0,xn.lang="en-US";let M=Pe.value;xn.onresult=ue=>{let Ce="",Fe="";for(let Ge=0;Ge<ue.results.length;Ge++){let st=ue.results[Ge],at=st[0].transcript;st.isFinal?Ce+=at+" ":Fe=at}let Ze=M+Ce+Fe;Pe.value=Ze,Ir&&clearTimeout(Ir),(Ce||Fe)&&(Ir=window.setTimeout(()=>{let Ge=Pe.value.trim();Ge&&xn&&$n&&(ir(),Pe.value="",Pe.style.height="auto",j.sendMessage(Ge,{viaVoice:!0}))},b))},xn.onerror=ue=>{ue.error!=="no-speech"&&ir()},xn.onend=()=>{if($n){let ue=Pe.value.trim();ue&&ue!==M.trim()&&(Pe.value="",Pe.style.height="auto",j.sendMessage(ue,{viaVoice:!0})),ir()}};try{if(xn.start(),$n=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),Gn(c),Tn(),I){let ue=(z=r.voiceRecognition)!=null?z:{};nt={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(W=ue.iconName)!=null?W:"mic",iconSize:parseFloat((ee=(le=ue.iconSize)!=null?le:(be=r.sendButton)==null?void 0:be.size)!=null?ee:"40")||24};let Ce=ue.recordingBackgroundColor,Fe=ue.recordingIconColor,Ze=ue.recordingBorderColor;if(I.classList.add("persona-voice-recording"),I.style.backgroundColor=Ce!=null?Ce:"var(--persona-voice-recording-bg, #ef4444)",I.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let Ge=I.querySelector("svg");Ge&&Ge.setAttribute("stroke",Fe)}Ze&&(I.style.borderColor=Ze),I.setAttribute("aria-label","Stop voice recognition")}}catch{ir("system")}},ir=(c="user")=>{if($n){if($n=!1,Ir&&(clearTimeout(Ir),Ir=null),xn){try{xn.stop()}catch{}xn=null}if(mt.active=!1,Gn(c),Tn(),I){if(I.classList.remove("persona-voice-recording"),nt){I.style.backgroundColor=nt.backgroundColor,I.style.color=nt.color,I.style.borderColor=nt.borderColor;let m=I.querySelector("svg");m&&m.setAttribute("stroke",nt.color||"currentColor"),nt=null}I.setAttribute("aria-label","Start voice recognition")}}},ha=(c,m)=>{var st,at,Me,Te,Ue,T,Ae,We;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((st=c==null?void 0:c.provider)==null?void 0:st.type)==="runtype";if(!(y||b))return null;let B=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 z=(at=c==null?void 0:c.iconName)!=null?at:"mic",W=(Me=m==null?void 0:m.size)!=null?Me:"40px",be=(Te=c==null?void 0:c.iconSize)!=null?Te:W,le=parseFloat(be)||24,ee=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:m==null?void 0:m.backgroundColor,ue=(T=c==null?void 0:c.iconColor)!=null?T: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",ue?F.style.color=ue:F.style.color="var(--persona-text, #111827)";let Fe=me(z,le,ue||"currentColor",1.5);Fe?F.appendChild(Fe):F.textContent="\u{1F3A4}",ee?F.style.backgroundColor=ee: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),B.appendChild(F);let Ze=(Ae=c==null?void 0:c.tooltipText)!=null?Ae:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&Ze){let Ve=h("div","persona-send-button-tooltip");Ve.textContent=Ze,B.appendChild(Ve)}return{micButton:F,micButtonWrapper:B}},Vo=()=>{var m,y,b,M,B;if(!I||nt)return;let c=(m=r.voiceRecognition)!=null?m:{};nt={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((B=(M=c.iconSize)!=null?M:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Jo=(c,m)=>{var B,F,z,W,be;if(!I)return;let y=I.querySelector("svg");y&&y.remove();let b=(be=nt==null?void 0:nt.iconSize)!=null?be:parseFloat((W=(z=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?z:(F=r.sendButton)==null?void 0:F.size)!=null?W:"40")||24,M=me(c,b,m,1.5);M&&I.appendChild(M)},xo=()=>{I&&I.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},eo=()=>{var M;if(!I)return;Vo();let c=(M=r.voiceRecognition)!=null?M:{},m=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(xo(),I.classList.add("persona-voice-recording"),I.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",I.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let B=I.querySelector("svg");B&&B.setAttribute("stroke",y)}b&&(I.style.borderColor=b),I.setAttribute("aria-label","Stop voice recognition")},ya=()=>{var z,W,be,le,ee,ue,Ce,Fe;if(!I)return;Vo();let c=(z=r.voiceRecognition)!=null?z:{},m=j.getVoiceInterruptionMode(),y=(W=c.processingIconName)!=null?W:"loader",b=(le=(be=c.processingIconColor)!=null?be:nt==null?void 0:nt.color)!=null?le:"",M=(ue=(ee=c.processingBackgroundColor)!=null?ee:nt==null?void 0:nt.backgroundColor)!=null?ue:"",B=(Fe=(Ce=c.processingBorderColor)!=null?Ce:nt==null?void 0:nt.borderColor)!=null?Fe:"";xo(),I.classList.add("persona-voice-processing"),I.style.backgroundColor=M,I.style.borderColor=B;let F=b||"currentColor";I.style.color=F,Jo(y,F),I.setAttribute("aria-label","Processing voice input"),m==="none"&&(I.style.cursor="default")},ba=()=>{var be,le,ee,ue,Ce,Fe,Ze,Ge,st,at,Me,Te;if(!I)return;Vo();let c=(be=r.voiceRecognition)!=null?be:{},m=j.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:y,M=(Fe=c.speakingIconColor)!=null?Fe:m==="barge-in"?(ue=(ee=c.recordingIconColor)!=null?ee:nt==null?void 0:nt.color)!=null?ue:"":(Ce=nt==null?void 0:nt.color)!=null?Ce:"",B=(st=c.speakingBackgroundColor)!=null?st:m==="barge-in"?(Ze=c.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(Ge=nt==null?void 0:nt.backgroundColor)!=null?Ge:"",F=(Te=c.speakingBorderColor)!=null?Te:m==="barge-in"?(at=c.recordingBorderColor)!=null?at:"":(Me=nt==null?void 0:nt.borderColor)!=null?Me:"";xo(),I.classList.add("persona-voice-speaking"),I.style.backgroundColor=B,I.style.borderColor=F;let z=M||"currentColor";I.style.color=z,Jo(b,z);let W=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";I.setAttribute("aria-label",W),m==="none"&&(I.style.cursor="default"),m==="barge-in"&&I.classList.add("persona-voice-recording")},lr=()=>{var c,m,y;I&&(xo(),nt&&(I.style.backgroundColor=(c=nt.backgroundColor)!=null?c:"",I.style.color=(m=nt.color)!=null?m:"",I.style.borderColor=(y=nt.borderColor)!=null?y:"",Jo(nt.iconName,nt.color||"currentColor"),nt=null),I.style.cursor="",I.setAttribute("aria-label","Start voice recognition"))},vo=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let y=j.getVoiceStatus(),b=j.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){j.stopVoicePlayback();return}if(j.isBargeInActive()){j.stopVoicePlayback(),j.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Tn(),Gn("user"),lr()});return}j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),mt.manuallyDeactivated=!j.isVoiceActive(),Tn(),Gn("user"),j.isVoiceActive()?eo():lr()});return}if($n){let y=Pe.value.trim();mt.manuallyDeactivated=!0,Tn(),ir("user"),y&&(Pe.value="",Pe.style.height="auto",j.sendMessage(y))}else mt.manuallyDeactivated=!1,Tn(),bo("user")};ur=vo,I&&(I.addEventListener("click",vo),ft.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(j.isVoiceActive()&&j.toggleVoice(),lr()):ir("system"),I&&I.removeEventListener("click",vo)}));let Ko=s.on("assistant:complete",()=>{ys&&(mt.active||mt.manuallyDeactivated||ys==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!mt.active&&!mt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),Gn("auto"),j.isVoiceActive()&&eo()}):bo("auto"))},600))});ft.push(Ko);let Je=s.on("action:resubmit",()=>{setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)});ft.push(Je);let C=()=>{Ht(!R,"user")},H=null,A=null;if(S&&!_()){let c=o.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Ks(r,C).element,onToggle:C});m&&(A=m)}A||(H=Ks(r,C))}H?e.appendChild(H.element):A&&e.appendChild(A),Zr(),nr.render(r.suggestionChips,j,Pe,void 0,r.suggestionChipsConfig),As(),qo(j.isStreaming()),Gr(!0),aa(),D&&(!S||_()?setTimeout(()=>zo(),0):R&&setTimeout(()=>zo(),200));let Q=()=>{var W,be,le,ee,ue,Ce,Fe,Ze,Ge,st,at,Me,Te,Ue,T,Ae,We,Ve,ye,Mt,ot,Xt;if(_()){qn(),Zr();return}let c=nn(r),m=(be=(W=r.launcher)==null?void 0:W.sidebarMode)!=null?be:!1,y=c||m||((ee=(le=r.launcher)==null?void 0:le.fullHeight)!=null?ee:!1),b=(ue=e.ownerDocument.defaultView)!=null?ue:window,M=(Fe=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Fe:!0,B=(Ge=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?Ge:640,F=b.innerWidth<=B,z=M&&F&&S;try{if(z){tr(),no(e,r);return}if(O&&(O=!1,tr(),no(e,r)),!S&&!c){V.style.height="",V.style.width="";return}if(!m&&!c){let dn=(at=(st=r==null?void 0:r.launcher)==null?void 0:st.width)!=null?at:r==null?void 0:r.launcherWidth,It=dn!=null?dn:Un;V.style.width=It,V.style.maxWidth=It}if(fr(),!y){let dn=b.innerHeight,It=64,vn=(Te=(Me=r.launcher)==null?void 0:Me.heightOffset)!=null?Te:0,pn=Math.max(200,dn-It),Xe=Math.min(640,pn),it=Math.max(200,Xe-vn);V.style.height=`${it}px`}}finally{if(qn(),Zr(),R&&S){let It=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((Ae=(T=r.launcher)==null?void 0:T.mobileBreakpoint)!=null?Ae:640),vn=(Ve=(We=r.launcher)==null?void 0:We.sidebarMode)!=null?Ve:!1,pn=(Mt=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Mt:!0,Xe=nn(r)&&pn&&It,it=vn||pn&&It&&S||Xe;if(it&&!Qt){let Cn=e.getRootNode(),mn=Cn instanceof ShadowRoot?Cn.host:e.closest(".persona-host");mn&&!Gt&&(Gt=Ui(mn,(Xt=(ot=r.launcher)==null?void 0:ot.zIndex)!=null?Xt:hn)),Qt=qi(e.ownerDocument)}else it||(Gt==null||Gt(),Gt=null,Qt==null||Qt(),Qt=null)}}};Q();let oe=(xc=e.ownerDocument.defaultView)!=null?xc:window;if(oe.addEventListener("resize",Q),ft.push(()=>oe.removeEventListener("resize",Q)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{qn()});c.observe(_e),ft.push(()=>c.disconnect())}sr=Ee.scrollTop;let Y=Ee.scrollHeight,Ke=()=>{let c=Ee.scrollTop,m=Ee.scrollHeight,y=m<Y;Y=m;let{action:b,nextLastScrollTop:M}=Ja({following:or.isFollowing(),currentScrollTop:c,lastScrollTop:sr,nearBottom:_s(Ee,hs),userScrollThreshold:oa,isAutoScrolling:Mr||fo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(sr=M,b==="resume"){Kr();return}b==="pause"&&xs()};Ee.addEventListener("scroll",Ke,{passive:!0}),ft.push(()=>Ee.removeEventListener("scroll",Ke));let Ne=c=>{let m=Ka({following:or.isFollowing(),deltaY:c.deltaY,nearBottom:_s(Ee,hs),resumeWhenNearBottom:!0});m==="pause"?xs():m==="resume"&&Kr()};Ee.addEventListener("wheel",Ne,{passive:!0}),ft.push(()=>Ee.removeEventListener("wheel",Ne)),ut.addEventListener("click",()=>{Ee.scrollTop=Ee.scrollHeight,sr=Ee.scrollTop,Kr(),Gr(!0)}),ft.push(()=>ut.remove()),ft.push(()=>{bs()});let rt=()=>{je&&(Fn&&(je.removeEventListener("click",Fn),Fn=null),U()?(je.style.display="",Fn=()=>{Ht(!1,"user")},je.addEventListener("click",Fn)):je.style.display="none")};rt(),(()=>{let{clearChatButton:c}=$e;c&&c.addEventListener("click",()=>{j.clearMessages(),On.clear(),Kr(),co($e.composerOverlay);try{localStorage.removeItem(gs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==gs)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={},k.syncFromMetadata(),X==null||X.clear(),ie==null||ie.update()})})(),Ot&&Ot.addEventListener("submit",Es),Pe==null||Pe.addEventListener("keydown",Ts),Pe==null||Pe.addEventListener("paste",Ms);let Et="persona-attachment-drop-active",Pt=0,Zt=()=>{Pt=0,re.classList.remove(Et)},ht=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&Ct!==null},Tt=c=>{!Ci(c.dataTransfer)||!ht()||(Pt++,Pt===1&&re.classList.add(Et))},rn=c=>{!Ci(c.dataTransfer)||!ht()||(Pt--,Pt<=0&&Zt())},un=c=>{!Ci(c.dataTransfer)||!ht()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},cn=c=>{var y;if(!Ci(c.dataTransfer)||!ht())return;c.preventDefault(),c.stopPropagation(),Zt();let m=Array.from((y=c.dataTransfer.files)!=null?y:[]);m.length!==0&&Ct.handleFiles(m)},$t=!0;re.addEventListener("dragenter",Tt,$t),re.addEventListener("dragleave",rn,$t),e.addEventListener("dragover",un,$t),e.addEventListener("drop",cn,$t);let Mn=e.ownerDocument,Il=c=>{ht()&&c.preventDefault()},Wl=c=>{ht()&&c.preventDefault()};Mn.addEventListener("dragover",Il),Mn.addEventListener("drop",Wl),ft.push(()=>{Ot&&Ot.removeEventListener("submit",Es),Pe==null||Pe.removeEventListener("keydown",Ts),Pe==null||Pe.removeEventListener("paste",Ms)}),ft.push(()=>{re.removeEventListener("dragenter",Tt,$t),re.removeEventListener("dragleave",rn,$t),e.removeEventListener("dragover",un,$t),e.removeEventListener("drop",cn,$t),Mn.removeEventListener("dragover",Il),Mn.removeEventListener("drop",Wl),Zt()}),ft.push(()=>{j.cancel()}),H?ft.push(()=>{H==null||H.destroy()}):A&&ft.push(()=>{A==null||A.remove()});let en={update(c){var tn,br,Rr,xa,va,Ca,Eo,wa,Ls,Tc,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,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,Cd,wd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,jd,Ud,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,vp,Cp;let m=r.toolCall,y=r.messageActions,b=(tn=r.layout)==null?void 0:tn.messages,M=r.colorScheme,B=r.loadingIndicator,F=r.iterationDisplay,z=(br=r.features)==null?void 0:br.showReasoning,W=(Rr=r.features)==null?void 0:Rr.showToolCalls,be=(xa=r.features)==null?void 0:xa.toolCallDisplay,le=(va=r.features)==null?void 0:va.reasoningDisplay;r={...r,...c},tr(),no(e,r),ui(e,r),mi(e,r),Dn(),r.colorScheme!==M&&Jr();let ee=ea.getForInstance(r.plugins);o.length=0,o.push(...ee),S=(Eo=(Ca=r.launcher)==null?void 0:Ca.enabled)!=null?Eo:!0,L=(Ls=(wa=r.launcher)==null?void 0:wa.autoExpand)!=null?Ls:!1,ke=(Mc=(Tc=r.features)==null?void 0:Tc.showReasoning)!=null?Mc:!0,Qe=(Lc=(kc=r.features)==null?void 0:kc.showToolCalls)!=null?Lc:!0,pe=(Ic=(Pc=r.features)==null?void 0:Pc.scrollToBottom)!=null?Ic:{},_r(),Lr();let ue=ge;if(ge=(Rc=(Wc=r.features)==null?void 0:Wc.showEventStreamToggle)!=null?Rc:!1,ge&&!ue){if(X||(te=new Zs(qe),X=new Ys(Se,te),te.open().then(()=>X==null?void 0:X.restore()).catch(()=>{}),j.setSSEEventCallback((Z,vt)=>{var _t;(_t=r.onSSEEvent)==null||_t.call(r,Z,vt),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!gt&&De){let Z=(Bc=(Hc=r.features)==null?void 0:Hc.eventStream)==null?void 0:Bc.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Z!=null&&Z.toggleButton?" "+Z.toggleButton:"");gt=h("button",vt),gt.style.width="28px",gt.style.height="28px",gt.style.color=Sn.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let _t=me("activity","18px","currentColor",1.5);_t&&gt.appendChild(_t);let lt=$e.clearChatButtonWrapper,St=$e.closeButtonWrapper,on=lt||St;on&&on.parentNode===De?De.insertBefore(gt,on):De.appendChild(gt),gt.addEventListener("click",()=>{He?er():Ar()})}}else!ge&&ue&&(er(),gt&&(gt.remove(),gt=null),X==null||X.clear(),te==null||te.destroy(),X=null,te=null);if(((Dc=r.launcher)==null?void 0:Dc.enabled)===!1&&H&&(H.destroy(),H=null),((Nc=r.launcher)==null?void 0:Nc.enabled)===!1&&A&&(A.remove(),A=null),((Fc=r.launcher)==null?void 0:Fc.enabled)!==!1&&!H&&!A){let Z=o.find(vt=>vt.renderLauncher);if(Z!=null&&Z.renderLauncher){let vt=Z.renderLauncher({config:r,defaultRenderer:()=>Ks(r,C).element,onToggle:C});vt&&(A=vt,e.appendChild(A))}A||(H=Ks(r,C),e.appendChild(H.element))}H&&H.update(r),we&&((Oc=r.launcher)==null?void 0:Oc.title)!==void 0&&(we.textContent=r.launcher.title),Be&&(($c=r.launcher)==null?void 0:$c.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Ce=(_c=r.layout)==null?void 0:_c.header;if((Ce==null?void 0:Ce.layout)!==E&&De){let Z=Ce?os(r,Ce,{showClose:U(),onClose:()=>Ht(!1,"user")}):Dr({config:r,showClose:U(),onClose:()=>Ht(!1,"user")});De.replaceWith(Z.header),De=Z.header,q=Z.iconHolder,we=Z.headerTitle,Be=Z.headerSubtitle,je=Z.closeButton,E=Ce==null?void 0:Ce.layout}else if(Ce&&(q&&(q.style.display=Ce.showIcon===!1?"none":""),we&&(we.style.display=Ce.showTitle===!1?"none":""),Be&&(Be.style.display=Ce.showSubtitle===!1?"none":""),je&&(je.style.display=Ce.showCloseButton===!1?"none":""),$e.clearChatButtonWrapper)){let Z=Ce.showClearChat;if(Z!==void 0){$e.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:vt}=$e;vt&&!vt.classList.contains("persona-absolute")&&(Z?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let Ze=((jc=r.layout)==null?void 0:jc.showHeader)!==!1;De&&(De.style.display=Ze?"":"none");let Ge=((Uc=r.layout)==null?void 0:Uc.showFooter)!==!1;_e&&(_e.style.display=Ge?"":"none"),qn(),Lr(),S!==P?S?Ht(L,"auto"):(R=!0,Zr()):L!==N&&Ht(L,"auto"),N=L,P=S,Q(),rt();let Me=JSON.stringify(c.toolCall)!==JSON.stringify(m),Te=JSON.stringify(r.messageActions)!==JSON.stringify(y),Ue=JSON.stringify((qc=r.layout)==null?void 0:qc.messages)!==JSON.stringify(b),T=((zc=r.loadingIndicator)==null?void 0:zc.render)!==(B==null?void 0:B.render)||((Vc=r.loadingIndicator)==null?void 0:Vc.renderIdle)!==(B==null?void 0:B.renderIdle)||((Jc=r.loadingIndicator)==null?void 0:Jc.showBubble)!==(B==null?void 0:B.showBubble),Ae=r.iterationDisplay!==F,We=((Gc=(Kc=r.features)==null?void 0:Kc.showReasoning)!=null?Gc:!0)!==(z!=null?z:!0)||((Xc=(Qc=r.features)==null?void 0:Qc.showToolCalls)!=null?Xc:!0)!==(W!=null?W:!0)||JSON.stringify((Yc=r.features)==null?void 0:Yc.toolCallDisplay)!==JSON.stringify(be)||JSON.stringify((Zc=r.features)==null?void 0:Zc.reasoningDisplay)!==JSON.stringify(le);(Me||Te||Ue||T||Ae||We)&&j&&(fs++,yo(xe,j.getMessages(),Ie));let ye=(ed=r.launcher)!=null?ed:{},Mt=(td=ye.headerIconHidden)!=null?td:!1,ot=(rd=(nd=r.layout)==null?void 0:nd.header)==null?void 0:rd.showIcon,Xt=Mt||ot===!1,dn=ye.headerIconName,It=(od=ye.headerIconSize)!=null?od:"48px";if(q){let Z=re.querySelector(".persona-border-b-persona-divider"),vt=Z==null?void 0:Z.querySelector(".persona-flex-col");if(Xt)q.style.display="none",Z&&vt&&!Z.contains(vt)&&Z.insertBefore(vt,Z.firstChild);else{if(q.style.display="",q.style.height=It,q.style.width=It,Z&&vt&&(Z.contains(q)?q.nextSibling!==vt&&(q.remove(),Z.insertBefore(q,vt)):Z.insertBefore(q,vt)),dn){let lt=parseFloat(It)||24,St=me(dn,lt*.6,"#ffffff",2);St?q.replaceChildren(St):q.textContent=(sd=ye.agentIconText)!=null?sd:"\u{1F4AC}"}else if(ye.iconUrl){let lt=q.querySelector("img");if(lt)lt.src=ye.iconUrl,lt.style.height=It,lt.style.width=It;else{let St=document.createElement("img");St.src=ye.iconUrl,St.alt="",St.className="persona-rounded-xl persona-object-cover",St.style.height=It,St.style.width=It,q.replaceChildren(St)}}else{let lt=q.querySelector("svg"),St=q.querySelector("img");(lt||St)&&q.replaceChildren(),q.textContent=(ad=ye.agentIconText)!=null?ad:"\u{1F4AC}"}let _t=q.querySelector("img");_t&&(_t.style.height=It,_t.style.width=It)}}let vn=(ld=(id=r.layout)==null?void 0:id.header)==null?void 0:ld.showTitle,pn=(dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.showSubtitle;if(we&&(we.style.display=vn===!1?"none":""),Be&&(Be.style.display=pn===!1?"none":""),je){((ud=(pd=r.layout)==null?void 0:pd.header)==null?void 0:ud.showCloseButton)===!1?je.style.display="none":je.style.display="";let vt=(md=ye.closeButtonSize)!=null?md:"32px",_t=(gd=ye.closeButtonPlacement)!=null?gd:"inline";je.style.height=vt,je.style.width=vt;let{closeButtonWrapper:lt}=$e,St=_t==="top-right",on=lt==null?void 0:lt.classList.contains("persona-absolute");if(lt&&St!==on)if(lt.remove(),St)lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",re.style.position="relative",re.appendChild(lt);else{let pt=(hd=(fd=ye.clearChat)==null?void 0:fd.placement)!=null?hd:"inline",sn=(bd=(yd=ye.clearChat)==null?void 0:yd.enabled)!=null?bd:!0;lt.className=sn&&pt==="inline"?"":"persona-ml-auto";let In=re.querySelector(".persona-border-b-persona-divider");In&&In.appendChild(lt)}if(je.style.color=ye.closeButtonColor||Sn.actionIconColor,ye.closeButtonBackgroundColor?(je.style.backgroundColor=ye.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let pt=ye.closeButtonBorderWidth||"0px",sn=ye.closeButtonBorderColor||"transparent";je.style.border=`${pt} solid ${sn}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");ye.closeButtonBorderRadius?(je.style.borderRadius=ye.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(je.style.paddingLeft=ye.closeButtonPaddingX,je.style.paddingRight=ye.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),ye.closeButtonPaddingY?(je.style.paddingTop=ye.closeButtonPaddingY,je.style.paddingBottom=ye.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom="");let gn=(xd=ye.closeButtonIconName)!=null?xd:"x",cr=(vd=ye.closeButtonIconText)!=null?vd:"\xD7";je.innerHTML="";let An=me(gn,"28px","currentColor",1);An?je.appendChild(An):je.textContent=cr;let Yt=(Cd=ye.closeButtonTooltipText)!=null?Cd:"Close chat",jn=(wd=ye.closeButtonShowTooltip)!=null?wd:!0;if(je.setAttribute("aria-label",Yt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),jn&&Yt)){let pt=null,sn=()=>{if(pt||!je)return;let To=je.ownerDocument,Ps=To.body;if(!Ps)return;pt=xr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Is=xr(To,"div");Is.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Is);let Mo=je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(ro),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ps.appendChild(pt)},In=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",In),je.addEventListener("focus",sn),je.addEventListener("blur",In),lt._cleanupTooltip=()=>{In(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",In)),je&&(je.removeEventListener("focus",sn),je.removeEventListener("blur",In))}}}let{clearChatButton:Xe,clearChatButtonWrapper:it}=$e;if(Xe){let Z=(Ad=ye.clearChat)!=null?Ad:{},vt=(Sd=Z.enabled)!=null?Sd:!0,_t=(Td=(Ed=r.layout)==null?void 0:Ed.header)==null?void 0:Td.showClearChat,lt=_t!==void 0?_t:vt,St=(Md=Z.placement)!=null?Md:"inline";if(it){it.style.display=lt?"":"none";let{closeButtonWrapper:on}=$e;!_()&&on&&!on.classList.contains("persona-absolute")&&(lt?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let gn=St==="top-right",cr=it.classList.contains("persona-absolute");if(!_()&&gn!==cr&&lt){if(it.remove(),gn)it.className="persona-absolute persona-top-4 persona-z-50",it.style.right="48px",re.style.position="relative",re.appendChild(it);else{it.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",it.style.right="";let Yt=re.querySelector(".persona-border-b-persona-divider"),jn=$e.closeButtonWrapper;Yt&&jn&&jn.parentElement===Yt?Yt.insertBefore(it,jn):Yt&&Yt.appendChild(it)}let An=$e.closeButtonWrapper;An&&!An.classList.contains("persona-absolute")&&(gn?An.classList.add("persona-ml-auto"):An.classList.remove("persona-ml-auto"))}}if(lt){if(!_()){let pt=(kd=Z.size)!=null?kd:"32px";Xe.style.height=pt,Xe.style.width=pt}let on=(Ld=Z.iconName)!=null?Ld:"refresh-cw",gn=(Pd=Z.iconColor)!=null?Pd:"";Xe.style.color=gn||Sn.actionIconColor,Xe.innerHTML="";let cr=_()?"14px":"20px",An=me(on,cr,"currentColor",2);if(An&&Xe.appendChild(An),Z.backgroundColor?(Xe.style.backgroundColor=Z.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let pt=Z.borderWidth||"0px",sn=Z.borderColor||"transparent";Xe.style.border=`${pt} solid ${sn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");Z.borderRadius?(Xe.style.borderRadius=Z.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),Z.paddingX?(Xe.style.paddingLeft=Z.paddingX,Xe.style.paddingRight=Z.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),Z.paddingY?(Xe.style.paddingTop=Z.paddingY,Xe.style.paddingBottom=Z.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let Yt=(Id=Z.tooltipText)!=null?Id:"Clear chat",jn=(Wd=Z.showTooltip)!=null?Wd:!0;if(Xe.setAttribute("aria-label",Yt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),jn&&Yt)){let pt=null,sn=()=>{if(pt||!Xe)return;let To=Xe.ownerDocument,Ps=To.body;if(!Ps)return;pt=xr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Is=xr(To,"div");Is.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Is);let Mo=Xe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(ro),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ps.appendChild(pt)},In=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",sn),it.addEventListener("mouseleave",In),Xe.addEventListener("focus",sn),Xe.addEventListener("blur",In),it._cleanupTooltip=()=>{In(),it&&(it.removeEventListener("mouseenter",sn),it.removeEventListener("mouseleave",In)),Xe&&(Xe.removeEventListener("focus",sn),Xe.removeEventListener("blur",In))}}}}let Cn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ta],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Oo.message,Oo.messageAndClick];k=na({parsers:Cn,handlers:mn,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Ku(r,k,se),j.updateConfig(r),yo(xe,j.getMessages(),Ie),nr.render(r.suggestionChips,j,Pe,void 0,r.suggestionChipsConfig),As(),qo(j.isStreaming());let Co=((Rd=r.voiceRecognition)==null?void 0:Rd.enabled)===!0,wo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ao=((Bd=(Hd=r.voiceRecognition)==null?void 0:Hd.provider)==null?void 0:Bd.type)==="runtype";if(Co&&(wo||Ao))if(!I||!he){let Z=ha(r.voiceRecognition,r.sendButton);Z&&(I=Z.micButton,he=Z.micButtonWrapper,wt.insertBefore(he,an),I.addEventListener("click",vo),I.disabled=j.isStreaming())}else{let Z=(Dd=r.voiceRecognition)!=null?Dd:{},vt=(Nd=r.sendButton)!=null?Nd:{},_t=(Fd=Z.iconName)!=null?Fd:"mic",lt=(Od=vt.size)!=null?Od:"40px",St=($d=Z.iconSize)!=null?$d:lt,on=parseFloat(St)||24;I.style.width=St,I.style.height=St,I.style.minWidth=St,I.style.minHeight=St;let gn=(jd=(_d=Z.iconColor)!=null?_d:vt.textColor)!=null?jd:"currentColor";I.innerHTML="";let cr=me(_t,on,gn,2);cr?I.appendChild(cr):I.textContent="\u{1F3A4}";let An=(Ud=Z.backgroundColor)!=null?Ud:vt.backgroundColor;An?I.style.backgroundColor=An:I.style.backgroundColor="",gn?I.style.color=gn:I.style.color="var(--persona-text, #111827)",Z.borderWidth?(I.style.borderWidth=Z.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),Z.borderColor?I.style.borderColor=Z.borderColor:I.style.borderColor="",Z.paddingX?(I.style.paddingLeft=Z.paddingX,I.style.paddingRight=Z.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),Z.paddingY?(I.style.paddingTop=Z.paddingY,I.style.paddingBottom=Z.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),jn=(qd=Z.tooltipText)!=null?qd:"Start voice recognition";if(((zd=Z.showTooltip)!=null?zd:!1)&&jn)if(Yt)Yt.textContent=jn,Yt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=jn,he==null||he.insertBefore(sn,I)}else Yt&&(Yt.style.display="none");he.style.display="",I.disabled=j.isStreaming()}else I&&he&&(he.style.display="none",((Jd=(Vd=r.voiceRecognition)==null?void 0:Vd.provider)==null?void 0:Jd.type)==="runtype"?j.isVoiceActive()&&j.toggleVoice():$n&&ir());if(((Kd=r.attachments)==null?void 0:Kd.enabled)===!0)if(!dt||!fe){let Z=(Gd=r.attachments)!=null?Gd:{},_t=(Xd=((Qd=r.sendButton)!=null?Qd:{}).size)!=null?Xd:"40px";Wt||(Wt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Wt.style.display="none",Ot.insertBefore(Wt,Pe)),ze||(ze=document.createElement("input"),ze.type="file",ze.accept=((Yd=Z.allowedTypes)!=null?Yd:Br).join(","),ze.multiple=((Zd=Z.maxFiles)!=null?Zd:4)>1,ze.style.display="none",ze.setAttribute("aria-label","Attach files"),Ot.insertBefore(ze,Pe)),dt=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",(ep=Z.buttonTooltipText)!=null?ep:"Attach file");let lt=(tp=Z.buttonIconName)!=null?tp:"paperclip",St=_t,on=parseFloat(St)||40,gn=Math.round(on*.6);fe.style.width=St,fe.style.height=St,fe.style.minWidth=St,fe.style.minHeight=St,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 cr=me(lt,gn,"currentColor",1.5);cr?fe.appendChild(cr):fe.textContent="\u{1F4CE}",fe.addEventListener("click",jn=>{jn.preventDefault(),ze==null||ze.click()}),dt.appendChild(fe);let An=(np=Z.buttonTooltipText)!=null?np:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=An,dt.appendChild(Yt),tt.append(dt),!Ct&&ze&&Wt&&(Ct=Bo.fromConfig(Z),Ct.setPreviewsContainer(Wt),ze.addEventListener("change",async()=>{Ct&&(ze!=null&&ze.files)&&(await Ct.handleFileSelect(ze.files),ze.value="")})),re.querySelector(".persona-attachment-drop-overlay")||re.appendChild(Gu(Z.dropOverlay))}else{dt.style.display="";let Z=(rp=r.attachments)!=null?rp:{};ze&&(ze.accept=((op=Z.allowedTypes)!=null?op:Br).join(","),ze.multiple=((sp=Z.maxFiles)!=null?sp:4)>1),Ct&&Ct.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}else dt&&(dt.style.display="none"),Ct&&Ct.clearAttachments(),(ap=re.querySelector(".persona-attachment-drop-overlay"))==null||ap.remove();let zt=(ip=r.sendButton)!=null?ip:{},So=(lp=zt.useIcon)!=null?lp:!1,to=(cp=zt.iconText)!=null?cp:"\u2191",yt=zt.iconName,kn=(dp=zt.tooltipText)!=null?dp:"Send message",Wr=(pp=zt.showTooltip)!=null?pp:!1,wn=(up=zt.size)!=null?up:"40px",Ln=zt.backgroundColor,Dt=zt.textColor;if(So){if(ne.style.width=wn,ne.style.height=wn,ne.style.minWidth=wn,ne.style.minHeight=wn,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.innerHTML="",Dt?ne.style.color=Dt:ne.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Z=parseFloat(wn)||24,vt=(Dt==null?void 0:Dt.trim())||"currentColor",_t=me(yt,Z,vt,2);_t?ne.appendChild(_t):ne.textContent=to}else ne.textContent=to;ne.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ln?(ne.style.backgroundColor=Ln,ne.classList.remove("persona-bg-persona-primary")):(ne.style.backgroundColor="",ne.classList.add("persona-bg-persona-primary"))}else ne.textContent=(gp=(mp=r.copy)==null?void 0:mp.sendButtonLabel)!=null?gp:"Send",ne.style.width="",ne.style.height="",ne.style.minWidth="",ne.style.minHeight="",ne.style.fontSize="",ne.style.lineHeight="",ne.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?(ne.style.backgroundColor=Ln,ne.classList.remove("persona-bg-persona-accent")):ne.classList.add("persona-bg-persona-accent"),Dt?ne.style.color=Dt:ne.classList.add("persona-text-white");zt.borderWidth?(ne.style.borderWidth=zt.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),zt.borderColor?ne.style.borderColor=zt.borderColor:ne.style.borderColor="",zt.paddingX?(ne.style.paddingLeft=zt.paddingX,ne.style.paddingRight=zt.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),zt.paddingY?(ne.style.paddingTop=zt.paddingY,ne.style.paddingBottom=zt.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Ut=an==null?void 0:an.querySelector(".persona-send-button-tooltip");if(Wr&&kn)if(Ut)Ut.textContent=kn,Ut.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=kn,an==null||an.insertBefore(Z,ne)}else Ut&&(Ut.style.display="none");let Nt=(xp=(fp=r.layout)==null?void 0:fp.contentMaxWidth)!=null?xp:_()?(bp=(yp=(hp=r.launcher)==null?void 0:hp.composerBar)==null?void 0:yp.contentMaxWidth)!=null?bp:"720px":void 0;Nt?(xe.style.maxWidth=Nt,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",Ot&&(Ot.style.maxWidth=Nt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Bt&&(Bt.style.maxWidth=Nt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto")):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""));let Vt=(vp=r.statusIndicator)!=null?vp:{},Pn=(Cp=Vt.visible)!=null?Cp:!0;if(Jt.style.display=Pn?"":"none",j){let Z=j.getStatus();Oe(Jt,(_t=>{var lt,St,on,gn;return _t==="idle"?(lt=Vt.idleText)!=null?lt:fn.idle:_t==="connecting"?(St=Vt.connectingText)!=null?St:fn.connecting:_t==="connected"?(on=Vt.connectedText)!=null?on:fn.connected:_t==="error"?(gn=Vt.errorText)!=null?gn:fn.error:fn[_t]})(Z),Vt,Z)}Jt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let _n=Vt.align==="left"?"persona-text-left":Vt.align==="center"?"persona-text-center":"persona-text-right";Jt.classList.add(_n)},open(){U()&&Ht(!0,"api")},close(){U()&&Ht(!1,"api")},toggle(){U()&&Ht(!R,"api")},clearChat(){yn=!1,j.clearMessages(),On.clear(),Kr();try{localStorage.removeItem(gs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==gs)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={},k.syncFromMetadata(),X==null||X.clear(),ie==null||ie.update()},setMessage(c){return!Pe||j.isStreaming()?!1:(!R&&U()&&Ht(!0,"system"),Pe.value=c,Pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(j.isStreaming())return!1;let m=(c==null?void 0:c.trim())||Pe.value.trim();return m?(!R&&U()&&Ht(!0,"system"),Pe.value="",Pe.style.height="auto",j.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return j.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(j.isVoiceActive()||(!R&&U()&&Ht(!0,"system"),mt.manuallyDeactivated=!1,Tn(),j.toggleVoice().then(()=>{mt.active=j.isVoiceActive(),Gn("user"),j.isVoiceActive()&&eo()})),!0):$n?!0:ks()?(!R&&U()&&Ht(!0,"system"),mt.manuallyDeactivated=!1,Tn(),bo("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.isVoiceActive()?(j.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Tn(),Gn("user"),lr()}),!0):!1:$n?(mt.manuallyDeactivated=!0,Tn(),ir("user"),!0):!1},injectMessage(c){return!R&&U()&&Ht(!0,"system"),j.injectMessage(c)},injectAssistantMessage(c){!R&&U()&&Ht(!0,"system");let m=j.injectAssistantMessage(c);return $&&($=!1,J&&(clearTimeout(J),J=null),setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)),m},injectUserMessage(c){return!R&&U()&&Ht(!0,"system"),j.injectUserMessage(c)},injectSystemMessage(c){return!R&&U()&&Ht(!0,"system"),j.injectSystemMessage(c)},injectMessageBatch(c){return!R&&U()&&Ht(!0,"system"),j.injectMessageBatch(c)},injectComponentDirective(c){return!R&&U()&&Ht(!0,"system"),j.injectComponentDirective(c)},injectTestMessage(c){!R&&U()&&Ht(!0,"system"),j.injectTestEvent(c)},async connectStream(c,m){return j.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(){!ge||!X||Ar()},hideEventStream(){He&&er()},isEventStreamVisible(){return He},showArtifacts(){Zn(r)&&(yn=!1,Dn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){Zn(r)&&(yn=!0,Dn())},upsertArtifact(c){return Zn(r)?(yn=!1,j.upsertArtifact(c)):null},selectArtifact(c){Zn(r)&&j.selectArtifact(c)},clearArtifacts(){Zn(r)&&j.clearArtifacts()},getArtifacts(){var c;return(c=j==null?void 0:j.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=j==null?void 0:j.getSelectedArtifactId())!=null?c:null},focusInput(){return S&&!R&&!_()||!Pe?!1:(Pe.focus(),!0)},async resolveApproval(c,m){let b=j.getMessages().find(M=>{var B;return M.variant==="approval"&&((B=M.approval)==null?void 0:B.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);return j.resolveApproval(b.approval,m)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return U()&&R},isVoiceActive(){return mt.active},getState(){return{open:U()&&R,launcherEnabled:S,voiceActive:mt.active,streaming:j.isStreaming()}},showCSATFeedback(c){!R&&U()&&Ht(!0,"system");let m=xe.querySelector(".persona-feedback-container");m&&m.remove();let y=xi({onSubmit:async(b,M)=>{var B;j.isClientTokenMode()&&await j.submitCSATFeedback(b,M),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});xe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&U()&&Ht(!0,"system");let m=xe.querySelector(".persona-feedback-container");m&&m.remove();let y=vi({onSubmit:async(b,M)=>{var B;j.isClientTokenMode()&&await j.submitNPSFeedback(b,M),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});xe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return j.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return j.submitNPSFeedback(c,m)},destroy(){yr!=null&&(clearInterval(yr),yr=null),ft.forEach(c=>c()),G.remove(),ve==null||ve.remove(),H==null||H.destroy(),A==null||A.remove(),Fn&&je.removeEventListener("click",Fn)}};if((((vc=t==null?void 0:t.debugTools)!=null?vc:!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,ft.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=z=>{let W=z.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",m),ft.push(()=>{window.removeEventListener("persona:focusInput",m)}),ge){let z=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&en.showEventStream()},W=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",W),ft.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",W)})}let y=z=>{let W=z.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.showArtifacts()},b=z=>{let W=z.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.hideArtifacts()},M=z=>{let W=z.detail;W!=null&&W.instanceId&&W.instanceId!==c||W!=null&&W.artifact&&en.upsertArtifact(W.artifact)},B=z=>{let W=z.detail;W!=null&&W.instanceId&&W.instanceId!==c||typeof(W==null?void 0:W.id)=="string"&&en.selectArtifact(W.id)},F=z=>{let W=z.detail;(!(W!=null&&W.instanceId)||W.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",F),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",F)})}let Qn=Of(r.persistState);if(Qn&&U()){let c=$f(Qn.storage),m=`${Qn.keyPrefix}widget-open`,y=`${Qn.keyPrefix}widget-voice`,b=`${Qn.keyPrefix}widget-voice-mode`;if(c){let M=((Cc=Qn.persist)==null?void 0:Cc.openState)&&c.getItem(m)==="true",B=((wc=Qn.persist)==null?void 0:wc.voiceState)&&c.getItem(y)==="true",F=((Ac=Qn.persist)==null?void 0:Ac.voiceState)&&c.getItem(b)==="true";if(M&&setTimeout(()=>{en.open(),setTimeout(()=>{var z;if(B||F)en.startVoiceRecognition();else if((z=Qn.persist)!=null&&z.focusInput){let W=e.querySelector("textarea");W&&W.focus()}},100)},0),(Sc=Qn.persist)!=null&&Sc.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Ec=Qn.persist)!=null&&Ec.voiceState&&(s.on("voice:state",z=>{c.setItem(y,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(b,z.viaVoice?"true":"false")})),Qn.clearOnChatClear){let z=()=>{c.removeItem(m),c.removeItem(y),c.removeItem(b)},W=()=>z();window.addEventListener("persona:clear-chat",W),ft.push(()=>{window.removeEventListener("persona:clear-chat",W)})}}}return u&&U()&&setTimeout(()=>{en.open()},0),Pr(),en};var _f=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,n*parseFloat(o[1])/100):420},Qu=(e,n)=>{var r,o;let t=(o=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?o:!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"},yl=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=""},Xu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",yl(e)},gl=e=>{e.style.transition=""},fl=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=""},hl=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=""},jf=(e,n,t,r,o)=>{o?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Uf=(e,n,t,r,o,s)=>{let a=s?n:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Yu=(e,n,t,r,o,s,a)=>{var w,x,k,S,L,D;let i=Xn(s),d=i.reveal==="push";jf(e,n,t,r,d),Uf(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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?x:!0,p=(S=(k=s==null?void 0:s.launcher)==null?void 0:k.mobileBreakpoint)!=null?S:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fl(n),gl(r),Xu(r),hl(t),Ai(o,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((D=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?D:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Xu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",fl(n),gl(r),hl(t),Ai(o,r);let N=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",E=a?"translateX(0)":P;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=N,r.style.transform=E,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",gl(r),yl(r),Ai(o,r);let N=_f(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),E=i.animate?"transform 180ms ease":"none",O=i.side==="right"?a?`translateX(-${N}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${N}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=`${P+N}px`,n.style.transition=E,n.style.transform=O,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${P}px`,t.style.maxWidth=`${P}px`,t.style.minWidth=`${P}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="",fl(n),yl(r),hl(t),Ai(o,r);let N=i.reveal==="emerge";N?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",E=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",O=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",r.style.position="relative",r.style.overflow=N||O?"hidden":"visible",r.style.transition=E,N&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},qf=(e,n)=>{let t=e.ownerDocument.createElement("div");return Qu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Qu(t,r)},destroy(){t.remove()}}},zf=(e,n)=>{var L,D,N,P;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(D=(L=n==null?void 0:n.launcher)==null?void 0:L.enabled)==null||D?(P=(N=n==null?void 0:n.launcher)==null?void 0:N.autoExpand)!=null?P:!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(()=>{Yu(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{Yu(a,i,d,l,u,n,p),w()},k=a.ownerDocument.defaultView,S=()=>{x()};return k==null||k.addEventListener("resize",S),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(E){let O=E.launcherEnabled?E.open:!0;p!==O&&(p=O,x())},updateConfig(E){var O,_;n=E,((_=(O=n==null?void 0:n.launcher)==null?void 0:O.enabled)!=null?_:!0)===!1&&(p=!0),x()},destroy(){k==null||k.removeEventListener("resize",S),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},ra=(e,n)=>nn(n)?zf(e,n):qf(e,n);var bl={},Vf=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},Jf=()=>{try{if(typeof bl!="undefined"&&bl.url)return new URL("../widget.css",bl.url).href}catch{}return null},Zu=(e,n)=>{let t=Jf(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=n.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),n.head.appendChild(s)}},xl=e=>{var k;let n=Vf(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,o=e.config,s=ra(n,o),a,i=[],d=(S,L)=>{var E,O;let N=!((O=(E=L==null?void 0:L.launcher)==null?void 0:E.enabled)!=null?O:!0)||nn(L),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),N&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),t){let _=S.attachShadow({mode:"open"});_.appendChild(P),Zu(_,r)}else S.appendChild(P),Zu(S,r);return n.id&&P.setAttribute("data-persona-instance",n.id),P},l=()=>{s.syncWidgetState(a.getState())},u=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let S=d(s.host,o);a=wi(S,o,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};p(),(k=e.onReady)==null||k.call(e);let g=S=>{f(),s.destroy(),s=ra(n,S),o=S,p()},w={update(S){var O,_,U,R,$,J;let L={...o,...S,launcher:{...(O=o==null?void 0:o.launcher)!=null?O:{},...(_=S==null?void 0:S.launcher)!=null?_:{},dock:{...(R=(U=o==null?void 0:o.launcher)==null?void 0:U.dock)!=null?R:{},...(J=($=S==null?void 0:S.launcher)==null?void 0:$.dock)!=null?J:{}}}},D=nn(o),N=nn(L),P=so(o),E=so(L);if(D!==N||P!==E){g(L);return}o=L,s.updateConfig(o),a.update(S),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(w,{get(S,L,D){if(L==="host")return s.host;if(L in S)return Reflect.get(S,L,D);let N=a[L];return typeof N=="function"?N.bind(a):N}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var om=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Kf=new Set(["button","a","input","select","textarea","details","summary"]),Gf=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),vl=/\b(product|card|item|listing|result)\b/i,wl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Qf=3e3,Xf=100;function sm(e){let n=typeof e.className=="string"?e.className:"";if(vl.test(n)||e.id&&vl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&vl.test(r.value))return!0}return!1}function am(e){var n;return wl.test(((n=e.textContent)!=null?n:"").trim())}function im(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let o=(t=n[r].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yf(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function em(e){let n=e.match(wl);return n?n[0]:null}function tm(e){var r,o,s;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&&((o=n.textContent)!=null&&o.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(s=t==null?void 0:t.textContent)!=null&&s.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Zf(e){let n=[],t=r=>{let o=r.trim();o&&!n.includes(o)&&n.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;t((o=r.value)!=null?o:"")}),n.slice(0,6)}var eh="commerce-card",th="result-card";function nm(e){return!sm(e)||!am(e)||!im(e)&&!Yf(e)?0:5200}function rm(e){var r;return!sm(e)||am(e)||!im(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 Al=[{id:eh,scoreElement(e){return nm(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||wl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(nm(e)===0)return null;let{title:t,href:r}=tm(e),o=(u=(l=em(((d=e.textContent)!=null?d:"").trim()))!=null?l:em(n.text))!=null?u:"",s=Zf(e);return[r&&t?`[${t}](${r})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||n.text.trim().slice(0,120),`selector: ${n.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
101
101
  `)}},{id:th,scoreElement(e){return rm(e)},formatSummary(e,n){if(rm(e)===0)return null;let{title:t,href:r}=tm(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
102
- `)}}];function nh(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function rh(e){var u,p,f,g,w,x,M,S,L,D,N,P,E;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",o=(M=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?M:200,s=(L=(S=n.visibleOnly)!=null?S:e.visibleOnly)!=null?L:!0,a=(D=n.root)!=null?D:e.root,i=(N=n.mode)!=null?N:"structured",d=(P=n.maxCandidates)!=null?P:Math.max(500,t*10),l=(E=e.rules)!=null?E:Al;return i==="simple"&&e.rules&&e.rules.length>0?(nh(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Cl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var oh=["data-testid","data-product","data-action","data-id","data-name","data-type"];function sh(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"||Kf.has(n)||t&&Gf.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function lm(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function ah(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let o=e.getAttribute("aria-label");o&&(n["aria-label"]=o);let s=e.getAttribute("type");s&&(n.type=s);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 Sl(e){let n=e.tagName.toLowerCase();if(e.id){let o=`#${Cl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of oh){let s=e.getAttribute(o);if(s){let a=`${n}[${o}="${Cl(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${n}.${t.map(a=>Cl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(s>=0)return`${n}:nth-of-type(${s+1})`}return n}function ih(e){return e==="static"?Xf:Qf}function cm(e,n){var o;let t=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,n);return{selector:Sl(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:sh(e),attributes:ah(e)}}function lh(e,n,t,r){let o=ih(n.interactivity),s=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function ch(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 dh(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(om.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!lm(l)){i=a.nextNode();continue}let p=cm(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}=lh(l,p,e.rules,t);o.push({el:l,domIndex:s,enriched:p,score:w,formattingRule:x}),s+=1}i=a.nextNode()}o.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 o){if(d.length>=e.maxElements)break;ch(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 ph(e,n){let t=[],r=new Set,o=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&t.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(om.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!lm(d)){s=o.nextNode();continue}let u=cm(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){s=o.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}s=o.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 dm(e={}){var r;let n=rh(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?ph(n,t):dh(n,t):[]}var Si=100;function pm(e,n={}){var s;if(e.length===0)return"No page elements found.";let t=(s=n.mode)!=null?s:"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:
102
+ `)}}];function nh(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function rh(e){var u,p,f,g,w,x,k,S,L,D,N,P,E;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",o=(k=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?k:200,s=(L=(S=n.visibleOnly)!=null?S:e.visibleOnly)!=null?L:!0,a=(D=n.root)!=null?D:e.root,i=(N=n.mode)!=null?N:"structured",d=(P=n.maxCandidates)!=null?P:Math.max(500,t*10),l=(E=e.rules)!=null?E:Al;return i==="simple"&&e.rules&&e.rules.length>0?(nh(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Cl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var oh=["data-testid","data-product","data-action","data-id","data-name","data-type"];function sh(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"||Kf.has(n)||t&&Gf.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function lm(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function ah(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let o=e.getAttribute("aria-label");o&&(n["aria-label"]=o);let s=e.getAttribute("type");s&&(n.type=s);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 Sl(e){let n=e.tagName.toLowerCase();if(e.id){let o=`#${Cl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of oh){let s=e.getAttribute(o);if(s){let a=`${n}[${o}="${Cl(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${n}.${t.map(a=>Cl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(s>=0)return`${n}:nth-of-type(${s+1})`}return n}function ih(e){return e==="static"?Xf:Qf}function cm(e,n){var o;let t=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,n);return{selector:Sl(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:sh(e),attributes:ah(e)}}function lh(e,n,t,r){let o=ih(n.interactivity),s=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function ch(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 dh(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(om.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!lm(l)){i=a.nextNode();continue}let p=cm(l,e.maxTextLength),f=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(k=>k==="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}=lh(l,p,e.rules,t);o.push({el:l,domIndex:s,enriched:p,score:w,formattingRule:x}),s+=1}i=a.nextNode()}o.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 o){if(d.length>=e.maxElements)break;ch(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 ph(e,n){let t=[],r=new Set,o=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&t.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(om.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!lm(d)){s=o.nextNode();continue}let u=cm(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){s=o.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}s=o.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 dm(e={}){var r;let n=rh(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?ph(n,t):dh(n,t):[]}var Si=100;function pm(e,n={}){var s;if(e.length===0)return"No page elements found.";let t=(s=n.mode)!=null?s:"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(`
@@ -113,7 +113,7 @@ ${a.join(`
113
113
  ${a.join(`
114
114
  `)}`)}return r.join(`
115
115
 
116
- `)}var um={name:"@runtypelabs/persona",version:"3.21.2",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=um.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 mh(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 mm=`({ text, message }: any) => {
116
+ `)}var um={name:"@runtypelabs/persona",version:"3.21.3",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=um.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 mh(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 mm=`({ 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
@@ -433,5 +433,5 @@ ${a.join(`
433
433
  min-height: 300px;
434
434
  }
435
435
  }
436
- `;function Sh(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ah,document.head.appendChild(e)}function Eh(e,n){let t=e.clientWidth-Tl*2-Sm,r=e.clientHeight-Tl*2-Sm;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function Th(e,n,t,r,o){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=o==="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 Em(e,n){let{items:t,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="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");Sh();let u=Math.max(0,Math.min(r,t.length-1)),p=o,f=s,g=null,w=1,x=!1,M=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),L=h("div","persona-dc-toolbar-lead"),D=h("div","persona-dc-toolbar-trail"),N=jt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Re(-1)}),P=h("div");P.style.position="relative";let E=h("button","persona-dc-title-btn");E.type="button",E.setAttribute("aria-expanded","false"),E.setAttribute("aria-haspopup","listbox");let O=h("span","persona-dc-title-text"),_=h("span","persona-dc-title-chevron"),U=ge("chevron-down",12,"currentColor",2);U&&_.appendChild(U),E.append(O,_);let R=h("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let $=!1;function J(){R.innerHTML="";for(let G=0;G<t.length;G++){let V=t[G],ve=h("button","persona-dc-dropdown-item");ve.type="button",ve.setAttribute("role","option"),ve.setAttribute("aria-current",G===u?"true":"false");let $e=h("span");if($e.textContent=V.title,ve.appendChild($e),V.description){let re=h("span","persona-dc-dropdown-desc");re.textContent=V.description,ve.appendChild(re)}ve.addEventListener("click",()=>{Ie(),et(G)}),R.appendChild(ve)}}function se(){$=!$,R.style.display=$?"":"none",E.setAttribute("aria-expanded",$?"true":"false"),$&&J()}function Ie(){$&&($=!1,R.style.display="none",E.setAttribute("aria-expanded","false"))}E.addEventListener("click",G=>{G.stopPropagation(),se()});let Le=()=>Ie();document.addEventListener("click",Le),P.append(E,R);let Qe=jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Re(1)}),pe=h("span","persona-dc-counter");L.append(N,P,Qe,pe);let ue=null;i&&(ue=Qs({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:G=>{p=G,X.dataset.device=p,g=null,K()}}),D.appendChild(ue.element));let ke=null;if(a){let G=h("div","persona-dc-zoom-controls"),V=jt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let re=g!=null?g:w;g=Math.max(wm,re-Cm),K()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{g=1,K()});let ve=jt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let re=g!=null?g:w;g=Math.min(Am,re+Cm),K()}}),$e=jt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,K()}});G.append(V,ke,ve,$e),D.appendChild(G)}if(d){let G=h("div","persona-dc-separator");D.appendChild(G);let V=Qs({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ve=>{f=ve,X.dataset.colorScheme=f,He()}});D.appendChild(V.element)}let je=h("div","persona-dc-separator");D.appendChild(je);let te=jt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});D.appendChild(te),S.append(L,D);let Se=h("div","persona-dc-stage"),X=h("div","persona-dc-iframe-wrapper");X.dataset.device=p,X.dataset.colorScheme=f;let ie=h("iframe","persona-dc-iframe");ie.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ie.setAttribute("loading","lazy"),ie.title=t[u].title,X.appendChild(ie),Se.appendChild(X),M.append(S,Se),e.appendChild(M);function He(){var G;try{let V=(G=ie.contentDocument)==null?void 0:G.body;if(!V)return;f==="dark"?V.classList.add("theme-dark"):V.classList.remove("theme-dark")}catch{}}ie.addEventListener("load",()=>He());function de(){let G=t[u];O.textContent=G.title,pe.textContent=`${u+1} / ${t.length}`,ie.title=G.title}function Re(G){let V=((u+G)%t.length+t.length)%t.length;et(V)}function et(G){G<0||G>=t.length||(u=G,ie.src=t[u].url,de(),l==null||l(u,t[u]))}function K(){var ve;if(x)return;let G=(ve=vm[p])!=null?ve:vm.desktop;w=Eh(Se,G);let V=Math.max(wm,Math.min(Am,g!=null?g:w));Th(X,ie,G,V,p),ke&&(ke.textContent=`${Math.round(V*100)}%`)}let ae=new ResizeObserver(()=>K());ae.observe(Se),de(),ie.src=t[u].url,requestAnimationFrame(()=>K());function Oe(){x||(x=!0,ae.disconnect(),document.removeEventListener("click",Le),M.remove())}return{element:M,goTo:et,next:()=>Re(1),prev:()=>Re(-1),getIndex:()=>u,setDevice(G){p=G,X.dataset.device=G,ue==null||ue.setSelected(G),g=null,K()},setColorScheme(G){f=G,X.dataset.colorScheme=G},setZoom(G){g=G,K()},destroy:Oe}}function Tm(){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 Mm(){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 km(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 Lm(){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 Pm(){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),o=parseInt(e.slice(5,7),16),s=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(o+(255-o)*(1-n));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Im(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Mh={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Wm={components:{panel:{borderRadius:"0",shadow:"none"}}},Ml={id:"shop",label:"Shopping Assistant",config:{theme:Mh,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Un},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?"]}},kl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Wm}},Ll={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Wm}},Pl={shop:Ml,minimal:kl,fullscreen:Ll};function Rm(e){return Pl[e]}var kh=xl;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});
436
+ `;function Sh(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ah,document.head.appendChild(e)}function Eh(e,n){let t=e.clientWidth-Tl*2-Sm,r=e.clientHeight-Tl*2-Sm;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function Th(e,n,t,r,o){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=o==="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 Em(e,n){let{items:t,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="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");Sh();let u=Math.max(0,Math.min(r,t.length-1)),p=o,f=s,g=null,w=1,x=!1,k=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),L=h("div","persona-dc-toolbar-lead"),D=h("div","persona-dc-toolbar-trail"),N=jt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Re(-1)}),P=h("div");P.style.position="relative";let E=h("button","persona-dc-title-btn");E.type="button",E.setAttribute("aria-expanded","false"),E.setAttribute("aria-haspopup","listbox");let O=h("span","persona-dc-title-text"),_=h("span","persona-dc-title-chevron"),U=me("chevron-down",12,"currentColor",2);U&&_.appendChild(U),E.append(O,_);let R=h("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let $=!1;function J(){R.innerHTML="";for(let G=0;G<t.length;G++){let V=t[G],ve=h("button","persona-dc-dropdown-item");ve.type="button",ve.setAttribute("role","option"),ve.setAttribute("aria-current",G===u?"true":"false");let $e=h("span");if($e.textContent=V.title,ve.appendChild($e),V.description){let re=h("span","persona-dc-dropdown-desc");re.textContent=V.description,ve.appendChild(re)}ve.addEventListener("click",()=>{Ie(),et(G)}),R.appendChild(ve)}}function se(){$=!$,R.style.display=$?"":"none",E.setAttribute("aria-expanded",$?"true":"false"),$&&J()}function Ie(){$&&($=!1,R.style.display="none",E.setAttribute("aria-expanded","false"))}E.addEventListener("click",G=>{G.stopPropagation(),se()});let ke=()=>Ie();document.addEventListener("click",ke),P.append(E,R);let Qe=jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Re(1)}),ge=h("span","persona-dc-counter");L.append(N,P,Qe,ge);let pe=null;i&&(pe=Qs({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:G=>{p=G,X.dataset.device=p,g=null,K()}}),D.appendChild(pe.element));let Le=null;if(a){let G=h("div","persona-dc-zoom-controls"),V=jt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let re=g!=null?g:w;g=Math.max(wm,re-Cm),K()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{g=1,K()});let ve=jt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let re=g!=null?g:w;g=Math.min(Am,re+Cm),K()}}),$e=jt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,K()}});G.append(V,Le,ve,$e),D.appendChild(G)}if(d){let G=h("div","persona-dc-separator");D.appendChild(G);let V=Qs({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ve=>{f=ve,X.dataset.colorScheme=f,He()}});D.appendChild(V.element)}let qe=h("div","persona-dc-separator");D.appendChild(qe);let te=jt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});D.appendChild(te),S.append(L,D);let Se=h("div","persona-dc-stage"),X=h("div","persona-dc-iframe-wrapper");X.dataset.device=p,X.dataset.colorScheme=f;let ie=h("iframe","persona-dc-iframe");ie.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ie.setAttribute("loading","lazy"),ie.title=t[u].title,X.appendChild(ie),Se.appendChild(X),k.append(S,Se),e.appendChild(k);function He(){var G;try{let V=(G=ie.contentDocument)==null?void 0:G.body;if(!V)return;f==="dark"?V.classList.add("theme-dark"):V.classList.remove("theme-dark")}catch{}}ie.addEventListener("load",()=>He());function de(){let G=t[u];O.textContent=G.title,ge.textContent=`${u+1} / ${t.length}`,ie.title=G.title}function Re(G){let V=((u+G)%t.length+t.length)%t.length;et(V)}function et(G){G<0||G>=t.length||(u=G,ie.src=t[u].url,de(),l==null||l(u,t[u]))}function K(){var ve;if(x)return;let G=(ve=vm[p])!=null?ve:vm.desktop;w=Eh(Se,G);let V=Math.max(wm,Math.min(Am,g!=null?g:w));Th(X,ie,G,V,p),Le&&(Le.textContent=`${Math.round(V*100)}%`)}let ae=new ResizeObserver(()=>K());ae.observe(Se),de(),ie.src=t[u].url,requestAnimationFrame(()=>K());function Oe(){x||(x=!0,ae.disconnect(),document.removeEventListener("click",ke),k.remove())}return{element:k,goTo:et,next:()=>Re(1),prev:()=>Re(-1),getIndex:()=>u,setDevice(G){p=G,X.dataset.device=G,pe==null||pe.setSelected(G),g=null,K()},setColorScheme(G){f=G,X.dataset.colorScheme=G},setZoom(G){g=G,K()},destroy:Oe}}function Tm(){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 Mm(){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 km(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 Lm(){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 Pm(){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),o=parseInt(e.slice(5,7),16),s=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(o+(255-o)*(1-n));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Im(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Mh={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Wm={components:{panel:{borderRadius:"0",shadow:"none"}}},Ml={id:"shop",label:"Shopping Assistant",config:{theme:Mh,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Un},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?"]}},kl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Wm}},Ll={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Wm}},Pl={shop:Ml,minimal:kl,fullscreen:Ll};function Rm(e){return Pl[e]}var kh=xl;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