@runtypelabs/persona 3.23.0 → 3.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,18 +1,18 @@
1
- "use strict";var cg=Object.create;var Ha=Object.defineProperty;var dg=Object.getOwnPropertyDescriptor;var pg=Object.getOwnPropertyNames;var ug=Object.getPrototypeOf,mg=Object.prototype.hasOwnProperty;var gg=(e,t)=>{for(var n in t)Ha(e,n,{get:t[n],enumerable:!0})},zp=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of pg(t))!mg.call(e,s)&&s!==n&&Ha(e,s,{get:()=>t[s],enumerable:!(r=dg(t,s))||r.enumerable});return e};var Vp=(e,t,n)=>(n=e!=null?cg(ug(e)):{},zp(t||!e||!e.__esModule?Ha(n,"default",{value:e,enumerable:!0}):n,e)),fg=e=>zp(Ha({},"__esModule",{value:!0}),e);var Cy={};gg(Cy,{ASK_USER_QUESTION_TOOL_NAME:()=>yl,AgentWidgetClient:()=>Wo,AgentWidgetSession:()=>os,AttachmentManager:()=>Do,DEFAULT_COMPONENTS:()=>Zi,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ya,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Xn,DEFAULT_PALETTE:()=>Qi,DEFAULT_SEMANTIC:()=>Yi,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>Kl,PRESET_FULLSCREEN:()=>Vl,PRESET_MINIMAL:()=>zl,PRESET_SHOP:()=>ql,THEME_ZONES:()=>vu,VERSION:()=>jo,WEBMCP_TOOL_PREFIX:()=>_s,WebMcpBridge:()=>ts,accessibilityPlugin:()=>tg,animationsPlugin:()=>ng,applyThemeVariables:()=>so,attachHeaderToContainer:()=>No,brandPlugin:()=>rg,buildComposer:()=>cs,buildDefaultHeader:()=>il,buildHeader:()=>_r,buildHeaderWithLayout:()=>ls,buildMinimalHeader:()=>ll,collectEnrichedPageContext:()=>Fm,componentRegistry:()=>Ur,createActionManager:()=>ua,createAgentExperience:()=>Di,createAskUserQuestionBubble:()=>nm,createBestAvailableVoiceProvider:()=>Xa,createBubbleWithLayout:()=>$u,createCSATFeedback:()=>Ri,createComboButton:()=>gi,createComponentMiddleware:()=>vm,createComponentStreamParser:()=>Li,createDefaultSanitizer:()=>Ki,createDemoCarousel:()=>eg,createDirectivePostprocessor:()=>Qp,createDropdownMenu:()=>co,createFlexibleJsonStreamParser:()=>nu,createIconButton:()=>_t,createImagePart:()=>cu,createJsonStreamParser:()=>ja,createLabelButton:()=>oa,createLocalStorageAdapter:()=>ki,createMarkdownProcessor:()=>Fs,createMarkdownProcessorFromConfig:()=>Lo,createMessageActions:()=>ml,createNPSFeedback:()=>Hi,createPlainTextParser:()=>_a,createPlugin:()=>ag,createRegexJsonParser:()=>$a,createStandardBubble:()=>ds,createTextPart:()=>qs,createTheme:()=>as,createThemeObserver:()=>ni,createToggleGroup:()=>sa,createTypingIndicator:()=>Oo,createVoiceProvider:()=>Bo,createWidgetHostLayout:()=>ma,createXmlParser:()=>Ua,default:()=>wy,defaultActionHandlers:()=>$o,defaultJsonActionParser:()=>pa,defaultParseRules:()=>_l,detectColorScheme:()=>Js,directivePostprocessor:()=>Yp,ensureAskUserQuestionSheet:()=>fs,escapeHtml:()=>Po,extractComponentDirectiveFromMessage:()=>Wi,fileToImagePart:()=>du,formatEnrichedContext:()=>_m,generateAssistantMessageId:()=>Ro,generateCodeSnippet:()=>Km,generateMessageId:()=>ou,generateStableSelector:()=>$l,generateUserMessageId:()=>rs,getActiveTheme:()=>is,getColorScheme:()=>tl,getDisplayText:()=>au,getHeaderLayout:()=>cl,getImageParts:()=>lu,getPreset:()=>lg,hasComponentDirective:()=>Ii,hasImages:()=>iu,headerLayouts:()=>fi,highContrastPlugin:()=>sg,initAgentWidget:()=>Dl,isAskUserQuestionMessage:()=>$r,isComponentDirectiveType:()=>xm,isDockedMountMode:()=>on,isVoiceSupported:()=>Vs,isWebMcpToolName:()=>$s,listRegisteredStreamAnimations:()=>Ru,markdownPostprocessor:()=>Vi,mergeWithDefaults:()=>Za,normalizeContent:()=>su,parseAskUserQuestionPayload:()=>jr,pluginRegistry:()=>da,reducedMotionPlugin:()=>og,registerStreamAnimationPlugin:()=>Iu,removeAskUserQuestionSheet:()=>mo,renderComponentDirective:()=>Pi,renderLoadingIndicatorWithFallback:()=>ul,renderLucideIcon:()=>be,resolveDockConfig:()=>ir,resolveSanitizer:()=>es,resolveTokens:()=>ei,stripWebMcpPrefix:()=>Ji,themeToCssVariables:()=>ti,unregisterStreamAnimationPlugin:()=>Wu,validateImageFile:()=>pu,validateTheme:()=>el});module.exports=fg(Cy);var Jp=require("marked"),hg=e=>{if(e)return e},Fs=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new Jp.Marked({gfm:(s=t==null?void 0:t.gfm)!=null?s:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=hg(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},Lo=e=>e?Fs({markedOptions:e.options,renderer:e.renderer}):Fs(),yg=Fs(),Vi=e=>yg(e),Po=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Gp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Kp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Xp=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Kp(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Kp(t.length);return t.push({token:o,type:s}),o}),n},Qp=e=>{let t=Lo(e);return n=>{let r=[],s=Xp(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Gp(i)}"></div>`;o=o.replace(d,u)}),o}},Yp=e=>{let t=[],n=Xp(e,t),r=Vi(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Gp(o)}"></div>`;r=r.replace(a,d)}),r};var Zp=Vp(require("dompurify"),1),bg={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"]},xg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ki=()=>{let e=(0,Zp.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let r=n.attrValue;r.toLowerCase().startsWith("data:")&&!xg.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,bg)},es=e=>e===!1?null:typeof e=="function"?e:Ki();var _s="webmcp:",Ba={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ts=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return Ba.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=wg(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return br("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let m=typeof document!="undefined"&&!!document.modelContext;return br(m?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Ji(t),a;try{a=await s.getTools()}catch(m){let v=m instanceof Error?m.message:String(m);return br(`Failed to read WebMCP registry: ${v}`)}let i=a.find(m=>m.name===o);if(!i)return br(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return br(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let d={toolName:o,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return br("User declined the tool call.");if(r!=null&&r.aborted)return br("Aborted by cancel()");let l=new AbortController,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),f=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",f,{once:!0}));try{let m=await s.executeTool(i,Eg(n),{signal:l.signal});return Cg(m)}catch(m){if(u)return br(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let v=m instanceof Error?m.message:String(m);return br(v)}finally{clearTimeout(p),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ba.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ba.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Ag;try{return await n(t)}catch(s){return Ba.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>vg(t,r))}},Ji=e=>e.startsWith(_s)?e.slice(_s.length):e,$s=e=>e.startsWith(_s),vg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},wg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Cg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Tg(t)}]}},br=e=>({isError:!0,content:[{type:"text",text:e}]}),Ag=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Sg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var pg=Object.create;var Ha=Object.defineProperty;var ug=Object.getOwnPropertyDescriptor;var mg=Object.getOwnPropertyNames;var gg=Object.getPrototypeOf,fg=Object.prototype.hasOwnProperty;var hg=(e,n)=>{for(var t in n)Ha(e,t,{get:n[t],enumerable:!0})},zp=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of mg(n))!fg.call(e,s)&&s!==t&&Ha(e,s,{get:()=>n[s],enumerable:!(r=ug(n,s))||r.enumerable});return e};var Vp=(e,n,t)=>(t=e!=null?pg(gg(e)):{},zp(n||!e||!e.__esModule?Ha(t,"default",{value:e,enumerable:!0}):t,e)),bg=e=>zp(Ha({},"__esModule",{value:!0}),e);var Tb={};hg(Tb,{ASK_USER_QUESTION_TOOL_NAME:()=>bl,AgentWidgetClient:()=>Wo,AgentWidgetSession:()=>os,AttachmentManager:()=>Do,DEFAULT_COMPONENTS:()=>Zi,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ya,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Xn,DEFAULT_PALETTE:()=>Qi,DEFAULT_SEMANTIC:()=>Yi,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>Kl,PRESET_FULLSCREEN:()=>Vl,PRESET_MINIMAL:()=>zl,PRESET_SHOP:()=>ql,THEME_ZONES:()=>Cu,VERSION:()=>jo,WEBMCP_TOOL_PREFIX:()=>_s,WebMcpBridge:()=>ts,accessibilityPlugin:()=>rg,animationsPlugin:()=>og,applyThemeVariables:()=>so,attachHeaderToContainer:()=>No,brandPlugin:()=>sg,buildComposer:()=>cs,buildDefaultHeader:()=>il,buildHeader:()=>_r,buildHeaderWithLayout:()=>ls,buildMinimalHeader:()=>ll,collectEnrichedPageContext:()=>$m,componentRegistry:()=>Ur,createActionManager:()=>ua,createAgentExperience:()=>Di,createAskUserQuestionBubble:()=>om,createBestAvailableVoiceProvider:()=>Xa,createBubbleWithLayout:()=>Uu,createCSATFeedback:()=>Ri,createComboButton:()=>gi,createComponentMiddleware:()=>Cm,createComponentStreamParser:()=>Li,createDefaultSanitizer:()=>Ki,createDemoCarousel:()=>ng,createDirectivePostprocessor:()=>Qp,createDropdownMenu:()=>co,createFlexibleJsonStreamParser:()=>ou,createIconButton:()=>_t,createImagePart:()=>pu,createJsonStreamParser:()=>ja,createLabelButton:()=>oa,createLocalStorageAdapter:()=>ki,createMarkdownProcessor:()=>Fs,createMarkdownProcessorFromConfig:()=>Lo,createMessageActions:()=>ml,createNPSFeedback:()=>Hi,createPlainTextParser:()=>_a,createPlugin:()=>lg,createRegexJsonParser:()=>$a,createStandardBubble:()=>ds,createTextPart:()=>qs,createTheme:()=>as,createThemeObserver:()=>ni,createToggleGroup:()=>sa,createTypingIndicator:()=>Oo,createVoiceProvider:()=>Bo,createWidgetHostLayout:()=>ma,createXmlParser:()=>Ua,default:()=>Sb,defaultActionHandlers:()=>$o,defaultJsonActionParser:()=>pa,defaultParseRules:()=>_l,detectColorScheme:()=>Js,directivePostprocessor:()=>Yp,ensureAskUserQuestionSheet:()=>fs,escapeHtml:()=>Po,extractComponentDirectiveFromMessage:()=>Wi,fileToImagePart:()=>uu,formatEnrichedContext:()=>jm,generateAssistantMessageId:()=>Ro,generateCodeSnippet:()=>Gm,generateMessageId:()=>au,generateStableSelector:()=>$l,generateUserMessageId:()=>rs,getActiveTheme:()=>is,getColorScheme:()=>tl,getDisplayText:()=>lu,getHeaderLayout:()=>cl,getImageParts:()=>du,getPreset:()=>dg,hasComponentDirective:()=>Ii,hasImages:()=>cu,headerLayouts:()=>fi,highContrastPlugin:()=>ig,initAgentWidget:()=>Dl,isAskUserQuestionMessage:()=>$r,isComponentDirectiveType:()=>wm,isDockedMountMode:()=>on,isVoiceSupported:()=>Vs,isWebMcpToolName:()=>$s,listRegisteredStreamAnimations:()=>Bu,markdownPostprocessor:()=>Vi,mergeWithDefaults:()=>Za,normalizeContent:()=>iu,parseAskUserQuestionPayload:()=>jr,pluginRegistry:()=>da,reducedMotionPlugin:()=>ag,registerStreamAnimationPlugin:()=>Ru,removeAskUserQuestionSheet:()=>mo,renderComponentDirective:()=>Pi,renderLoadingIndicatorWithFallback:()=>ul,renderLucideIcon:()=>ye,resolveDockConfig:()=>ir,resolveSanitizer:()=>es,resolveTokens:()=>ei,stripWebMcpPrefix:()=>Ji,themeToCssVariables:()=>ti,unregisterStreamAnimationPlugin:()=>Hu,validateImageFile:()=>mu,validateTheme:()=>el});module.exports=bg(Tb);var Jp=require("marked"),yg=e=>{if(e)return e},Fs=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Jp.Marked({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=yg(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Lo=e=>e?Fs({markedOptions:e.options,renderer:e.renderer}):Fs(),xg=Fs(),Vi=e=>xg(e),Po=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Gp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Kp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Xp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Kp(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Kp(n.length);return n.push({token:o,type:s}),o}),t},Qp=e=>{let n=Lo(e);return t=>{let r=[],s=Xp(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Gp(i)}"></div>`;o=o.replace(d,u)}),o}},Yp=e=>{let n=[],t=Xp(e,n),r=Vi(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Gp(o)}"></div>`;r=r.replace(a,d)}),r};var Zp=Vp(require("dompurify"),1),vg={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"]},wg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ki=()=>{let e=(0,Zp.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:")&&!wg.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,vg)},es=e=>e===!1?null:typeof e=="function"?e:Ki();var _s="webmcp:",Ba={warn(e,...n){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...n)}};function tu(e){if(e.length===0)return"0:empty";let n=e.map(t=>{var r,s;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(s=t.origin)!=null?s:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${e.length}:${Cg(n.join(""))}`}function eu(e,n){let t=3735928559^n,r=1103547991^n;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Cg(e){let n=eu(e,0).toString(36),t=eu(e,2654435761).toString(36);return`${n}.${t}`}var ts=class{constructor(n){this.config=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=n.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(n){this.confirmHandler=n}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let n=this.getModelContext();if(!n)return[];let t;try{t=await n.getTools()}catch(s){return Ba.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return t.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Sg(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(n,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return yr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let m=typeof document!="undefined"&&!!document.modelContext;return yr(m?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Ji(n),a;try{a=await s.getTools()}catch(m){let x=m instanceof Error?m.message:String(m);return yr(`Failed to read WebMCP registry: ${x}`)}let i=a.find(m=>m.name===o);if(!i)return yr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return yr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return yr("Aborted by cancel()");let d={toolName:o,args:t,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return yr("User declined the tool call.");if(r!=null&&r.aborted)return yr("Aborted by cancel()");let l=new AbortController,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),f=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",f,{once:!0}));try{let m=await s.executeTool(i,kg(t),{signal:l.signal});return Tg(m)}catch(m){if(u)return yr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return yr("Aborted by cancel()");let x=m instanceof Error?m.message:String(m);return yr(x)}finally{clearTimeout(p),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(n){Ba.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",n),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let n=document.modelContext;if(!n||typeof n!="object")return null;let t=n;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ba.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):n}async requestConfirm(n){var r;let t=(r=this.confirmHandler)!=null?r:Eg;try{return await t(n)}catch(s){return Ba.warn(`Confirm handler threw for WebMCP tool '${n.toolName}'; declining.`,s),!1}}passesClientAllowlist(n){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Ag(n,r))}},Ji=e=>e.startsWith(_s)?e.slice(_s.length):e,$s=e=>e.startsWith(_s),Ag=(e,n)=>{if(n==="*")return!0;let t=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)},Sg=e=>{if(!(e===void 0||e===""))try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:void 0}catch{return}},Tg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let n;try{n=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return n!==null&&typeof n=="object"&&Array.isArray(n.content)?n:{content:[{type:"text",text:typeof n=="string"?n:Lg(n)}]}},yr=e=>({isError:!0,content:[{type:"text",text:e}]}),Eg=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let n=Mg(e.args),t=`Allow the AI to call ${e.toolName}`+(n?`
2
2
 
3
3
  Arguments:
4
- ${t}`:"")+(e.description?`
4
+ ${n}`:"")+(e.description?`
5
5
 
6
- ${e.description}`:"");return window.confirm(n)},Sg=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Eg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Tg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Or=require("partial-json"),Da=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ns=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)}},Mg=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},eu=e=>e.status==="complete"?Mg(e):e.status==="pending"?"Waiting":"",kg=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var tu=e=>e.status==="complete"?kg(e):"Using tool...",Na=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Us=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Na(t)},Oa=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Na(t)},Gi=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Us(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Fa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&js(r,n.slice(o,a.index),[]),a[1]!==void 0?js(r,a[1],["bold"]):a[2]!==void 0?js(r,a[2],["italic"]):a[3]!==void 0&&js(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&js(r,n.slice(o),[]),r},js=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Lg=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(t)},Mg=e=>{if(e==null)return"";try{let n=JSON.stringify(e,null,2);return n.length>500?n.slice(0,500)+"\u2026":n}catch{return String(e)}},kg=e=>{if(e===void 0)return"{}";try{let n=JSON.stringify(e);return n===void 0?"{}":n}catch{return"{}"}},Lg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Or=require("partial-json"),Da=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ns=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)}},Pg=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},nu=e=>e.status==="complete"?Pg(e):e.status==="pending"?"Waiting":"",Ig=e=>{var s,o,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var ru=e=>e.status==="complete"?Ig(e):"Using tool...",Na=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},Us=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Na(n)},Oa=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Na(n)},Gi=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Us(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Fa=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&js(r,t.slice(o,a.index),[]),a[1]!==void 0?js(r,a[1],["bold"]):a[2]!==void 0?js(r,a[2],["italic"]):a[3]!==void 0&&js(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&js(r,t.slice(o),[]),r},js=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},Wg=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Io=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},_a=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},$a=()=>{var t;let e=Lg();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},ja=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=(0,Or.parse)(n,Or.STR|Or.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Da(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Da(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},nu=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Da(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=(0,Or.parse)(o,Or.STR|Or.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Ua=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var qa=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Pg="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function Ig(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Xi=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 Wg(e){switch(e){case"json":return ja;case"regex-json":return $a;case"xml":return Ua;default:return _a}}var ru=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Rg(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=ru(n);if(!ru(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Io(e);return Io(t)!==null&&a===null?t:e}var Wo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Pg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Wg(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new ts(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/feedback`}async sendFeedback(t){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:m}),m}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Xi).map(m=>{var v,x,T;return{id:m.id,role:m.role,content:(T=(x=(v=m.contentParts)!=null?v:m.llmContent)!=null?x:m.rawContent)!=null?T:m.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:x}),x}if(f.status===429){let x=new Error(m.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let v=new Error(m.error||"Failed to send message");throw n({type:"error",error:v}),v}if(!f.body){let m=new Error("No response body received");throw n({type:"error",error:m}),m}n({type:"status",status:"connected"});try{await this.streamResponse(f.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,u;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||za}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Xi).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(t){var o;let r={messages:t.slice().filter(Xi).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Ot,cn,Bn,Yn;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=B=>{let se=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,De=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Qe=B.tools?B.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...B,reasoning:se,toolCall:De,tools:Qe}},p=B=>{n({type:"message",message:u(B)})},f=null,m=null,v={current:null},x={current:null},T=!1,S=new Map,W=new Map,I=new Map,O=new Map,P={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},R=(B,se,De="")=>`${B}::${se}::${De}`,_=(B,se)=>`${B}::${se}::`,$=(B,se,De,Qe)=>{let _e=R(B,se,De),$e=I.get(_e);if($e)return $e;let ot=De?`-${De}`:"",St={id:`nested-${B}-${se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Qe,parentToolId:B,parentStepId:se}};return I.set(_e,St),p(St),St},D=B=>{if(B==null)return null;try{return String(B)}catch{return null}},U=B=>{var se,De,Qe,_e,$e;return D(($e=(_e=(Qe=(De=(se=B.stepId)!=null?se:B.step_id)!=null?De:B.step)!=null?Qe:B.parentId)!=null?_e:B.flowStepId)!=null?$e:B.flow_step_id)},z=B=>{var se,De,Qe,_e,$e,ot,St;return D((St=(ot=($e=(_e=(Qe=(De=(se=B.callId)!=null?se:B.call_id)!=null?De:B.requestId)!=null?Qe:B.request_id)!=null?_e:B.toolCallId)!=null?$e:B.tool_call_id)!=null?ot:B.stepId)!=null?St:B.step_id)},oe=r,We=!1,He=()=>{if(f)return f;let B;return!We&&oe?(B=oe,We=!0):oe&&x.current?B=`${oe}_${x.current}`:B=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:B,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Oe=(B,se)=>{P.lastId=se,B&&P.byStep.set(B,se)},de=(B,se)=>{var $e;let De=($e=B.reasoningId)!=null?$e:B.id,Qe=U(B);if(De){let ot=String(De);return Oe(Qe,ot),ot}if(Qe){let ot=P.byStep.get(Qe);if(ot)return P.lastId=ot,ot}if(P.lastId&&!se)return P.lastId;if(!se)return null;let _e=`reason-${l()}`;return Oe(Qe,_e),_e},we=B=>{let se=S.get(B);if(se)return se;let De={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:B,status:"streaming",chunks:[]}};return S.set(B,De),p(De),De},ke=(B,se)=>{C.lastId=se,B&&C.byCall.set(B,se)},Pe=new Set,re=new Map,Le=new Set,K=new Map,ue=B=>{if(!B)return!1;let se=B.replace(/_+/g,"_").replace(/^_|_$/g,"");return se==="emit_artifact_markdown"||se==="emit_artifact_component"},he=(B,se)=>{var $e;let De=($e=B.toolId)!=null?$e:B.id,Qe=z(B);if(De){let ot=String(De);return ke(Qe,ot),ot}if(Qe){let ot=C.byCall.get(Qe);if(ot)return C.lastId=ot,ot}if(C.lastId&&!se)return C.lastId;if(!se)return null;let _e=`tool-${l()}`;return ke(Qe,_e),_e},ge=B=>{let se=W.get(B);if(se)return se;let De={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:B,status:"pending"}};return W.set(B,De),p(De),De},me=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let se=Number(B);if(!Number.isNaN(se)&&Number.isFinite(se))return se;let De=Date.parse(B);if(!Number.isNaN(De))return De}return Date.now()},Xe=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},V=new Map,ne=new Map,Re=new Map,fe=new Map,le=null,ie=(B,se,De)=>{var St;let Qe=Re.get(B);Qe||(Qe=[],Re.set(B,Qe));let _e=0,$e=Qe.length;for(;_e<$e;){let $t=_e+$e>>>1;Qe[$t].seq<se?_e=$t+1:$e=$t}((St=Qe[_e])==null?void 0:St.seq)===se?Qe[_e]={seq:se,text:De}:Qe.splice(_e,0,{seq:se,text:De});let ot="";for(let $t=0;$t<Qe.length;$t++)ot+=Qe[$t].text;return ot},Ye=(B,se)=>{let De=Xe(se),Qe=ne.get(B.id),_e=Rg(Qe,De);B.rawContent=_e;let $e=V.get(B.id),ot=ft=>{var qt;let rt=(qt=B.content)!=null?qt:"";ft.trim()!==""&&(rt.trim().length===0||ft.startsWith(rt)||ft.trimStart().startsWith(rt.trim()))&&(B.content=ft)},St=()=>{var ft;if($e){let rt=(ft=$e.close)==null?void 0:ft.call($e);rt instanceof Promise&&rt.catch(()=>{})}V.delete(B.id),ne.delete(B.id),B.streaming=!1,p(B)};if(!$e){ot(De),St();return}let $t=Io(_e);if($t!==null&&$t.trim()!==""){ot($t),St();return}let Jt=ft=>{var ae;let rt=typeof ft=="string"?ft:(ae=ft==null?void 0:ft.text)!=null?ae:null;if(rt!==null&&rt.trim()!=="")return rt;let qt=$e.getExtractedText();return qt!==null&&qt.trim()!==""?qt:De},J;try{J=$e.processChunk(_e)}catch{ot(De),St();return}if(J instanceof Promise){J.then(ft=>{ot(Jt(ft)),St()}).catch(()=>{ot(De),St()});return}ot(Jt(J)),St()},Ae=[],pe=!1,Q,je=()=>{pe||(pe=!0,queueMicrotask(()=>{pe=!1,Q()}))},At=new qa((B,se)=>{Ae.push({payloadType:B,payload:se}),je()}),X=null,Fe=new Map,kn=(Ot=this.config.iterationDisplay)!=null?Ot:"separate";for(Q=()=>{var B,se,De,Qe,_e,$e,ot,St,$t,Jt,J,ft,rt,qt,ae,xe,Ct,jt,en,bn,Mt,Et,yt,xt,zt,tt,Dn,Zn,xn,Nn,mt,vr,On,ho,Ln,Uo,zr,Mr,vt,Fn,_n,vn,It,er,tr,$n,Vr,kr,Kr,jn,Rt,wn,nr,Jr,Lr,Gr,wr,Un,dr,ht,Gt,Xt,qn,Xr,rr,pr,zn,E,Vn,ur,Pr,Cr,xs,mr,gr,fr,Ir,yo,ga,vs,fa,qo,gt,ws,or,Pn,ha,ya,zo,Wr,ba,bo,Cs,Rr,As,Qr,Yr,xa,va,qi,xo,Zr,wa,Ss,eo,Ca,Es,to,Ts,Aa,Hr,Sa,no,Ht,Vo,Ko,Ms,Ar,Ea,ks,Ls,Ta,Jo,Go,vo,Ma,ka,Ps,Is,Ws,Rs,Cn,Kn,Br,st,Hs,wo,hr;for(let Xo=0;Xo<Ae.length;Xo++){let qe=Ae[Xo].payloadType,A=Ae[Xo].payload;if(qe==="reason_start"){let j=(B=de(A,!0))!=null?B:`reason-${l()}`,k=we(j);k.reasoning=(se=k.reasoning)!=null?se:{id:j,status:"streaming",chunks:[]},k.reasoning.startedAt=(Qe=k.reasoning.startedAt)!=null?Qe:me((De=A.startedAt)!=null?De:A.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",p(k)}else if(qe==="reason_delta"||qe==="reason_chunk"){let j=($e=(_e=de(A,!1))!=null?_e:de(A,!0))!=null?$e:`reason-${l()}`,k=we(j);k.reasoning=(ot=k.reasoning)!=null?ot:{id:j,status:"streaming",chunks:[]},k.reasoning.startedAt=($t=k.reasoning.startedAt)!=null?$t:me((St=A.startedAt)!=null?St:A.timestamp);let Z=(ft=(J=(Jt=A.reasoningText)!=null?Jt:A.text)!=null?J:A.delta)!=null?ft:"";if(Z&&A.hidden!==!0){let ee=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ee!==void 0){let G=ie(j,ee,String(Z));k.reasoning.chunks=[G]}else k.reasoning.chunks.push(String(Z))}if(k.reasoning.status=A.done?"complete":"streaming",A.done){k.reasoning.completedAt=me((rt=A.completedAt)!=null?rt:A.timestamp);let ee=(qt=k.reasoning.startedAt)!=null?qt:Date.now();k.reasoning.durationMs=Math.max(0,((ae=k.reasoning.completedAt)!=null?ae:Date.now())-ee)}k.streaming=k.reasoning.status!=="complete",p(k)}else if(qe==="reason_complete"){let j=(Ct=(xe=de(A,!1))!=null?xe:de(A,!0))!=null?Ct:`reason-${l()}`,k=S.get(j);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=me((jt=A.completedAt)!=null?jt:A.timestamp);let ee=(en=k.reasoning.startedAt)!=null?en:Date.now();k.reasoning.durationMs=Math.max(0,((bn=k.reasoning.completedAt)!=null?bn:Date.now())-ee),k.streaming=!1,p(k)}let Z=U(A);Z&&P.byStep.delete(Z)}else if(qe==="tool_start"){let j=(Mt=he(A,!0))!=null?Mt:`tool-${l()}`,k=(Et=A.toolName)!=null?Et:A.name;if(ue(k)){Pe.add(j);continue}let Z=ge(j),ee=(yt=Z.toolCall)!=null?yt:{id:j,status:"pending"};ee.name=k!=null?k:ee.name,ee.status="running",A.args!==void 0?ee.args=A.args:A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=(zt=ee.startedAt)!=null?zt:me((xt=A.startedAt)!=null?xt:A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,Z.toolCall=ee,Z.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(Z.agentMetadata={executionId:(tt=G==null?void 0:G.executionId)!=null?tt:A.executionId,iteration:(Dn=G==null?void 0:G.iteration)!=null?Dn:A.iteration}),p(Z)}else if(qe==="tool_chunk"||qe==="tool_delta"){let j=(xn=(Zn=he(A,!1))!=null?Zn:he(A,!0))!=null?xn:`tool-${l()}`;if(Pe.has(j))continue;let k=ge(j),Z=(Nn=k.toolCall)!=null?Nn:{id:j,status:"running"};Z.startedAt=(vr=Z.startedAt)!=null?vr:me((mt=A.startedAt)!=null?mt:A.timestamp);let ee=(Ln=(ho=(On=A.text)!=null?On:A.delta)!=null?ho:A.message)!=null?Ln:"";ee&&(Z.chunks=(Uo=Z.chunks)!=null?Uo:[],Z.chunks.push(String(ee))),Z.status="running",k.toolCall=Z,k.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(k.agentMetadata=(vt=k.agentMetadata)!=null?vt:{executionId:(zr=G==null?void 0:G.executionId)!=null?zr:A.executionId,iteration:(Mr=G==null?void 0:G.iteration)!=null?Mr:A.iteration}),p(k)}else if(qe==="tool_complete"){let j=(_n=(Fn=he(A,!1))!=null?Fn:he(A,!0))!=null?_n:`tool-${l()}`;if(Pe.has(j)){Pe.delete(j);continue}let k=ge(j),Z=(vn=k.toolCall)!=null?vn:{id:j,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=me((It=A.completedAt)!=null?It:A.timestamp);let ee=(er=A.duration)!=null?er:A.executionTime;if(typeof ee=="number")Z.durationMs=ee;else{let Ne=(tr=Z.startedAt)!=null?tr:Date.now();Z.durationMs=Math.max(0,(($n=Z.completedAt)!=null?$n:Date.now())-Ne)}k.toolCall=Z,k.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(k.agentMetadata=(Kr=k.agentMetadata)!=null?Kr:{executionId:(Vr=G==null?void 0:G.executionId)!=null?Vr:A.executionId,iteration:(kr=G==null?void 0:G.iteration)!=null?kr:A.iteration}),p(k);let ze=z(A);ze&&C.byCall.delete(ze)}else if(qe==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let j=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,k=(jn=j!=null?j:A.toolId)!=null?jn:`local-${l()}`,Z=ge(k),ee=(Rt=Z.toolCall)!=null?Rt:{id:k,status:"pending"};ee.name=A.toolName,ee.args=A.parameters,ee.status="complete",ee.chunks=(wn=ee.chunks)!=null?wn:[],ee.startedAt=(Jr=ee.startedAt)!=null?Jr:me((nr=A.startedAt)!=null?nr:A.timestamp),ee.completedAt=(Lr=ee.completedAt)!=null?Lr:ee.startedAt,Z.toolCall=ee,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(wr=A.executionId)!=null?wr:(Gr=Z.agentMetadata)==null?void 0:Gr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},p(Z)}else if(qe==="text_start"){if((Un=A.toolContext)!=null&&Un.toolId)continue;let j=A.partId;if(j!==void 0&&x.current!==null&&j!==x.current){let k=f;k&&(k.streaming=!1,p(k),le=k,f=null,T=!0)}j!==void 0&&(x.current=j)}else if(qe==="text_end"){if((dr=A.toolContext)!=null&&dr.toolId)continue;let j=f;j&&(j.streaming=!1,p(j),le=j,f=null,T=!0)}else if(qe==="step_chunk"||qe==="step_delta"){let j=A.stepType,k=A.executionType;if(j==="tool"||k==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Gt=(ht=A.id)!=null?ht:Z.stepId)!=null?Gt:`step-${l()}`),it=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ke=`${Z.toolId}::${Ne}`,Je=O.get(Ke);if(it!==""&&Je!==void 0&&Je!==""&&Je!==it){let Tt=I.get(R(Z.toolId,Ne,Je));Tt&&Tt.streaming!==!1&&(Tt.streaming=!1,p(Tt))}it!==""&&O.set(Ke,it);let Ze=$(Z.toolId,Ne,it,Z.executionId),Qt=(rr=(Xr=(qn=(Xt=A.text)!=null?Xt:A.delta)!=null?qn:A.content)!=null?Xr:A.chunk)!=null?rr:"";Qt&&(Ze.content+=String(Qt),Ze.streaming=!0,p(Ze)),A.isComplete&&(Ze.streaming=!1,p(Ze));continue}let ee=A.partId;if(ee!==void 0&&x.current!==null&&ee!==x.current){let Ne=f;Ne&&(Ne.streaming=!1,p(Ne),le=Ne,f=null,T=!0)}ee!==void 0&&(x.current=ee);let G=ee!==void 0&&(pr=fe.get(ee))!=null?pr:He();ee!==void 0&&(G.partId||(G.partId=ee),fe.set(ee,G));let ze=(ur=(Vn=(E=(zn=A.text)!=null?zn:A.delta)!=null?E:A.content)!=null?Vn:A.chunk)!=null?ur:"";if(ze){let Ne=typeof A.seq=="number"?A.seq:void 0,it=ee!=null?ee:G.id,Ke=Ne!==void 0?ie(it,Ne,String(ze)):((Pr=ne.get(G.id))!=null?Pr:"")+ze;G.rawContent=Ke,V.has(G.id)||V.set(G.id,this.createStreamParser());let Je=V.get(G.id),Ze=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(Ze&&ne.set(G.id,Ke),Je.__isPlainTextParser===!0){G.content=Ne!==void 0?Ke:G.content+ze,ne.delete(G.id),V.delete(G.id),G.rawContent=void 0,p(G);continue}let Tt=Je.processChunk(Ke);if(Tt instanceof Promise)Tt.then(Lt=>{var mn;let sn=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(sn!==null&&sn.trim()!=="")G.content=sn,p(G);else if(!Ze&&!Ke.trim().startsWith("<")){let dn=f,tn=dn&&dn.id===G.id?dn:G;tn.id===G.id&&(tn.content=Ne!==void 0?Ke:tn.content+ze,ne.delete(tn.id),V.delete(tn.id),tn.rawContent=void 0,p(tn))}}).catch(()=>{G.content=Ne!==void 0?Ke:G.content+ze,ne.delete(G.id),V.delete(G.id),G.rawContent=void 0,p(G)});else{let Lt=typeof Tt=="string"?Tt:(Cr=Tt==null?void 0:Tt.text)!=null?Cr:null;Lt!==null&&Lt.trim()!==""?(G.content=Lt,p(G)):!Ze&&!Ke.trim().startsWith("<")&&(G.content=Ne!==void 0?Ke:G.content+ze,ne.delete(G.id),V.delete(G.id),G.rawContent=void 0,p(G))}}if(A.isComplete){let Ne=(mr=(xs=A.result)==null?void 0:xs.response)!=null?mr:G.content;if(Ne){let it=ne.get(G.id),Ke=it!=null?it:Xe(Ne);G.rawContent=Ke;let Je=V.get(G.id),Ze=null,Qt=!1;if(Je&&(Ze=Je.getExtractedText(),Ze===null&&(Ze=Io(Ke)),Ze===null)){let Tt=Je.processChunk(Ke);Tt instanceof Promise?(Qt=!0,Tt.then(Lt=>{var mn;let sn=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(sn!==null){let dn=f;dn&&dn.id===G.id&&(dn.content=sn,dn.streaming=!1,V.delete(dn.id),ne.delete(dn.id),p(dn))}})):Ze=typeof Tt=="string"?Tt:(gr=Tt==null?void 0:Tt.text)!=null?gr:null}if(!Qt){Ze!==null&&Ze.trim()!==""?G.content=Ze:ne.has(G.id)||(G.content=Xe(Ne));let Tt=V.get(G.id);if(Tt){let Lt=(fr=Tt.close)==null?void 0:fr.call(Tt);Lt instanceof Promise&&Lt.catch(()=>{}),V.delete(G.id)}ne.delete(G.id),G.streaming=!1,p(G)}}}}else if(qe==="step_complete"){let j=A.stepType,k=A.executionType;if(j==="tool"||k==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((yo=(Ir=A.id)!=null?Ir:Z.stepId)!=null?yo:"");if(Ne){let it=_(Z.toolId,Ne);for(let[Ke,Je]of I)Ke.startsWith(it)&&Je.streaming!==!1&&(Je.streaming=!1,p(Je));O.delete(`${Z.toolId}::${Ne}`)}continue}let ee=A.stopReason;if(T){if(f!==null){let Ke=f;ee&&(Ke.stopReason=ee),V.delete(Ke.id),ne.delete(Ke.id),Ke.streaming!==!1&&(Ke.streaming=!1,p(Ke))}let Ne=(ga=A.result)==null?void 0:ga.response,it=le;it&&(ee&&(it.stopReason=ee),Ne!=null?Ye(it,Ne):(V.delete(it.id),ne.delete(it.id))),le=null;continue}let G=(vs=A.result)==null?void 0:vs.response,ze=He();if(ee&&(ze.stopReason=ee),G!=null){let Ne=V.get(ze.id),it=!1,Ke=!1;if(Ne){let Je=Ne.getExtractedText(),Ze=ne.get(ze.id),Qt=Ze!=null?Ze:Xe(G);if(ze.rawContent=Qt,Je!==null&&Je.trim()!=="")ze.content=Je,it=!0;else{let Tt=Io(Qt);if(Tt!==null)ze.content=Tt,it=!0;else{let Lt=Ne.processChunk(Qt);if(Lt instanceof Promise)Ke=!0,Lt.then(sn=>{var dn;let mn=typeof sn=="string"?sn:(dn=sn==null?void 0:sn.text)!=null?dn:null;if(mn!==null&&mn.trim()!==""){let tn=f;tn&&tn.id===ze.id&&(tn.content=mn,tn.streaming=!1,V.delete(tn.id),ne.delete(tn.id),p(tn))}else{let tn=Ne.getExtractedText(),sr=f;sr&&sr.id===ze.id&&(tn!==null&&tn.trim()!==""?sr.content=tn:ne.has(sr.id)||(sr.content=Xe(G)),sr.streaming=!1,V.delete(sr.id),ne.delete(sr.id),p(sr))}});else{let sn=typeof Lt=="string"?Lt:(fa=Lt==null?void 0:Lt.text)!=null?fa:null;if(sn!==null&&sn.trim()!=="")ze.content=sn,it=!0;else{let mn=Ne.getExtractedText();mn!==null&&mn.trim()!==""&&(ze.content=mn,it=!0)}}}}}if(!Ke){if(!ze.rawContent){let Je=ne.get(ze.id);ze.rawContent=Je!=null?Je:Xe(G)}if(!it&&!ne.has(ze.id)&&(ze.content=Xe(G)),Ne){let Je=(qo=Ne.close)==null?void 0:qo.call(Ne);Je instanceof Promise&&Je.catch(()=>{})}V.delete(ze.id),ne.delete(ze.id),ze.streaming=!1,p(ze)}}else V.delete(ze.id),ne.delete(ze.id),ze.streaming=!1,p(ze)}else if(qe==="flow_complete"){let j=(gt=A.result)==null?void 0:gt.response;if(T){if(f!==null){let k=f;V.delete(k.id),ne.delete(k.id),k.streaming!==!1&&(k.streaming=!1,p(k))}}else if(j!=null){let k=He(),Z=ne.get(k.id),ee=Z!=null?Z:Xe(j);k.rawContent=ee;let G=Xe(j),ze=V.get(k.id);if(ze){let Ke=Io(ee);if(Ke!==null)G=Ke;else{let Je=ze.processChunk(ee);Je instanceof Promise&&Je.then(Qt=>{var Lt;let Tt=typeof Qt=="string"?Qt:(Lt=Qt==null?void 0:Qt.text)!=null?Lt:null;Tt!==null&&(k.content=Tt,k.streaming=!1,p(k))});let Ze=ze.getExtractedText();Ze!==null&&(G=Ze)}}V.delete(k.id),ne.delete(k.id);let Ne=G!==k.content,it=k.streaming!==!1;Ne&&(k.content=G),k.streaming=!1,(Ne||it)&&p(k)}else if(f!==null){let k=f;V.delete(k.id),ne.delete(k.id),k.streaming!==!1&&(k.streaming=!1,p(k))}n({type:"status",status:"idle"})}else if(qe==="agent_start")X={executionId:A.executionId,agentId:(ws=A.agentId)!=null?ws:"virtual",agentName:(or=A.agentName)!=null?or:"",status:"running",currentIteration:0,maxTurns:(Pn=A.maxTurns)!=null?Pn:1,startedAt:me(A.startedAt)};else if(qe==="agent_iteration_start"){if(X&&(X.currentIteration=A.iteration),kn==="separate"&&A.iteration>1){let j=f;j&&(j.streaming=!1,p(j),Fe.set(A.iteration-1,j),f=null)}}else if(qe==="agent_turn_start")m=null;else if(qe==="agent_turn_delta"){if(A.contentType==="text"){let j=He();j.content+=(ha=A.delta)!=null?ha:"",j.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:X==null?void 0:X.agentName},m=j,p(j)}else if(A.contentType==="thinking"){let j=(ya=A.turnId)!=null?ya:`agent-think-${A.iteration}`,k=we(j);k.reasoning=(zo=k.reasoning)!=null?zo:{id:j,status:"streaming",chunks:[]},k.reasoning.chunks.push((Wr=A.delta)!=null?Wr:""),k.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},p(k)}else if(A.contentType==="tool_input"){let j=(ba=A.toolCallId)!=null?ba:C.lastId;if(j){let k=W.get(j);k!=null&&k.toolCall&&(k.toolCall.chunks=(bo=k.toolCall.chunks)!=null?bo:[],k.toolCall.chunks.push((Cs=A.delta)!=null?Cs:""),p(k))}}}else if(qe==="agent_turn_complete"){let j=A.turnId;if(j){let ee=S.get(j);if(ee!=null&&ee.reasoning){ee.reasoning.status="complete",ee.reasoning.completedAt=me(A.completedAt);let G=(Rr=ee.reasoning.startedAt)!=null?Rr:Date.now();ee.reasoning.durationMs=Math.max(0,((As=ee.reasoning.completedAt)!=null?As:Date.now())-G),ee.streaming=!1,p(ee)}}let k=A.stopReason,Z=f!=null?f:m;if(k&&Z!==null){let ee=A.turnId;(!ee||((Qr=Z.agentMetadata)==null?void 0:Qr.turnId)===ee)&&(Z.stopReason=k,p(Z))}}else if(qe==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let j=(Yr=A.toolCallId)!=null?Yr:`agent-tool-${l()}`;ke(z(A),j);let k=ge(j),Z=(xa=k.toolCall)!=null?xa:{id:j,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(qi=(va=A.toolName)!=null?va:A.name)!=null?qi:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=me((xo=A.startedAt)!=null?xo:A.timestamp),k.toolCall=Z,k.streaming=!0,k.agentMetadata={executionId:A.executionId,iteration:A.iteration},p(k)}else if(qe==="agent_tool_delta"){let j=(Zr=A.toolCallId)!=null?Zr:C.lastId;if(j){let k=(wa=W.get(j))!=null?wa:ge(j);k.toolCall&&(k.toolCall.chunks=(Ss=k.toolCall.chunks)!=null?Ss:[],k.toolCall.chunks.push((eo=A.delta)!=null?eo:""),k.toolCall.status="running",k.streaming=!0,p(k))}}else if(qe==="agent_tool_complete"){let j=(Ca=A.toolCallId)!=null?Ca:C.lastId;if(j){let k=(Es=W.get(j))!=null?Es:ge(j);if(k.toolCall){k.toolCall.status="complete",A.result!==void 0&&(k.toolCall.result=A.result),typeof A.executionTime=="number"&&(k.toolCall.durationMs=A.executionTime),k.toolCall.completedAt=me((to=A.completedAt)!=null?to:A.timestamp),k.streaming=!1,p(k);let Z=z(A);Z&&C.byCall.delete(Z)}}}else if(qe==="agent_media"){let j=Array.isArray(A.media)?A.media:[],k=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let ee=Z,G=typeof ee.type=="string"?ee.type:void 0,ze=typeof ee.mediaType=="string"?ee.mediaType.toLowerCase():"",Ne=null,it="";if(G==="media"){let Ke=typeof ee.data=="string"?ee.data:void 0;if(!Ke)continue;it=ze.length>0?ze:"application/octet-stream",Ne=`data:${it};base64,${Ke}`}else if(G==="image-url"){let Ke=typeof ee.url=="string"?ee.url:void 0;if(!Ke)continue;it=ze,Ne=Ke}else if(G==="file-url"){let Ke=typeof ee.url=="string"?ee.url:void 0;if(!Ke)continue;it=ze,Ne=Ke}else continue;if(Ne)if(G==="image-url"||it.startsWith("image/"))k.push({type:"image",image:Ne,...it?{mimeType:it}:{}});else if(it.startsWith("audio/"))k.push({type:"audio",audio:Ne,mimeType:it});else if(it.startsWith("video/"))k.push({type:"video",video:Ne,mimeType:it});else{let Ke=it||"application/octet-stream";k.push({type:"file",data:Ne,mimeType:Ke,filename:Ig(Ke)})}}if(k.length>0){let Z=l(),ee=A.toolCallId,ze={id:`agent-media-${typeof ee=="string"&&ee.length>0?`${ee}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(ze);let Ne=f;Ne&&(Ne.streaming=!1,p(Ne)),f=null,v.current=null}}else if(qe!=="agent_iteration_complete"){if(qe==="agent_reflection"||qe==="agent_reflect"){let j=`agent-reflection-${A.executionId}-${A.iteration}`,k={id:j,role:"assistant",content:(Ts=A.reflection)!=null?Ts:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Aa=A.reflection)!=null?Aa:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(k)}else if(qe==="agent_complete"){X&&(X.status=A.success?"complete":"error",X.completedAt=me(A.completedAt),X.stopReason=A.stopReason);let j=f;j&&(j.streaming=!1,p(j)),n({type:"status",status:"idle"})}else if(qe==="agent_error"){let j=typeof A.error=="string"?A.error:(Sa=(Hr=A.error)==null?void 0:Hr.message)!=null?Sa:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):n({type:"error",error:new Error(j)})}else if(qe!=="agent_ping"){if(qe==="agent_approval_start"){let j=(no=A.approvalId)!=null?no:`approval-${l()}`,k={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ht=X==null?void 0:X.agentId)!=null?Ht:"virtual",executionId:(Ko=(Vo=A.executionId)!=null?Vo:X==null?void 0:X.executionId)!=null?Ko:"",toolName:(Ms=A.toolName)!=null?Ms:"",toolType:A.toolType,description:(Ea=A.description)!=null?Ea:`Execute ${(Ar=A.toolName)!=null?Ar:"tool"}`,parameters:A.parameters}};p(k)}else if(qe==="step_await"&&A.awaitReason==="approval_required"){let j=(ks=A.approvalId)!=null?ks:`approval-${l()}`,k={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ls=X==null?void 0:X.agentId)!=null?Ls:"virtual",executionId:(Jo=(Ta=A.executionId)!=null?Ta:X==null?void 0:X.executionId)!=null?Jo:"",toolName:(Go=A.toolName)!=null?Go:"",toolType:A.toolType,description:(Ma=A.description)!=null?Ma:`Execute ${(vo=A.toolName)!=null?vo:"tool"}`,parameters:A.parameters}};p(k)}else if(qe==="agent_approval_complete"){let j=A.approvalId;if(j){let Z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(ka=A.decision)!=null?ka:"approved",agentId:(Ps=X==null?void 0:X.agentId)!=null?Ps:"virtual",executionId:(Ws=(Is=A.executionId)!=null?Is:X==null?void 0:X.executionId)!=null?Ws:"",toolName:(Rs=A.toolName)!=null?Rs:"",description:(Cn=A.description)!=null?Cn:"",resolvedAt:Date.now()}};p(Z)}}else if(qe==="artifact_start"||qe==="artifact_delta"||qe==="artifact_update"||qe==="artifact_complete"){if(qe==="artifact_start"){let j=A.artifactType,k=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:k,artifactType:j,title:Z,component:typeof A.component=="string"?A.component:void 0}),K.set(k,{markdown:"",title:Z}),!Le.has(k)){Le.add(k);let ee={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Z,artifactType:j,status:"streaming"}})};re.set(k,ee),p(ee)}}else if(qe==="artifact_delta"){let j=String(A.id),k=typeof A.delta=="string"?A.delta:String((Kn=A.delta)!=null?Kn:"");n({type:"artifact_delta",id:j,artDelta:k});let Z=K.get(j);Z&&(Z.markdown+=k)}else if(qe==="artifact_update"){let j=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:j,component:typeof A.component=="string"?A.component:void 0})}else if(qe==="artifact_complete"){let j=String(A.id);n({type:"artifact_complete",id:j});let k=re.get(j);if(k){k.streaming=!1;try{let Z=JSON.parse((Br=k.rawContent)!=null?Br:"{}");if(Z.props){Z.props.status="complete";let ee=K.get(j);ee!=null&&ee.markdown&&(Z.props.markdown=ee.markdown)}k.rawContent=JSON.stringify(Z)}catch{}K.delete(j),p(k),re.delete(j)}}}else if(qe==="transcript_insert"){let j=A.message;if(!j||typeof j!="object")continue;let k=String((st=j.id)!=null?st:`msg-${l()}`),Z=j.role,G={id:k,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(p(G),G.rawContent)try{let ze=JSON.parse(G.rawContent),Ne=(Hs=ze==null?void 0:ze.props)==null?void 0:Hs.artifactId;typeof Ne=="string"&&Le.add(Ne)}catch{}f=null,v.current=null,V.delete(k),ne.delete(k)}else if(qe==="error"||qe==="step_error"||qe==="dispatch_error"||qe==="flow_error"){let j=null;if(A.error instanceof Error)j=A.error;else if(qe==="dispatch_error"){let k=(wo=A.message)!=null?wo:A.error;k!=null&&k!==""&&(j=new Error(String(k)))}else if(qe==="step_error"||qe==="flow_error"){let k=A.error;typeof k=="string"&&k!==""?j=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&(j=new Error(String((hr=k.message)!=null?hr:k)))}else qe==="error"&&A.error!=null&&A.error!==""&&(j=new Error(String(A.error)));if(j){n({type:"error",error:j});let k=f;k&&k.streaming&&(k.streaming=!1,p(k)),n({type:"status",status:"idle"})}}}}}Ae.length=0};;){let{done:B,value:se}=await s.read();if(B)break;a+=o.decode(se,{stream:!0});let De=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Io=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},_a=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},$a=()=>{var n;let e=Wg();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)}},ja=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,Or.parse)(t,Or.STR|Or.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Da(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Da(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},ou=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Da(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=(0,Or.parse)(o,Or.STR|Or.OBJ),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},Ua=()=>{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 qa=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Rg="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function Hg(e){var o,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let s=n.indexOf("/");if(s>0){let i=(a=(o=n.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Xi=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 Bg(e){switch(e){case"json":return ja;case"regex-json":return $a;case"xml":return Ua;default:return _a}}var su=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Dg(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=su(t);if(!su(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Io(e);return Io(n)!==null&&a===null?n:e}var Wo=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,s,o;this.apiUrl=(t=n.apiUrl)!=null?t:Rg,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Bg(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders,this.webMcpBridge=((o=n.webmcp)==null?void 0:o.enabled)===!0?new ts(n.webmcp):null}setSSEEventCallback(n){this.onSSEEvent=n}setWebMcpConfirmHandler(n){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(n)}isWebMcpOperational(){var n;return((n=this.webMcpBridge)==null?void 0:n.isOperational())===!0}executeWebMcpToolCall(n,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(n,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${n}`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let W=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:W}),W}let l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([W])=>W!=="sessionId"&&W!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(Xi).map(W=>{var P,w,H;return{id:W.id,role:W.role,content:(H=(w=(P=W.contentParts)!=null?P:W.llmContent)!=null?w:W.rawContent)!=null?H:W.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),x=m?tu(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===x,S=!1,R=null,I;for(let W=0;;W++){let w={...p,...m&&(S||!E)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),I=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:r.signal}),I.status===409&&W===0&&m){let H=await I.json().catch(()=>null);if((H==null?void 0:H.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}R=H!=null?H:{error:"Chat request failed"}}break}if(!I.ok){let W=R!=null?R:await I.json().catch(()=>({error:"Chat request failed"}));if(I.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:w}),w}if(I.status===429){let w=new Error(W.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let P=new Error(W.error||"Failed to send message");throw t({type:"error",error:P}),P}if(!I.body){let W=new Error("No response body received");throw t({type:"error",error:W}),W}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(I.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var l,u;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||za}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:n,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(n){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Xi).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(n){var o;let r={messages:n.slice().filter(Xi).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var Ot,cn,Bn,Yn;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=D=>{let se=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,De=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,Qe=D.tools?D.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...D,reasoning:se,toolCall:De,tools:Qe}},p=D=>{t({type:"message",message:u(D)})},f=null,m=null,x={current:null},v={current:null},E=!1,S=new Map,R=new Map,I=new Map,W=new Map,P={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},H=(D,se,De="")=>`${D}::${se}::${De}`,_=(D,se)=>`${D}::${se}::`,$=(D,se,De,Qe)=>{let _e=H(D,se,De),$e=I.get(_e);if($e)return $e;let ot=De?`-${De}`:"",St={id:`nested-${D}-${se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Qe,parentToolId:D,parentStepId:se}};return I.set(_e,St),p(St),St},N=D=>{if(D==null)return null;try{return String(D)}catch{return null}},U=D=>{var se,De,Qe,_e,$e;return N(($e=(_e=(Qe=(De=(se=D.stepId)!=null?se:D.step_id)!=null?De:D.step)!=null?Qe:D.parentId)!=null?_e:D.flowStepId)!=null?$e:D.flow_step_id)},z=D=>{var se,De,Qe,_e,$e,ot,St;return N((St=(ot=($e=(_e=(Qe=(De=(se=D.callId)!=null?se:D.call_id)!=null?De:D.requestId)!=null?Qe:D.request_id)!=null?_e:D.toolCallId)!=null?$e:D.tool_call_id)!=null?ot:D.stepId)!=null?St:D.step_id)},oe=r,We=!1,He=()=>{if(f)return f;let D;return!We&&oe?(D=oe,We=!0):oe&&v.current?D=`${oe}_${v.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Oe=(D,se)=>{P.lastId=se,D&&P.byStep.set(D,se)},de=(D,se)=>{var $e;let De=($e=D.reasoningId)!=null?$e:D.id,Qe=U(D);if(De){let ot=String(De);return Oe(Qe,ot),ot}if(Qe){let ot=P.byStep.get(Qe);if(ot)return P.lastId=ot,ot}if(P.lastId&&!se)return P.lastId;if(!se)return null;let _e=`reason-${l()}`;return Oe(Qe,_e),_e},we=D=>{let se=S.get(D);if(se)return se;let De={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:D,status:"streaming",chunks:[]}};return S.set(D,De),p(De),De},ke=(D,se)=>{w.lastId=se,D&&w.byCall.set(D,se)},Pe=new Set,re=new Map,Le=new Set,K=new Map,ue=D=>{if(!D)return!1;let se=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return se==="emit_artifact_markdown"||se==="emit_artifact_component"},he=(D,se)=>{var $e;let De=($e=D.toolId)!=null?$e:D.id,Qe=z(D);if(De){let ot=String(De);return ke(Qe,ot),ot}if(Qe){let ot=w.byCall.get(Qe);if(ot)return w.lastId=ot,ot}if(w.lastId&&!se)return w.lastId;if(!se)return null;let _e=`tool-${l()}`;return ke(Qe,_e),_e},ge=D=>{let se=R.get(D);if(se)return se;let De={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:D,status:"pending"}};return R.set(D,De),p(De),De},me=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let se=Number(D);if(!Number.isNaN(se)&&Number.isFinite(se))return se;let De=Date.parse(D);if(!Number.isNaN(De))return De}return Date.now()},Xe=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},V=new Map,ne=new Map,Re=new Map,fe=new Map,le=null,ie=(D,se,De)=>{var St;let Qe=Re.get(D);Qe||(Qe=[],Re.set(D,Qe));let _e=0,$e=Qe.length;for(;_e<$e;){let $t=_e+$e>>>1;Qe[$t].seq<se?_e=$t+1:$e=$t}((St=Qe[_e])==null?void 0:St.seq)===se?Qe[_e]={seq:se,text:De}:Qe.splice(_e,0,{seq:se,text:De});let ot="";for(let $t=0;$t<Qe.length;$t++)ot+=Qe[$t].text;return ot},Ye=(D,se)=>{let De=Xe(se),Qe=ne.get(D.id),_e=Dg(Qe,De);D.rawContent=_e;let $e=V.get(D.id),ot=ft=>{var qt;let rt=(qt=D.content)!=null?qt:"";ft.trim()!==""&&(rt.trim().length===0||ft.startsWith(rt)||ft.trimStart().startsWith(rt.trim()))&&(D.content=ft)},St=()=>{var ft;if($e){let rt=(ft=$e.close)==null?void 0:ft.call($e);rt instanceof Promise&&rt.catch(()=>{})}V.delete(D.id),ne.delete(D.id),D.streaming=!1,p(D)};if(!$e){ot(De),St();return}let $t=Io(_e);if($t!==null&&$t.trim()!==""){ot($t),St();return}let Jt=ft=>{var ae;let rt=typeof ft=="string"?ft:(ae=ft==null?void 0:ft.text)!=null?ae:null;if(rt!==null&&rt.trim()!=="")return rt;let qt=$e.getExtractedText();return qt!==null&&qt.trim()!==""?qt:De},J;try{J=$e.processChunk(_e)}catch{ot(De),St();return}if(J instanceof Promise){J.then(ft=>{ot(Jt(ft)),St()}).catch(()=>{ot(De),St()});return}ot(Jt(J)),St()},Ae=[],pe=!1,Q,je=()=>{pe||(pe=!0,queueMicrotask(()=>{pe=!1,Q()}))},At=new qa((D,se)=>{Ae.push({payloadType:D,payload:se}),je()}),X=null,Fe=new Map,kn=(Ot=this.config.iterationDisplay)!=null?Ot:"separate";for(Q=()=>{var D,se,De,Qe,_e,$e,ot,St,$t,Jt,J,ft,rt,qt,ae,xe,Ct,jt,en,yn,Mt,Tt,bt,xt,zt,tt,Dn,Zn,xn,Nn,mt,vr,On,ho,Ln,Uo,zr,Mr,vt,Fn,_n,vn,It,er,tr,$n,Vr,kr,Kr,jn,Rt,wn,nr,Jr,Lr,Gr,wr,Un,dr,ht,Gt,Xt,qn,Xr,rr,pr,zn,T,Vn,ur,Pr,Cr,xs,mr,gr,fr,Ir,bo,ga,vs,fa,qo,gt,ws,or,Pn,ha,ba,zo,Wr,ya,yo,Cs,Rr,As,Qr,Yr,xa,va,qi,xo,Zr,wa,Ss,eo,Ca,Ts,to,Es,Aa,Hr,Sa,no,Ht,Vo,Ko,Ms,Ar,Ta,ks,Ls,Ea,Jo,Go,vo,Ma,ka,Ps,Is,Ws,Rs,Cn,Kn,Br,st,Hs,wo,hr;for(let Xo=0;Xo<Ae.length;Xo++){let qe=Ae[Xo].payloadType,A=Ae[Xo].payload;if(qe==="reason_start"){let j=(D=de(A,!0))!=null?D:`reason-${l()}`,k=we(j);k.reasoning=(se=k.reasoning)!=null?se:{id:j,status:"streaming",chunks:[]},k.reasoning.startedAt=(Qe=k.reasoning.startedAt)!=null?Qe:me((De=A.startedAt)!=null?De:A.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",p(k)}else if(qe==="reason_delta"||qe==="reason_chunk"){let j=($e=(_e=de(A,!1))!=null?_e:de(A,!0))!=null?$e:`reason-${l()}`,k=we(j);k.reasoning=(ot=k.reasoning)!=null?ot:{id:j,status:"streaming",chunks:[]},k.reasoning.startedAt=($t=k.reasoning.startedAt)!=null?$t:me((St=A.startedAt)!=null?St:A.timestamp);let Z=(ft=(J=(Jt=A.reasoningText)!=null?Jt:A.text)!=null?J:A.delta)!=null?ft:"";if(Z&&A.hidden!==!0){let ee=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ee!==void 0){let G=ie(j,ee,String(Z));k.reasoning.chunks=[G]}else k.reasoning.chunks.push(String(Z))}if(k.reasoning.status=A.done?"complete":"streaming",A.done){k.reasoning.completedAt=me((rt=A.completedAt)!=null?rt:A.timestamp);let ee=(qt=k.reasoning.startedAt)!=null?qt:Date.now();k.reasoning.durationMs=Math.max(0,((ae=k.reasoning.completedAt)!=null?ae:Date.now())-ee)}k.streaming=k.reasoning.status!=="complete",p(k)}else if(qe==="reason_complete"){let j=(Ct=(xe=de(A,!1))!=null?xe:de(A,!0))!=null?Ct:`reason-${l()}`,k=S.get(j);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=me((jt=A.completedAt)!=null?jt:A.timestamp);let ee=(en=k.reasoning.startedAt)!=null?en:Date.now();k.reasoning.durationMs=Math.max(0,((yn=k.reasoning.completedAt)!=null?yn:Date.now())-ee),k.streaming=!1,p(k)}let Z=U(A);Z&&P.byStep.delete(Z)}else if(qe==="tool_start"){let j=(Mt=he(A,!0))!=null?Mt:`tool-${l()}`,k=(Tt=A.toolName)!=null?Tt:A.name;if(ue(k)){Pe.add(j);continue}let Z=ge(j),ee=(bt=Z.toolCall)!=null?bt:{id:j,status:"pending"};ee.name=k!=null?k:ee.name,ee.status="running",A.args!==void 0?ee.args=A.args:A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=(zt=ee.startedAt)!=null?zt:me((xt=A.startedAt)!=null?xt:A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,Z.toolCall=ee,Z.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(Z.agentMetadata={executionId:(tt=G==null?void 0:G.executionId)!=null?tt:A.executionId,iteration:(Dn=G==null?void 0:G.iteration)!=null?Dn:A.iteration}),p(Z)}else if(qe==="tool_chunk"||qe==="tool_delta"){let j=(xn=(Zn=he(A,!1))!=null?Zn:he(A,!0))!=null?xn:`tool-${l()}`;if(Pe.has(j))continue;let k=ge(j),Z=(Nn=k.toolCall)!=null?Nn:{id:j,status:"running"};Z.startedAt=(vr=Z.startedAt)!=null?vr:me((mt=A.startedAt)!=null?mt:A.timestamp);let ee=(Ln=(ho=(On=A.text)!=null?On:A.delta)!=null?ho:A.message)!=null?Ln:"";ee&&(Z.chunks=(Uo=Z.chunks)!=null?Uo:[],Z.chunks.push(String(ee))),Z.status="running",k.toolCall=Z,k.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(k.agentMetadata=(vt=k.agentMetadata)!=null?vt:{executionId:(zr=G==null?void 0:G.executionId)!=null?zr:A.executionId,iteration:(Mr=G==null?void 0:G.iteration)!=null?Mr:A.iteration}),p(k)}else if(qe==="tool_complete"){let j=(_n=(Fn=he(A,!1))!=null?Fn:he(A,!0))!=null?_n:`tool-${l()}`;if(Pe.has(j)){Pe.delete(j);continue}let k=ge(j),Z=(vn=k.toolCall)!=null?vn:{id:j,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=me((It=A.completedAt)!=null?It:A.timestamp);let ee=(er=A.duration)!=null?er:A.executionTime;if(typeof ee=="number")Z.durationMs=ee;else{let Ne=(tr=Z.startedAt)!=null?tr:Date.now();Z.durationMs=Math.max(0,(($n=Z.completedAt)!=null?$n:Date.now())-Ne)}k.toolCall=Z,k.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(k.agentMetadata=(Kr=k.agentMetadata)!=null?Kr:{executionId:(Vr=G==null?void 0:G.executionId)!=null?Vr:A.executionId,iteration:(kr=G==null?void 0:G.iteration)!=null?kr:A.iteration}),p(k);let ze=z(A);ze&&w.byCall.delete(ze)}else if(qe==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let j=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,k=(jn=j!=null?j:A.toolId)!=null?jn:`local-${l()}`,Z=ge(k),ee=(Rt=Z.toolCall)!=null?Rt:{id:k,status:"pending"};ee.name=A.toolName,ee.args=A.parameters,ee.status="complete",ee.chunks=(wn=ee.chunks)!=null?wn:[],ee.startedAt=(Jr=ee.startedAt)!=null?Jr:me((nr=A.startedAt)!=null?nr:A.timestamp),ee.completedAt=(Lr=ee.completedAt)!=null?Lr:ee.startedAt,Z.toolCall=ee,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(wr=A.executionId)!=null?wr:(Gr=Z.agentMetadata)==null?void 0:Gr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},p(Z)}else if(qe==="text_start"){if((Un=A.toolContext)!=null&&Un.toolId)continue;let j=A.partId;if(j!==void 0&&v.current!==null&&j!==v.current){let k=f;k&&(k.streaming=!1,p(k),le=k,f=null,E=!0)}j!==void 0&&(v.current=j)}else if(qe==="text_end"){if((dr=A.toolContext)!=null&&dr.toolId)continue;let j=f;j&&(j.streaming=!1,p(j),le=j,f=null,E=!0)}else if(qe==="step_chunk"||qe==="step_delta"){let j=A.stepType,k=A.executionType;if(j==="tool"||k==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Gt=(ht=A.id)!=null?ht:Z.stepId)!=null?Gt:`step-${l()}`),it=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ke=`${Z.toolId}::${Ne}`,Je=W.get(Ke);if(it!==""&&Je!==void 0&&Je!==""&&Je!==it){let Et=I.get(H(Z.toolId,Ne,Je));Et&&Et.streaming!==!1&&(Et.streaming=!1,p(Et))}it!==""&&W.set(Ke,it);let Ze=$(Z.toolId,Ne,it,Z.executionId),Qt=(rr=(Xr=(qn=(Xt=A.text)!=null?Xt:A.delta)!=null?qn:A.content)!=null?Xr:A.chunk)!=null?rr:"";Qt&&(Ze.content+=String(Qt),Ze.streaming=!0,p(Ze)),A.isComplete&&(Ze.streaming=!1,p(Ze));continue}let ee=A.partId;if(ee!==void 0&&v.current!==null&&ee!==v.current){let Ne=f;Ne&&(Ne.streaming=!1,p(Ne),le=Ne,f=null,E=!0)}ee!==void 0&&(v.current=ee);let G=ee!==void 0&&(pr=fe.get(ee))!=null?pr:He();ee!==void 0&&(G.partId||(G.partId=ee),fe.set(ee,G));let ze=(ur=(Vn=(T=(zn=A.text)!=null?zn:A.delta)!=null?T:A.content)!=null?Vn:A.chunk)!=null?ur:"";if(ze){let Ne=typeof A.seq=="number"?A.seq:void 0,it=ee!=null?ee:G.id,Ke=Ne!==void 0?ie(it,Ne,String(ze)):((Pr=ne.get(G.id))!=null?Pr:"")+ze;G.rawContent=Ke,V.has(G.id)||V.set(G.id,this.createStreamParser());let Je=V.get(G.id),Ze=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(Ze&&ne.set(G.id,Ke),Je.__isPlainTextParser===!0){G.content=Ne!==void 0?Ke:G.content+ze,ne.delete(G.id),V.delete(G.id),G.rawContent=void 0,p(G);continue}let Et=Je.processChunk(Ke);if(Et instanceof Promise)Et.then(Lt=>{var mn;let sn=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(sn!==null&&sn.trim()!=="")G.content=sn,p(G);else if(!Ze&&!Ke.trim().startsWith("<")){let dn=f,tn=dn&&dn.id===G.id?dn:G;tn.id===G.id&&(tn.content=Ne!==void 0?Ke:tn.content+ze,ne.delete(tn.id),V.delete(tn.id),tn.rawContent=void 0,p(tn))}}).catch(()=>{G.content=Ne!==void 0?Ke:G.content+ze,ne.delete(G.id),V.delete(G.id),G.rawContent=void 0,p(G)});else{let Lt=typeof Et=="string"?Et:(Cr=Et==null?void 0:Et.text)!=null?Cr:null;Lt!==null&&Lt.trim()!==""?(G.content=Lt,p(G)):!Ze&&!Ke.trim().startsWith("<")&&(G.content=Ne!==void 0?Ke:G.content+ze,ne.delete(G.id),V.delete(G.id),G.rawContent=void 0,p(G))}}if(A.isComplete){let Ne=(mr=(xs=A.result)==null?void 0:xs.response)!=null?mr:G.content;if(Ne){let it=ne.get(G.id),Ke=it!=null?it:Xe(Ne);G.rawContent=Ke;let Je=V.get(G.id),Ze=null,Qt=!1;if(Je&&(Ze=Je.getExtractedText(),Ze===null&&(Ze=Io(Ke)),Ze===null)){let Et=Je.processChunk(Ke);Et instanceof Promise?(Qt=!0,Et.then(Lt=>{var mn;let sn=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(sn!==null){let dn=f;dn&&dn.id===G.id&&(dn.content=sn,dn.streaming=!1,V.delete(dn.id),ne.delete(dn.id),p(dn))}})):Ze=typeof Et=="string"?Et:(gr=Et==null?void 0:Et.text)!=null?gr:null}if(!Qt){Ze!==null&&Ze.trim()!==""?G.content=Ze:ne.has(G.id)||(G.content=Xe(Ne));let Et=V.get(G.id);if(Et){let Lt=(fr=Et.close)==null?void 0:fr.call(Et);Lt instanceof Promise&&Lt.catch(()=>{}),V.delete(G.id)}ne.delete(G.id),G.streaming=!1,p(G)}}}}else if(qe==="step_complete"){let j=A.stepType,k=A.executionType;if(j==="tool"||k==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((bo=(Ir=A.id)!=null?Ir:Z.stepId)!=null?bo:"");if(Ne){let it=_(Z.toolId,Ne);for(let[Ke,Je]of I)Ke.startsWith(it)&&Je.streaming!==!1&&(Je.streaming=!1,p(Je));W.delete(`${Z.toolId}::${Ne}`)}continue}let ee=A.stopReason;if(E){if(f!==null){let Ke=f;ee&&(Ke.stopReason=ee),V.delete(Ke.id),ne.delete(Ke.id),Ke.streaming!==!1&&(Ke.streaming=!1,p(Ke))}let Ne=(ga=A.result)==null?void 0:ga.response,it=le;it&&(ee&&(it.stopReason=ee),Ne!=null?Ye(it,Ne):(V.delete(it.id),ne.delete(it.id))),le=null;continue}let G=(vs=A.result)==null?void 0:vs.response,ze=He();if(ee&&(ze.stopReason=ee),G!=null){let Ne=V.get(ze.id),it=!1,Ke=!1;if(Ne){let Je=Ne.getExtractedText(),Ze=ne.get(ze.id),Qt=Ze!=null?Ze:Xe(G);if(ze.rawContent=Qt,Je!==null&&Je.trim()!=="")ze.content=Je,it=!0;else{let Et=Io(Qt);if(Et!==null)ze.content=Et,it=!0;else{let Lt=Ne.processChunk(Qt);if(Lt instanceof Promise)Ke=!0,Lt.then(sn=>{var dn;let mn=typeof sn=="string"?sn:(dn=sn==null?void 0:sn.text)!=null?dn:null;if(mn!==null&&mn.trim()!==""){let tn=f;tn&&tn.id===ze.id&&(tn.content=mn,tn.streaming=!1,V.delete(tn.id),ne.delete(tn.id),p(tn))}else{let tn=Ne.getExtractedText(),sr=f;sr&&sr.id===ze.id&&(tn!==null&&tn.trim()!==""?sr.content=tn:ne.has(sr.id)||(sr.content=Xe(G)),sr.streaming=!1,V.delete(sr.id),ne.delete(sr.id),p(sr))}});else{let sn=typeof Lt=="string"?Lt:(fa=Lt==null?void 0:Lt.text)!=null?fa:null;if(sn!==null&&sn.trim()!=="")ze.content=sn,it=!0;else{let mn=Ne.getExtractedText();mn!==null&&mn.trim()!==""&&(ze.content=mn,it=!0)}}}}}if(!Ke){if(!ze.rawContent){let Je=ne.get(ze.id);ze.rawContent=Je!=null?Je:Xe(G)}if(!it&&!ne.has(ze.id)&&(ze.content=Xe(G)),Ne){let Je=(qo=Ne.close)==null?void 0:qo.call(Ne);Je instanceof Promise&&Je.catch(()=>{})}V.delete(ze.id),ne.delete(ze.id),ze.streaming=!1,p(ze)}}else V.delete(ze.id),ne.delete(ze.id),ze.streaming=!1,p(ze)}else if(qe==="flow_complete"){let j=(gt=A.result)==null?void 0:gt.response;if(E){if(f!==null){let k=f;V.delete(k.id),ne.delete(k.id),k.streaming!==!1&&(k.streaming=!1,p(k))}}else if(j!=null){let k=He(),Z=ne.get(k.id),ee=Z!=null?Z:Xe(j);k.rawContent=ee;let G=Xe(j),ze=V.get(k.id);if(ze){let Ke=Io(ee);if(Ke!==null)G=Ke;else{let Je=ze.processChunk(ee);Je instanceof Promise&&Je.then(Qt=>{var Lt;let Et=typeof Qt=="string"?Qt:(Lt=Qt==null?void 0:Qt.text)!=null?Lt:null;Et!==null&&(k.content=Et,k.streaming=!1,p(k))});let Ze=ze.getExtractedText();Ze!==null&&(G=Ze)}}V.delete(k.id),ne.delete(k.id);let Ne=G!==k.content,it=k.streaming!==!1;Ne&&(k.content=G),k.streaming=!1,(Ne||it)&&p(k)}else if(f!==null){let k=f;V.delete(k.id),ne.delete(k.id),k.streaming!==!1&&(k.streaming=!1,p(k))}t({type:"status",status:"idle"})}else if(qe==="agent_start")X={executionId:A.executionId,agentId:(ws=A.agentId)!=null?ws:"virtual",agentName:(or=A.agentName)!=null?or:"",status:"running",currentIteration:0,maxTurns:(Pn=A.maxTurns)!=null?Pn:1,startedAt:me(A.startedAt)};else if(qe==="agent_iteration_start"){if(X&&(X.currentIteration=A.iteration),kn==="separate"&&A.iteration>1){let j=f;j&&(j.streaming=!1,p(j),Fe.set(A.iteration-1,j),f=null)}}else if(qe==="agent_turn_start")m=null;else if(qe==="agent_turn_delta"){if(A.contentType==="text"){let j=He();j.content+=(ha=A.delta)!=null?ha:"",j.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:X==null?void 0:X.agentName},m=j,p(j)}else if(A.contentType==="thinking"){let j=(ba=A.turnId)!=null?ba:`agent-think-${A.iteration}`,k=we(j);k.reasoning=(zo=k.reasoning)!=null?zo:{id:j,status:"streaming",chunks:[]},k.reasoning.chunks.push((Wr=A.delta)!=null?Wr:""),k.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},p(k)}else if(A.contentType==="tool_input"){let j=(ya=A.toolCallId)!=null?ya:w.lastId;if(j){let k=R.get(j);k!=null&&k.toolCall&&(k.toolCall.chunks=(yo=k.toolCall.chunks)!=null?yo:[],k.toolCall.chunks.push((Cs=A.delta)!=null?Cs:""),p(k))}}}else if(qe==="agent_turn_complete"){let j=A.turnId;if(j){let ee=S.get(j);if(ee!=null&&ee.reasoning){ee.reasoning.status="complete",ee.reasoning.completedAt=me(A.completedAt);let G=(Rr=ee.reasoning.startedAt)!=null?Rr:Date.now();ee.reasoning.durationMs=Math.max(0,((As=ee.reasoning.completedAt)!=null?As:Date.now())-G),ee.streaming=!1,p(ee)}}let k=A.stopReason,Z=f!=null?f:m;if(k&&Z!==null){let ee=A.turnId;(!ee||((Qr=Z.agentMetadata)==null?void 0:Qr.turnId)===ee)&&(Z.stopReason=k,p(Z))}}else if(qe==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let j=(Yr=A.toolCallId)!=null?Yr:`agent-tool-${l()}`;ke(z(A),j);let k=ge(j),Z=(xa=k.toolCall)!=null?xa:{id:j,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(qi=(va=A.toolName)!=null?va:A.name)!=null?qi:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=me((xo=A.startedAt)!=null?xo:A.timestamp),k.toolCall=Z,k.streaming=!0,k.agentMetadata={executionId:A.executionId,iteration:A.iteration},p(k)}else if(qe==="agent_tool_delta"){let j=(Zr=A.toolCallId)!=null?Zr:w.lastId;if(j){let k=(wa=R.get(j))!=null?wa:ge(j);k.toolCall&&(k.toolCall.chunks=(Ss=k.toolCall.chunks)!=null?Ss:[],k.toolCall.chunks.push((eo=A.delta)!=null?eo:""),k.toolCall.status="running",k.streaming=!0,p(k))}}else if(qe==="agent_tool_complete"){let j=(Ca=A.toolCallId)!=null?Ca:w.lastId;if(j){let k=(Ts=R.get(j))!=null?Ts:ge(j);if(k.toolCall){k.toolCall.status="complete",A.result!==void 0&&(k.toolCall.result=A.result),typeof A.executionTime=="number"&&(k.toolCall.durationMs=A.executionTime),k.toolCall.completedAt=me((to=A.completedAt)!=null?to:A.timestamp),k.streaming=!1,p(k);let Z=z(A);Z&&w.byCall.delete(Z)}}}else if(qe==="agent_media"){let j=Array.isArray(A.media)?A.media:[],k=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let ee=Z,G=typeof ee.type=="string"?ee.type:void 0,ze=typeof ee.mediaType=="string"?ee.mediaType.toLowerCase():"",Ne=null,it="";if(G==="media"){let Ke=typeof ee.data=="string"?ee.data:void 0;if(!Ke)continue;it=ze.length>0?ze:"application/octet-stream",Ne=`data:${it};base64,${Ke}`}else if(G==="image-url"){let Ke=typeof ee.url=="string"?ee.url:void 0;if(!Ke)continue;it=ze,Ne=Ke}else if(G==="file-url"){let Ke=typeof ee.url=="string"?ee.url:void 0;if(!Ke)continue;it=ze,Ne=Ke}else continue;if(Ne)if(G==="image-url"||it.startsWith("image/"))k.push({type:"image",image:Ne,...it?{mimeType:it}:{}});else if(it.startsWith("audio/"))k.push({type:"audio",audio:Ne,mimeType:it});else if(it.startsWith("video/"))k.push({type:"video",video:Ne,mimeType:it});else{let Ke=it||"application/octet-stream";k.push({type:"file",data:Ne,mimeType:Ke,filename:Hg(Ke)})}}if(k.length>0){let Z=l(),ee=A.toolCallId,ze={id:`agent-media-${typeof ee=="string"&&ee.length>0?`${ee}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(ze);let Ne=f;Ne&&(Ne.streaming=!1,p(Ne)),f=null,x.current=null}}else if(qe!=="agent_iteration_complete"){if(qe==="agent_reflection"||qe==="agent_reflect"){let j=`agent-reflection-${A.executionId}-${A.iteration}`,k={id:j,role:"assistant",content:(Es=A.reflection)!=null?Es:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Aa=A.reflection)!=null?Aa:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(k)}else if(qe==="agent_complete"){X&&(X.status=A.success?"complete":"error",X.completedAt=me(A.completedAt),X.stopReason=A.stopReason);let j=f;j&&(j.streaming=!1,p(j)),t({type:"status",status:"idle"})}else if(qe==="agent_error"){let j=typeof A.error=="string"?A.error:(Sa=(Hr=A.error)==null?void 0:Hr.message)!=null?Sa:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):t({type:"error",error:new Error(j)})}else if(qe!=="agent_ping"){if(qe==="agent_approval_start"){let j=(no=A.approvalId)!=null?no:`approval-${l()}`,k={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ht=X==null?void 0:X.agentId)!=null?Ht:"virtual",executionId:(Ko=(Vo=A.executionId)!=null?Vo:X==null?void 0:X.executionId)!=null?Ko:"",toolName:(Ms=A.toolName)!=null?Ms:"",toolType:A.toolType,description:(Ta=A.description)!=null?Ta:`Execute ${(Ar=A.toolName)!=null?Ar:"tool"}`,parameters:A.parameters}};p(k)}else if(qe==="step_await"&&A.awaitReason==="approval_required"){let j=(ks=A.approvalId)!=null?ks:`approval-${l()}`,k={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ls=X==null?void 0:X.agentId)!=null?Ls:"virtual",executionId:(Jo=(Ea=A.executionId)!=null?Ea:X==null?void 0:X.executionId)!=null?Jo:"",toolName:(Go=A.toolName)!=null?Go:"",toolType:A.toolType,description:(Ma=A.description)!=null?Ma:`Execute ${(vo=A.toolName)!=null?vo:"tool"}`,parameters:A.parameters}};p(k)}else if(qe==="agent_approval_complete"){let j=A.approvalId;if(j){let Z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(ka=A.decision)!=null?ka:"approved",agentId:(Ps=X==null?void 0:X.agentId)!=null?Ps:"virtual",executionId:(Ws=(Is=A.executionId)!=null?Is:X==null?void 0:X.executionId)!=null?Ws:"",toolName:(Rs=A.toolName)!=null?Rs:"",description:(Cn=A.description)!=null?Cn:"",resolvedAt:Date.now()}};p(Z)}}else if(qe==="artifact_start"||qe==="artifact_delta"||qe==="artifact_update"||qe==="artifact_complete"){if(qe==="artifact_start"){let j=A.artifactType,k=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(t({type:"artifact_start",id:k,artifactType:j,title:Z,component:typeof A.component=="string"?A.component:void 0}),K.set(k,{markdown:"",title:Z}),!Le.has(k)){Le.add(k);let ee={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Z,artifactType:j,status:"streaming"}})};re.set(k,ee),p(ee)}}else if(qe==="artifact_delta"){let j=String(A.id),k=typeof A.delta=="string"?A.delta:String((Kn=A.delta)!=null?Kn:"");t({type:"artifact_delta",id:j,artDelta:k});let Z=K.get(j);Z&&(Z.markdown+=k)}else if(qe==="artifact_update"){let j=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};t({type:"artifact_update",id:String(A.id),props:j,component:typeof A.component=="string"?A.component:void 0})}else if(qe==="artifact_complete"){let j=String(A.id);t({type:"artifact_complete",id:j});let k=re.get(j);if(k){k.streaming=!1;try{let Z=JSON.parse((Br=k.rawContent)!=null?Br:"{}");if(Z.props){Z.props.status="complete";let ee=K.get(j);ee!=null&&ee.markdown&&(Z.props.markdown=ee.markdown)}k.rawContent=JSON.stringify(Z)}catch{}K.delete(j),p(k),re.delete(j)}}}else if(qe==="transcript_insert"){let j=A.message;if(!j||typeof j!="object")continue;let k=String((st=j.id)!=null?st:`msg-${l()}`),Z=j.role,G={id:k,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(p(G),G.rawContent)try{let ze=JSON.parse(G.rawContent),Ne=(Hs=ze==null?void 0:ze.props)==null?void 0:Hs.artifactId;typeof Ne=="string"&&Le.add(Ne)}catch{}f=null,x.current=null,V.delete(k),ne.delete(k)}else if(qe==="error"||qe==="step_error"||qe==="dispatch_error"||qe==="flow_error"){let j=null;if(A.error instanceof Error)j=A.error;else if(qe==="dispatch_error"){let k=(wo=A.message)!=null?wo:A.error;k!=null&&k!==""&&(j=new Error(String(k)))}else if(qe==="step_error"||qe==="flow_error"){let k=A.error;typeof k=="string"&&k!==""?j=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&(j=new Error(String((hr=k.message)!=null?hr:k)))}else qe==="error"&&A.error!=null&&A.error!==""&&(j=new Error(String(A.error)));if(j){t({type:"error",error:j});let k=f;k&&k.streaming&&(k.streaming=!1,p(k)),t({type:"status",status:"idle"})}}}}}Ae.length=0};;){let{done:D,value:se}=await s.read();if(D)break;a+=o.decode(se,{stream:!0});let De=a.split(`
10
10
 
11
11
  `);a=(cn=De.pop())!=null?cn:"";for(let Qe of De){let _e=Qe.split(`
12
- `),$e="message",ot="";for(let Jt of _e)Jt.startsWith("event:")?$e=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(ot+=Jt.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(Jt){n({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let $t=$e!=="message"?$e:(Bn=St.type)!=null?Bn:"message";if((Yn=this.onSSEEvent)==null||Yn.call(this,$t,St),this.parseSSEEvent){v.current=f;let Jt=await this.handleCustomSSEEvent(St,n,v,p,l,x);if(v.current&&v.current!==f&&(f=v.current),Jt)continue}At.push($t,St),Q()}}At.flushPending(),Q(),At.destroy()}};function ou(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function rs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ro(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function su(e){return typeof e=="string"?[{type:"text",text:e}]:e}function au(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function iu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function lu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function qs(e){return{type:"text",text:e}}function cu(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function du(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function pu(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var uu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Hg=["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"],Fr=[...uu,...Hg];function Bg(e){return uu.includes(e)||e.startsWith("image/")}function Ka(e){return Bg(e.type)}async function mu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ka(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function gu(e,t=Fr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Dg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function fu(e,t){let n=Dg(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ja=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ga=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var zs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ga;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,x=S=>{v||(v=!0,clearTimeout(T),m(new Error(S)))},T=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(T),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!v){let W=S.code!==1006?` (code ${S.code})`:"";x("WebSocket connection failed"+W+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ja(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ho=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Bo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new zs(e.runtype);case"browser":if(!Ho.isSupported())throw new Error("Browser speech recognition not supported");return new Ho(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Xa(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Bo({type:"runtype",runtype:e.runtype});if(Ho.isSupported())return Bo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vs(e){try{return Xa(e),!0}catch{return!1}}function hu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
12
+ `),$e="message",ot="";for(let Jt of _e)Jt.startsWith("event:")?$e=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(ot+=Jt.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(Jt){t({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let $t=$e!=="message"?$e:(Bn=St.type)!=null?Bn:"message";if((Yn=this.onSSEEvent)==null||Yn.call(this,$t,St),this.parseSSEEvent){x.current=f;let Jt=await this.handleCustomSSEEvent(St,t,x,p,l,v);if(x.current&&x.current!==f&&(f=x.current),Jt)continue}At.push($t,St),Q()}}At.flushPending(),Q(),At.destroy()}};function au(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function rs(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function Ro(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Va="[Image]";function iu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function lu(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function cu(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function du(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function qs(e){return{type:"text",text:e}}function pu(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 uu(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function mu(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 gu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ng=["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"],Fr=[...gu,...Ng];function Og(e){return gu.includes(e)||e.startsWith("image/")}function Ka(e){return Og(e.type)}async function fu(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ka(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function hu(e,n=Fr,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 Fg(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function bu(e,n){let t=Fg(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 Ja=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ga=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var zs=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 Ga;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let x=!1,v=S=>{x||(x=!0,clearTimeout(E),m(new Error(S)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!x){let R=S.code!==1006?` (code ${S.code})`:"";v("WebSocket connection failed"+R+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ja(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ho=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Bo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new zs(e.runtype);case"browser":if(!Ho.isSupported())throw new Error("Browser speech recognition not supported");return new Ho(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Xa(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Bo({type:"runtype",runtype:e.runtype});if(Ho.isSupported())return Bo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vs(e){try{return Xa(e),!0}catch{return!1}}function yu(e,n){let t=e instanceof Error?e:new Error(String(e));if(typeof n=="string")return n;if(typeof n=="function")return n(t);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${r}
13
13
 
14
- _Details: ${n.message}_`:r}var os=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(u!=null&&u.name)&&$s(u.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Wo(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Vs((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Bo(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,m,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let T=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:v.id;T&&this.ttsSpokenMessageIds.add(T)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Wo(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=t,m={id:a!=null?a:n==="user"?rs():n==="assistant"?Ro():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:s==="user"?rs():s==="assistant"?Ro():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,u,p,f,m;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=rs(),o=Ro(),a={id:s,role:"user",content:r||Va,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let T=hu(v,this.config.errorMessage);if(T){let S={id:o,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(S)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Ro();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=hu(l,this.config.errorMessage);if(p){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n){var d,l,u,p;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):f=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let m=null;if(f instanceof Response){if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${f.status}`)}m=f.body}else f instanceof ReadableStream&&(m=f);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let m=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var u,p,f,m,v,x,T,S,W,I,O,P;let r=this.messages.find(C=>C.id===t.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=t.agentMetadata)==null?void 0:p.executionId,o=(f=t.toolCall)==null?void 0:f.name;if(!s||!o){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(x=t.toolCall)==null?void 0:x.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let _=typeof((T=R[0])==null?void 0:T.question)=="string"?R[0].question:"";_&&(a={[_]:n})}}this.markAskUserQuestionResolved(t,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(W=t.toolCall)==null?void 0:W.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,_])=>`${R}: ${Array.isArray(_)?_.join(", "):_}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};l.forEach((R,_)=>{let $=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!$)return;let D=C[$],U=Array.isArray(D)?D.join(", "):typeof D=="string"?D:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(s,{[o]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((I=R==null?void 0:R.error)!=null?I:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(P=(O=this.callbacks).onError)==null||P.call(O,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var W,I,O,P,C,R,_;let p=(W=u.toolCall)==null?void 0:W.name,f=(I=u.toolCall)==null?void 0:I.id;if(!p||!f)return null;let m=`${t}:${f}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),r.push(m),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(P=(O=u.agentMetadata)==null?void 0:O.webMcpToolCallId)!=null?P:p,T=this.client.executeWebMcpToolCall(p,(C=u.toolCall)==null?void 0:C.args,v.signal),S;if(!T)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await T}catch($){return $ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"))||(_=(R=this.callbacks).onError)==null||_.call(R,$ instanceof Error?$:new Error(String($))),this.webMcpInflightKeys.delete(m),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:x,output:S}}));try{let u=a.filter(m=>m!==null);if(u.length===0)return;let p={};for(let m of u)p[m.resumeKey]=m.output;let f=await this.client.resumeFlow(t,p,{signal:o.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${f.status}`)}for(let m of u)this.webMcpResolvedKeys.add(m.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of s)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,p,f,m,v,x,T,S,W,I,O,P;let n=(u=t.agentMetadata)==null?void 0:u.executionId,r=(p=t.toolCall)==null?void 0:p.name,s=(f=t.toolCall)==null?void 0:f.id;if(!n){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let C=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return;this.webMcpInflightKeys.add(C);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(C)}catch(R){(T=(x=this.callbacks).onError)==null||T.call(x,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(C)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(S=t.toolCall)==null?void 0:S.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let C;if(l?C=await l:C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let R=(I=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?I:r;await this.resumeWithToolOutput(n,R,C,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(C){C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"))||(P=(O=this.callbacks).onError)==null||P.call(O,C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var u,p,f,m,v,x;if(o!==r)return s;let a={...s,...n};((u=s.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(m=n.toolCall)==null?void 0:m.id;if(i&&$s(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let T=`${d}:${l}`;(this.webMcpInflightKeys.has(T)||this.webMcpResolvedKeys.has(T))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Er=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var w=require("lucide"),Ng={activity:w.Activity,"arrow-down":w.ArrowDown,"arrow-up":w.ArrowUp,"arrow-up-right":w.ArrowUpRight,bot:w.Bot,"chevron-down":w.ChevronDown,"chevron-up":w.ChevronUp,"chevron-right":w.ChevronRight,"chevron-left":w.ChevronLeft,check:w.Check,clipboard:w.Clipboard,"clipboard-copy":w.ClipboardCopy,copy:w.Copy,file:w.File,"file-code":w.FileCode,"file-spreadsheet":w.FileSpreadsheet,"file-text":w.FileText,"image-plus":w.ImagePlus,loader:w.Loader,"loader-circle":w.LoaderCircle,mic:w.Mic,paperclip:w.Paperclip,"refresh-cw":w.RefreshCw,search:w.Search,send:w.Send,"shield-alert":w.ShieldAlert,"shield-check":w.ShieldCheck,"shield-x":w.ShieldX,square:w.Square,"thumbs-down":w.ThumbsDown,"thumbs-up":w.ThumbsUp,upload:w.Upload,"volume-2":w.Volume2,x:w.X,user:w.User,mail:w.Mail,phone:w.Phone,calendar:w.Calendar,clock:w.Clock,building:w.Building,"map-pin":w.MapPin,lock:w.Lock,key:w.Key,"credit-card":w.CreditCard,"at-sign":w.AtSign,hash:w.Hash,globe:w.Globe,link:w.Link,"circle-check":w.CircleCheck,"circle-x":w.CircleX,"triangle-alert":w.TriangleAlert,info:w.Info,ban:w.Ban,shield:w.Shield,"arrow-left":w.ArrowLeft,"arrow-right":w.ArrowRight,"external-link":w.ExternalLink,ellipsis:w.Ellipsis,"ellipsis-vertical":w.EllipsisVertical,menu:w.Menu,house:w.House,plus:w.Plus,minus:w.Minus,pencil:w.Pencil,trash:w.Trash,"trash-2":w.Trash2,save:w.Save,download:w.Download,share:w.Share,funnel:w.Funnel,settings:w.Settings,"rotate-cw":w.RotateCw,maximize:w.Maximize,minimize:w.Minimize,"shopping-cart":w.ShoppingCart,"shopping-bag":w.ShoppingBag,package:w.Package,truck:w.Truck,tag:w.Tag,gift:w.Gift,receipt:w.Receipt,wallet:w.Wallet,store:w.Store,"dollar-sign":w.DollarSign,percent:w.Percent,play:w.Play,pause:w.Pause,"volume-x":w.VolumeX,camera:w.Camera,image:w.Image,film:w.Film,headphones:w.Headphones,"message-circle":w.MessageCircle,"message-square":w.MessageSquare,bell:w.Bell,heart:w.Heart,star:w.Star,eye:w.Eye,"eye-off":w.EyeOff,bookmark:w.Bookmark,"calendar-days":w.CalendarDays,history:w.History,timer:w.Timer,folder:w.Folder,"folder-open":w.FolderOpen,files:w.Files,sparkles:w.Sparkles,zap:w.Zap,sun:w.Sun,moon:w.Moon,flag:w.Flag,monitor:w.Monitor,smartphone:w.Smartphone},be=(e,t=24,n="currentColor",r=2)=>{let s=Ng[e];return s?Og(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Og(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var Qa={allowedTypes:Fr,maxFileSize:10*1024*1024,maxFiles:4};function Fg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function _g(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 Do=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Qa.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Qa.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Qa.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Qa.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let u=gu(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await mu(l),f=Ka(l)?URL.createObjectURL(l):null,m={id:Fg(),file:l,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ka(t.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=_g(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=fu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=be("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var yu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ks(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];yu(o)&&yu(s)?n[r]=Ks(o,s):n[r]=s}return n}var Xn="min(440px, calc(100vw - 24px))",Ya="440px",Nt={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:Xn,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 bu(e,t){if(!(!e&&!t))return e?t?Ks(e,t):e:t}function Za(e){var t,n,r,s,o,a,i,d,l,u,p,f,m,v,x,T,S,W,I,O,P;return e?{...Nt,...e,theme:bu(Nt.theme,e.theme),darkTheme:bu(Nt.darkTheme,e.darkTheme),launcher:{...Nt.launcher,...e.launcher,dock:{...(t=Nt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Nt.copy,...e.copy},sendButton:{...Nt.sendButton,...e.sendButton},statusIndicator:{...Nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...e.voiceRecognition},features:(()=>{var we,ke,Pe,re,Le,K,ue,he;let C=(we=Nt.features)==null?void 0:we.artifacts,R=(ke=e.features)==null?void 0:ke.artifacts,_=(Pe=Nt.features)==null?void 0:Pe.scrollToBottom,$=(re=e.features)==null?void 0:re.scrollToBottom,D=(Le=Nt.features)==null?void 0:Le.streamAnimation,U=(K=e.features)==null?void 0:K.streamAnimation,z=(ue=Nt.features)==null?void 0:ue.askUserQuestion,oe=(he=e.features)==null?void 0:he.askUserQuestion,We=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},He=_===void 0&&$===void 0?void 0:{..._,...$},Oe=D===void 0&&U===void 0?void 0:{...D,...U},de=z===void 0&&oe===void 0?void 0:{...z,...oe,styles:{...z==null?void 0:z.styles,...oe==null?void 0:oe.styles}};return{...Nt.features,...e.features,...He!==void 0?{scrollToBottom:He}:{},...We!==void 0?{artifacts:We}:{},...Oe!==void 0?{streamAnimation:Oe}:{},...de!==void 0?{askUserQuestion:de}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Nt.layout,...e.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Nt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(S=(T=e.layout)==null?void 0:T.messages)==null?void 0:S.timestamp}},slots:{...(W=Nt.layout)==null?void 0:W.slots,...(I=e.layout)==null?void 0:I.slots}},markdown:{...Nt.markdown,...e.markdown,options:{...(O=Nt.markdown)==null?void 0:O.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Nt.messageActions,...e.messageActions}}:Nt}var Qi={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"}},Yi={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"}},Zi={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:Xn,maxWidth:Ya,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 ss(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ss(e,r):r}function ei(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ss(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function el(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function xu(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=xu(o,s):n[r]=s}return n}function $g(e,t){return t?xu(e,t):e}function as(e,t={}){var s,o,a,i,d,l,u,p,f,m,v,x,T;let n={palette:Qi,semantic:Yi,components:Zi},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:$g(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let S=el(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(W=>W.message).join(", ")}`)}if(t.plugins)for(let S of t.plugins)r=S.transform(r);return r}function ti(e){var x,T,S,W,I,O,P,C,R,_,$,D,U,z,oe,We,He,Oe,de,we,ke,Pe,re,Le,K,ue,he,ge,me,Xe,V,ne,Re,fe,le,ie,Ye,Ae,pe,Q,je,At,X,Fe,kn,Ot,cn,Bn,Yn,B,se,De,Qe,_e,$e,ot,St,$t,Jt,J,ft,rt,qt,ae,xe,Ct,jt,en,bn,Mt,Et,yt,xt,zt,tt,Dn,Zn,xn,Nn,mt,vr,On,ho,Ln,Uo,zr,Mr,vt,Fn,_n,vn,It,er,tr,$n,Vr,kr,Kr,jn,Rt,wn,nr,Jr,Lr,Gr,wr,Un,dr,ht,Gt,Xt,qn,Xr,rr,pr,zn;let t=ei(e),n={};for(let[E,Vn]of Object.entries(t)){let ur=E.replace(/\./g,"-");n[`--persona-${ur}`]=Vn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(T=n["--persona-semantic-colors-secondary"])!=null?T:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(S=n["--persona-semantic-colors-accent"])!=null?S:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(W=n["--persona-semantic-colors-surface"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(I=n["--persona-semantic-colors-background"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(O=n["--persona-semantic-colors-container"])!=null?O:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(_=n["--persona-semantic-colors-border"])!=null?_:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(D=n["--persona-components-voice-recording-indicator"])!=null?D:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(U=n["--persona-components-voice-recording-background"])!=null?U:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(We=n["--persona-components-approval-requested-background"])!=null?We:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(He=n["--persona-components-approval-requested-border"])!=null?He:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Oe=n["--persona-components-approval-requested-text"])!=null?Oe:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(de=n["--persona-components-approval-approve-background"])!=null?de:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(we=n["--persona-components-approval-deny-background"])!=null?we:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(ke=n["--persona-components-attachment-image-background"])!=null?ke:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(Pe=n["--persona-components-attachment-image-border"])!=null?Pe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(re=n["--persona-semantic-typography-fontFamily"])!=null?re:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Le=n["--persona-semantic-typography-fontSize"])!=null?Le:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(K=n["--persona-semantic-typography-fontWeight"])!=null?K:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ue=n["--persona-semantic-typography-lineHeight"])!=null?ue:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(he=n["--persona-palette-radius-sm"])!=null?he:"0.125rem",n["--persona-radius-md"]=(ge=n["--persona-palette-radius-md"])!=null?ge:"0.375rem",n["--persona-radius-lg"]=(me=n["--persona-palette-radius-lg"])!=null?me:"0.5rem",n["--persona-radius-xl"]=(Xe=n["--persona-palette-radius-xl"])!=null?Xe:"0.75rem",n["--persona-radius-full"]=(V=n["--persona-palette-radius-full"])!=null?V:"9999px",n["--persona-launcher-radius"]=(Re=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?Re:"9999px",n["--persona-launcher-bg"]=(fe=n["--persona-components-launcher-background"])!=null?fe:n["--persona-primary"],n["--persona-launcher-fg"]=(le=n["--persona-components-launcher-foreground"])!=null?le:n["--persona-text-inverse"],n["--persona-launcher-border"]=(ie=n["--persona-components-launcher-border"])!=null?ie:n["--persona-border"],n["--persona-button-primary-bg"]=(Ye=n["--persona-components-button-primary-background"])!=null?Ye:n["--persona-primary"],n["--persona-button-primary-fg"]=(Ae=n["--persona-components-button-primary-foreground"])!=null?Ae:n["--persona-text-inverse"],n["--persona-button-radius"]=(Q=(pe=n["--persona-components-button-primary-borderRadius"])!=null?pe:n["--persona-palette-radius-full"])!=null?Q:"9999px",n["--persona-panel-radius"]=(At=(je=n["--persona-components-panel-borderRadius"])!=null?je:n["--persona-radius-xl"])!=null?At:"0.75rem",n["--persona-panel-border"]=(X=n["--persona-components-panel-border"])!=null?X:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(kn=(Fe=n["--persona-components-panel-shadow"])!=null?Fe:n["--persona-palette-shadows-xl"])!=null?kn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(cn=(Ot=n["--persona-components-input-borderRadius"])!=null?Ot:n["--persona-radius-lg"])!=null?cn:"0.5rem",n["--persona-message-user-radius"]=(Yn=(Bn=n["--persona-components-message-user-borderRadius"])!=null?Bn:n["--persona-radius-lg"])!=null?Yn:"0.5rem",n["--persona-message-assistant-radius"]=(se=(B=n["--persona-components-message-assistant-borderRadius"])!=null?B:n["--persona-radius-lg"])!=null?se:"0.5rem",n["--persona-header-bg"]=(De=n["--persona-components-header-background"])!=null?De:n["--persona-surface"],n["--persona-header-border"]=(Qe=n["--persona-components-header-border"])!=null?Qe:n["--persona-divider"],n["--persona-header-icon-bg"]=(_e=n["--persona-components-header-iconBackground"])!=null?_e:n["--persona-primary"],n["--persona-header-icon-fg"]=($e=n["--persona-components-header-iconForeground"])!=null?$e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ot=n["--persona-components-header-titleForeground"])!=null?ot:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(St=n["--persona-components-header-subtitleForeground"])!=null?St:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=($t=n["--persona-components-header-actionIconForeground"])!=null?$t:n["--persona-muted"];let r=(Jt=e.components)==null?void 0:Jt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(J=e.components)==null?void 0:J.introCard;n["--persona-intro-card-bg"]=(ft=n["--persona-components-introCard-background"])!=null?ft:n["--persona-surface"],n["--persona-intro-card-radius"]=(rt=n["--persona-components-introCard-borderRadius"])!=null?rt:"1rem",n["--persona-intro-card-padding"]=(qt=n["--persona-components-introCard-padding"])!=null?qt:"1.5rem",n["--persona-intro-card-shadow"]=(xe=(ae=s==null?void 0:s.shadow)!=null?ae:n["--persona-components-introCard-shadow"])!=null?xe:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ct=n["--persona-components-input-background"])!=null?Ct:n["--persona-surface"],n["--persona-input-placeholder"]=(jt=n["--persona-components-input-placeholder"])!=null?jt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(en=n["--persona-components-message-user-background"])!=null?en:n["--persona-accent"],n["--persona-message-user-text"]=(bn=n["--persona-components-message-user-text"])!=null?bn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Mt=n["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Et=n["--persona-components-message-assistant-background"])!=null?Et:n["--persona-surface"],n["--persona-message-assistant-text"]=(yt=n["--persona-components-message-assistant-text"])!=null?yt:n["--persona-text"],n["--persona-message-assistant-border"]=(xt=n["--persona-components-message-assistant-border"])!=null?xt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Dn=(tt=n["--persona-components-scrollToBottom-background"])!=null?tt:n["--persona-button-primary-bg"])!=null?Dn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(xn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?xn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Nn=n["--persona-components-scrollToBottom-border"])!=null?Nn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(mt=n["--persona-components-scrollToBottom-size"])!=null?mt:"40px",n["--persona-scroll-to-bottom-radius"]=(ho=(On=(vr=n["--persona-components-scrollToBottom-borderRadius"])!=null?vr:n["--persona-button-radius"])!=null?On:n["--persona-radius-full"])!=null?ho:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Uo=(Ln=n["--persona-components-scrollToBottom-shadow"])!=null?Ln:n["--persona-palette-shadows-sm"])!=null?Uo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(zr=n["--persona-components-scrollToBottom-padding"])!=null?zr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Mr=n["--persona-components-scrollToBottom-gap"])!=null?Mr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Fn=(vt=n["--persona-components-scrollToBottom-fontSize"])!=null?vt:n["--persona-palette-typography-fontSize-sm"])!=null?Fn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(_n=n["--persona-components-scrollToBottom-iconSize"])!=null?_n:"14px",n["--persona-tool-bubble-shadow"]=(vn=n["--persona-components-toolBubble-shadow"])!=null?vn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(It=n["--persona-components-reasoningBubble-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(er=n["--persona-components-composer-shadow"])!=null?er:"none",n["--persona-md-inline-code-bg"]=(tr=n["--persona-components-markdown-inlineCode-background"])!=null?tr:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(kr=(Vr=n["--persona-components-markdown-link-foreground"])!=null?Vr:n["--persona-accent"])!=null?kr:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Kr=n["--persona-components-markdown-codeBlock-background"])!=null?Kr:n["--persona-container"],n["--persona-md-code-block-border-color"]=(jn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?jn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Rt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Rt:"inherit",n["--persona-md-table-header-bg"]=(wn=n["--persona-components-markdown-table-headerBackground"])!=null?wn:n["--persona-container"],n["--persona-md-table-border-color"]=(nr=n["--persona-components-markdown-table-borderColor"])!=null?nr:n["--persona-border"],n["--persona-md-hr-color"]=(Jr=n["--persona-components-markdown-hr-color"])!=null?Jr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Lr=n["--persona-components-markdown-blockquote-borderColor"])!=null?Lr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Gr=n["--persona-components-markdown-blockquote-background"])!=null?Gr:"transparent",n["--persona-md-blockquote-text-color"]=(wr=n["--persona-components-markdown-blockquote-textColor"])!=null?wr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Un=n["--persona-components-collapsibleWidget-container"])!=null?Un:n["--persona-surface"],n["--cw-surface"]=(dr=n["--persona-components-collapsibleWidget-surface"])!=null?dr:n["--persona-surface"],n["--cw-border"]=(ht=n["--persona-components-collapsibleWidget-border"])!=null?ht:n["--persona-border"],n["--persona-message-border"]=(Gt=n["--persona-components-message-border"])!=null?Gt:n["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let E=v.toolbar;E.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=E.iconHoverColor),E.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=E.iconHoverBackground),E.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=E.iconPadding),E.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=E.iconBorderRadius),E.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=E.iconBorder),E.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=E.toggleGroupGap),E.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=E.toggleBorderRadius),E.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=E.copyBackground),E.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=E.copyBorder),E.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=E.copyColor),E.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=E.copyBorderRadius),E.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=E.copyPadding),E.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=E.copyMenuBackground,n["--persona-dropdown-bg"]=(Xt=n["--persona-dropdown-bg"])!=null?Xt:E.copyMenuBackground),E.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=E.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:E.copyMenuBorder),E.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=E.copyMenuShadow,n["--persona-dropdown-shadow"]=(Xr=n["--persona-dropdown-shadow"])!=null?Xr:E.copyMenuShadow),E.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=E.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(rr=n["--persona-dropdown-radius"])!=null?rr:E.copyMenuBorderRadius),E.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=E.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(pr=n["--persona-dropdown-item-hover-bg"])!=null?pr:E.copyMenuItemHoverBackground),E.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=E.iconBackground),E.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=E.toolbarBorder)}if(v!=null&&v.tab){let E=v.tab;E.background&&(n["--persona-artifact-tab-bg"]=E.background),E.activeBackground&&(n["--persona-artifact-tab-active-bg"]=E.activeBackground),E.activeBorder&&(n["--persona-artifact-tab-active-border"]=E.activeBorder),E.borderRadius&&(n["--persona-artifact-tab-radius"]=E.borderRadius),E.textColor&&(n["--persona-artifact-tab-color"]=E.textColor),E.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=E.hoverBackground),E.listBackground&&(n["--persona-artifact-tab-list-bg"]=E.listBackground),E.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=E.listBorderColor),E.listPadding&&(n["--persona-artifact-tab-list-padding"]=E.listPadding)}if(v!=null&&v.pane){let E=v.pane;if(E.toolbarBackground){let Vn=(zn=ss(e,E.toolbarBackground))!=null?zn:E.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Vn}}return n}var vu={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 jg={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"}}},wu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Js=()=>{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"},Ug=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Js()},tl=e=>Ug(e),qg=e=>as(e),zg=e=>{var n;let t=as(void 0,{validate:!1});return as({...e,palette:{...t.palette,colors:{...jg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},is=e=>{let t=tl(e),n=wu(e==null?void 0:e.theme),r=wu(e==null?void 0:e.darkTheme);return t==="dark"?zg(Ks(n!=null?n:{},r!=null?r:{})):qg(n)},Vg=e=>ti(e),so=(e,t)=>{var o;let n=is(t),r=Vg(n);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=t==null?void 0:t.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ni=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Js())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Js());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var Cu=require("idiomorph"),ri=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Cu.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var oi={index:-1,draft:""};function Au(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...oi}}}function Su(e,t){var n,r,s,o,a,i,d,l,u,p,f,m,v,x,T,S,W,I,O,P,C,R,_,$,D,U,z,oe,We,He,Oe,de,we,ke,Pe,re,Le,K;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(T=(x=e.toolCall)==null?void 0:x.name)!=null?T:"",(I=(W=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:W.length)!=null?I:0,(R=(C=(P=(O=e.toolCall)==null?void 0:O.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(z=(U=(D=e.reasoning)==null?void 0:D.chunks)==null?void 0:U.length)!=null?z:0,(Oe=(He=(We=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:He.length)!=null?Oe:0,(Pe=(ke=(we=(de=e.reasoning)==null?void 0:de.chunks)==null?void 0:we[e.reasoning.chunks.length-1])==null?void 0:ke.slice(-32))!=null?Pe:"",(Le=(re=e.contentParts)==null?void 0:re.length)!=null?Le:0,(K=e.stopReason)!=null?K:"",t].join("\0")}function Eu(){return new Map}function Tu(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Mu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function ku(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function si(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Gs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Xs(e,t){return Gs(e)-e.scrollTop<=t}function ai(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:n}:!t&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function ii(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,ao=yn+1;var Qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Kg=["pre","code","a","script","style"],li=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Qs.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Qs.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Qs.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Qs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Qs.buffer}},Pu=[{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"}],Ys=new Map;for(let e of Pu)Ys.set(e.name,e);var Iu=e=>{Ys.set(e.name,e)},Wu=e=>{Pu.some(t=>t.name===e)||Ys.delete(e)},Ru=()=>Array.from(Ys.keys()),Zs=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Ys.get(e))!=null?r:null},ci=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
15
- `);return o<0?"":e.slice(0,o)}return e},Jg=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},Gg=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},nl=/\s/,Xg=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Qg=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(nl.test(o[i])){let l=i;for(;l<o.length&&nl.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!nl.test(o[u]);)l.appendChild(Jg(r,o[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},Yg=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Gg(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},ea=(e,t,n,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((p=r==null?void 0:r.skipTags)!=null?p:Kg).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Xg(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=t==="char"?Qg:Yg;for(let m of i)u(m,n,l);return s.innerHTML},di=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ta=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Lu=new WeakMap,Zg=(e,t)=>{var o;if(!e.styles)return;let n=Lu.get(t);if(n||(n=new Set,Lu.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},rl=new WeakMap,ef=(e,t)=>{if(!e.onAttach)return;let n=rl.get(t);if(n||(n=new Map,rl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Hu=e=>{let t=rl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ol=(e,t)=>{Zg(e,t),ef(e,t)};function sl(e,t=yn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var na=0,io=null;function al(e=document){var n;if(na++,na===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;io={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,na=Math.max(0,na-1),na===0&&io)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=io.originalOverflow,s.style.position=io.originalPosition,s.style.top=io.originalTop,s.style.width=io.originalWidth,o.scrollTo(0,io.scrollY),io=null}}}var pi={side:"right",width:"420px",animate:!0,reveal:"resize"},on=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},lo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},ir=e=>{var n,r,s,o,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:pi.side,width:(s=t==null?void 0:t.width)!=null?s:pi.width,animate:(o=t==null?void 0:t.animate)!=null?o:pi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:pi.reveal}};var xr={"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 ra=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
14
+ _Details: ${t.message}_`:r}var os=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d,l;if(n.type==="message"){this.upsertMessage(n.message);let u=n.message.toolCall;((t=n.message.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&(u!=null&&u.name)&&$s(u.name)&&this.enqueueWebMcpAwait(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(s=n.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(n.type==="status"){if(this.setStatus(n.status),n.status==="connecting")this.setStreaming(!0);else if(n.status==="idle"||n.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(n.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else n.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Wo(n),this.wireDefaultWebMcpConfirm();for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Vs((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Bo(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,m,x,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(x=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:x.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Wo(this.config),this.wireDefaultWebMcpConfirm(),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=n,m={id:a!=null?a:t==="user"?rs():t==="assistant"?Ro():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:m}=r,v={id:d!=null?d:s==="user"?rs():s==="assistant"?Ro():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};t.push(v)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=n,l={text:s,component:t,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(n,t){var l,u,p,f,m;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=rs(),o=Ro(),a={id:s,role:"user",content:r||Va,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let E=yu(x,this.config.errorMessage);if(E){let S={id:o,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(S)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,x):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=Ro();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=yu(l,this.config.errorMessage);if(p){let f={id:n,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(n,t){var s,o,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let n=this.config.webmcp;(n==null?void 0:n.enabled)===!0&&!n.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(n){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,n))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:n.toolName,toolType:"webmcp",description:(a=n.description)!=null?a:`Allow the assistant to run ${n.toolName}?`,parameters:n.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(n,t){let r=this.webMcpApprovalResolvers.get(n);if(!r)return;this.webMcpApprovalResolvers.delete(n);let s=this.messages.find(o=>o.id===n);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(n,t){var d,l,u,p;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):f=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),f){let m=null;if(f instanceof Response){if(!f.ok){let x=await f.json().catch(()=>null);throw new Error((l=x==null?void 0:x.error)!=null?l:`Approval request failed: ${f.status}`)}m=f.body}else f instanceof ReadableStream&&(m=f);m?await this.connectStream(m,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let m=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,p,f,m,x,v,E,S,R,I,W,P;let r=this.messages.find(w=>w.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=n.agentMetadata)==null?void 0:p.executionId,o=(f=n.toolCall)==null?void 0:f.name;if(!s||!o){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let w=(v=n.toolCall)==null?void 0:v.args,H=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(H.length===1){let _=typeof((E=H[0])==null?void 0:E.question)=="string"?H[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=(R=n.toolCall)==null?void 0:R.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof t=="string"?t:Object.entries(t).map(([H,_])=>`${H}: ${Array.isArray(_)?_.join(", "):_}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((H,_)=>{let $=typeof(H==null?void 0:H.question)=="string"?H.question:"";if(!$)return;let N=w[$],U=Array.isArray(N)?N.join(", "):typeof N=="string"?N:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:t});if(!w.ok){let H=await w.json().catch(()=>null);throw new Error((I=H==null?void 0:H.error)!=null?I:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let H=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,H||(P=(W=this.callbacks).onError)==null||P.call(W,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(n){var o,a;let t=(o=n.agentMetadata)==null?void 0:o.executionId,r=(a=n.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(n)});return}let s=this.webMcpAwaitBatches.get(t);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(n))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let n=this.webMcpEpoch;queueMicrotask(()=>{if(n===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(n){let t=this.webMcpAwaitBatches.get(n);if(!t)return;this.webMcpAwaitBatches.delete(n);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(n,r)}async resolveWebMcpToolCallBatch(n,t){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(t.map(async u=>{var R,I,W,P,w,H,_;let p=(R=u.toolCall)==null?void 0:R.name,f=(I=u.toolCall)==null?void 0:I.id;if(!p||!f)return null;let m=`${n}:${f}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),r.push(m),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let x=new AbortController;this.webMcpResolveControllers.add(x),s.push(x);let v=(P=(W=u.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?P:p,E=this.client.executeWebMcpToolCall(p,(w=u.toolCall)==null?void 0:w.args,x.signal),S;if(!E)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await E}catch($){return $ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"))||(_=(H=this.callbacks).onError)==null||_.call(H,$ instanceof Error?$:new Error(String($))),this.webMcpInflightKeys.delete(m),null}return x.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:v,output:S}}));try{let u=a.filter(m=>m!==null);if(u.length===0)return;let p={};for(let m of u)p[m.resumeKey]=m.output;let f=await this.client.resumeFlow(n,p,{signal:o.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${f.status}`)}for(let m of u)this.webMcpResolvedKeys.add(m.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of s)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(n){var u,p,f,m,x,v,E,S,R,I,W,P;let t=(u=n.agentMetadata)==null?void 0:u.executionId,r=(p=n.toolCall)==null?void 0:p.name,s=(f=n.toolCall)==null?void 0:f.id;if(!t){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(H){(E=(v=this.callbacks).onError)==null||E.call(v,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${t}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(S=n.toolCall)==null?void 0:S.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let H=(I=(R=n.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?I:r;await this.resumeWithToolOutput(t,H,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(P=(W=this.callbacks).onError)==null||P.call(W,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(n,t,r,s){var a,i;let o=await this.client.resumeFlow(n,{[t]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let n of this.webMcpResolveControllers)n.abort();this.webMcpResolveControllers.clear();for(let n of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(n,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var u,p,f,m,x,v;if(o!==r)return s;let a={...s,...t};((u=s.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=t.toolCall)==null?void 0:p.name,d=(f=t.agentMetadata)==null?void 0:f.executionId,l=(m=t.toolCall)==null?void 0:m.id;if(i&&$s(i)&&d&&l&&((x=t.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let E=`${d}:${l}`;(this.webMcpInflightKeys.has(E)||this.webMcpResolvedKeys.has(E))&&(a.agentMetadata={...(v=a.agentMetadata)!=null?v:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},Tr=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var C=require("lucide"),_g={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},ye=(e,n=24,t="currentColor",r=2)=>{let s=_g[e];return s?$g(s,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function $g(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var Qa={allowedTypes:Fr,maxFileSize:10*1024*1024,maxFiles:4};function jg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ug(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 Do=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Qa.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Qa.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Qa.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:Qa.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let u=hu(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await fu(l),f=Ka(l)?URL.createObjectURL(l):null,m={id:jg(),file:l,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ka(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=Ug(n.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=bu(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=ye("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var xu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ks(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];xu(o)&&xu(s)?t[r]=Ks(o,s):t[r]=s}return t}var Xn="min(440px, calc(100vw - 24px))",Ya="440px",Nt={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:Xn,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 vu(e,n){if(!(!e&&!n))return e?n?Ks(e,n):e:n}function Za(e){var n,t,r,s,o,a,i,d,l,u,p,f,m,x,v,E,S,R,I,W,P;return e?{...Nt,...e,theme:vu(Nt.theme,e.theme),darkTheme:vu(Nt.darkTheme,e.darkTheme),launcher:{...Nt.launcher,...e.launcher,dock:{...(n=Nt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Nt.copy,...e.copy},sendButton:{...Nt.sendButton,...e.sendButton},statusIndicator:{...Nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...e.voiceRecognition},features:(()=>{var we,ke,Pe,re,Le,K,ue,he;let w=(we=Nt.features)==null?void 0:we.artifacts,H=(ke=e.features)==null?void 0:ke.artifacts,_=(Pe=Nt.features)==null?void 0:Pe.scrollToBottom,$=(re=e.features)==null?void 0:re.scrollToBottom,N=(Le=Nt.features)==null?void 0:Le.streamAnimation,U=(K=e.features)==null?void 0:K.streamAnimation,z=(ue=Nt.features)==null?void 0:ue.askUserQuestion,oe=(he=e.features)==null?void 0:he.askUserQuestion,We=w===void 0&&H===void 0?void 0:{...w,...H,layout:{...w==null?void 0:w.layout,...H==null?void 0:H.layout}},He=_===void 0&&$===void 0?void 0:{..._,...$},Oe=N===void 0&&U===void 0?void 0:{...N,...U},de=z===void 0&&oe===void 0?void 0:{...z,...oe,styles:{...z==null?void 0:z.styles,...oe==null?void 0:oe.styles}};return{...Nt.features,...e.features,...He!==void 0?{scrollToBottom:He}:{},...We!==void 0?{artifacts:We}:{},...Oe!==void 0?{streamAnimation:Oe}:{},...de!==void 0?{askUserQuestion:de}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Nt.layout,...e.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Nt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(v=(x=Nt.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(S=(E=e.layout)==null?void 0:E.messages)==null?void 0:S.timestamp}},slots:{...(R=Nt.layout)==null?void 0:R.slots,...(I=e.layout)==null?void 0:I.slots}},markdown:{...Nt.markdown,...e.markdown,options:{...(W=Nt.markdown)==null?void 0:W.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Nt.messageActions,...e.messageActions}}:Nt}var Qi={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"}},Yi={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"}},Zi={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:Xn,maxWidth:Ya,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 ss(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ss(e,r):r}function ei(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ss(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function el(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 wu(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=wu(o,s):t[r]=s}return t}function qg(e,n){return n?wu(e,n):e}function as(e,n={}){var s,o,a,i,d,l,u,p,f,m,x,v,E;let t={palette:Qi,semantic:Yi,components:Zi},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...t.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:qg(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let S=el(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(R=>R.message).join(", ")}`)}if(n.plugins)for(let S of n.plugins)r=S.transform(r);return r}function ti(e){var v,E,S,R,I,W,P,w,H,_,$,N,U,z,oe,We,He,Oe,de,we,ke,Pe,re,Le,K,ue,he,ge,me,Xe,V,ne,Re,fe,le,ie,Ye,Ae,pe,Q,je,At,X,Fe,kn,Ot,cn,Bn,Yn,D,se,De,Qe,_e,$e,ot,St,$t,Jt,J,ft,rt,qt,ae,xe,Ct,jt,en,yn,Mt,Tt,bt,xt,zt,tt,Dn,Zn,xn,Nn,mt,vr,On,ho,Ln,Uo,zr,Mr,vt,Fn,_n,vn,It,er,tr,$n,Vr,kr,Kr,jn,Rt,wn,nr,Jr,Lr,Gr,wr,Un,dr,ht,Gt,Xt,qn,Xr,rr,pr,zn;let n=ei(e),t={};for(let[T,Vn]of Object.entries(n)){let ur=T.replace(/\./g,"-");t[`--persona-${ur}`]=Vn.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E: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"]=(R=t["--persona-semantic-colors-surface"])!=null?R:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(I=t["--persona-semantic-colors-background"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(W=t["--persona-semantic-colors-container"])!=null?W: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"]=(w=t["--persona-semantic-colors-text-muted"])!=null?w:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(H=t["--persona-semantic-colors-text-inverse"])!=null?H:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(_=t["--persona-semantic-colors-border"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=($=t["--persona-semantic-colors-divider"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(N=t["--persona-components-voice-recording-indicator"])!=null?N:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(U=t["--persona-components-voice-recording-background"])!=null?U:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(z=t["--persona-components-voice-processing-icon"])!=null?z:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(We=t["--persona-components-approval-requested-background"])!=null?We:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(He=t["--persona-components-approval-requested-border"])!=null?He:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Oe=t["--persona-components-approval-requested-text"])!=null?Oe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(de=t["--persona-components-approval-approve-background"])!=null?de:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(we=t["--persona-components-approval-deny-background"])!=null?we: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"]=(Pe=t["--persona-components-attachment-image-border"])!=null?Pe:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Le=t["--persona-semantic-typography-fontSize"])!=null?Le:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(K=t["--persona-semantic-typography-fontWeight"])!=null?K:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ue=t["--persona-semantic-typography-lineHeight"])!=null?ue: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"]=(ge=t["--persona-palette-radius-md"])!=null?ge:"0.375rem",t["--persona-radius-lg"]=(me=t["--persona-palette-radius-lg"])!=null?me:"0.5rem",t["--persona-radius-xl"]=(Xe=t["--persona-palette-radius-xl"])!=null?Xe:"0.75rem",t["--persona-radius-full"]=(V=t["--persona-palette-radius-full"])!=null?V:"9999px",t["--persona-launcher-radius"]=(Re=(ne=t["--persona-components-launcher-borderRadius"])!=null?ne:t["--persona-palette-radius-full"])!=null?Re:"9999px",t["--persona-launcher-bg"]=(fe=t["--persona-components-launcher-background"])!=null?fe:t["--persona-primary"],t["--persona-launcher-fg"]=(le=t["--persona-components-launcher-foreground"])!=null?le:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ie=t["--persona-components-launcher-border"])!=null?ie:t["--persona-border"],t["--persona-button-primary-bg"]=(Ye=t["--persona-components-button-primary-background"])!=null?Ye:t["--persona-primary"],t["--persona-button-primary-fg"]=(Ae=t["--persona-components-button-primary-foreground"])!=null?Ae:t["--persona-text-inverse"],t["--persona-button-radius"]=(Q=(pe=t["--persona-components-button-primary-borderRadius"])!=null?pe:t["--persona-palette-radius-full"])!=null?Q:"9999px",t["--persona-panel-radius"]=(At=(je=t["--persona-components-panel-borderRadius"])!=null?je:t["--persona-radius-xl"])!=null?At:"0.75rem",t["--persona-panel-border"]=(X=t["--persona-components-panel-border"])!=null?X:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(kn=(Fe=t["--persona-components-panel-shadow"])!=null?Fe:t["--persona-palette-shadows-xl"])!=null?kn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(cn=(Ot=t["--persona-components-input-borderRadius"])!=null?Ot:t["--persona-radius-lg"])!=null?cn:"0.5rem",t["--persona-message-user-radius"]=(Yn=(Bn=t["--persona-components-message-user-borderRadius"])!=null?Bn:t["--persona-radius-lg"])!=null?Yn:"0.5rem",t["--persona-message-assistant-radius"]=(se=(D=t["--persona-components-message-assistant-borderRadius"])!=null?D:t["--persona-radius-lg"])!=null?se:"0.5rem",t["--persona-header-bg"]=(De=t["--persona-components-header-background"])!=null?De:t["--persona-surface"],t["--persona-header-border"]=(Qe=t["--persona-components-header-border"])!=null?Qe:t["--persona-divider"],t["--persona-header-icon-bg"]=(_e=t["--persona-components-header-iconBackground"])!=null?_e:t["--persona-primary"],t["--persona-header-icon-fg"]=($e=t["--persona-components-header-iconForeground"])!=null?$e:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(ot=t["--persona-components-header-titleForeground"])!=null?ot:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(St=t["--persona-components-header-subtitleForeground"])!=null?St:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=($t=t["--persona-components-header-actionIconForeground"])!=null?$t:t["--persona-muted"];let r=(Jt=e.components)==null?void 0:Jt.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(J=e.components)==null?void 0:J.introCard;t["--persona-intro-card-bg"]=(ft=t["--persona-components-introCard-background"])!=null?ft:t["--persona-surface"],t["--persona-intro-card-radius"]=(rt=t["--persona-components-introCard-borderRadius"])!=null?rt:"1rem",t["--persona-intro-card-padding"]=(qt=t["--persona-components-introCard-padding"])!=null?qt:"1.5rem",t["--persona-intro-card-shadow"]=(xe=(ae=s==null?void 0:s.shadow)!=null?ae:t["--persona-components-introCard-shadow"])!=null?xe:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ct=t["--persona-components-input-background"])!=null?Ct:t["--persona-surface"],t["--persona-input-placeholder"]=(jt=t["--persona-components-input-placeholder"])!=null?jt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(en=t["--persona-components-message-user-background"])!=null?en:t["--persona-accent"],t["--persona-message-user-text"]=(yn=t["--persona-components-message-user-text"])!=null?yn:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Mt=t["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Tt=t["--persona-components-message-assistant-background"])!=null?Tt:t["--persona-surface"],t["--persona-message-assistant-text"]=(bt=t["--persona-components-message-assistant-text"])!=null?bt:t["--persona-text"],t["--persona-message-assistant-border"]=(xt=t["--persona-components-message-assistant-border"])!=null?xt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(zt=t["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Dn=(tt=t["--persona-components-scrollToBottom-background"])!=null?tt:t["--persona-button-primary-bg"])!=null?Dn:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(xn=(Zn=t["--persona-components-scrollToBottom-foreground"])!=null?Zn:t["--persona-button-primary-fg"])!=null?xn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Nn=t["--persona-components-scrollToBottom-border"])!=null?Nn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(mt=t["--persona-components-scrollToBottom-size"])!=null?mt:"40px",t["--persona-scroll-to-bottom-radius"]=(ho=(On=(vr=t["--persona-components-scrollToBottom-borderRadius"])!=null?vr:t["--persona-button-radius"])!=null?On:t["--persona-radius-full"])!=null?ho:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Uo=(Ln=t["--persona-components-scrollToBottom-shadow"])!=null?Ln:t["--persona-palette-shadows-sm"])!=null?Uo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(zr=t["--persona-components-scrollToBottom-padding"])!=null?zr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Mr=t["--persona-components-scrollToBottom-gap"])!=null?Mr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Fn=(vt=t["--persona-components-scrollToBottom-fontSize"])!=null?vt:t["--persona-palette-typography-fontSize-sm"])!=null?Fn:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(_n=t["--persona-components-scrollToBottom-iconSize"])!=null?_n:"14px",t["--persona-tool-bubble-shadow"]=(vn=t["--persona-components-toolBubble-shadow"])!=null?vn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(It=t["--persona-components-reasoningBubble-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(er=t["--persona-components-composer-shadow"])!=null?er:"none",t["--persona-md-inline-code-bg"]=(tr=t["--persona-components-markdown-inlineCode-background"])!=null?tr:t["--persona-container"],t["--persona-md-inline-code-color"]=($n=t["--persona-components-markdown-inlineCode-foreground"])!=null?$n:t["--persona-text"],t["--persona-md-link-color"]=(kr=(Vr=t["--persona-components-markdown-link-foreground"])!=null?Vr:t["--persona-accent"])!=null?kr:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Kr=t["--persona-components-markdown-codeBlock-background"])!=null?Kr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(jn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?jn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Rt=t["--persona-components-markdown-codeBlock-textColor"])!=null?Rt:"inherit",t["--persona-md-table-header-bg"]=(wn=t["--persona-components-markdown-table-headerBackground"])!=null?wn:t["--persona-container"],t["--persona-md-table-border-color"]=(nr=t["--persona-components-markdown-table-borderColor"])!=null?nr:t["--persona-border"],t["--persona-md-hr-color"]=(Jr=t["--persona-components-markdown-hr-color"])!=null?Jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Lr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Lr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Gr=t["--persona-components-markdown-blockquote-background"])!=null?Gr:"transparent",t["--persona-md-blockquote-text-color"]=(wr=t["--persona-components-markdown-blockquote-textColor"])!=null?wr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Un=t["--persona-components-collapsibleWidget-container"])!=null?Un:t["--persona-surface"],t["--cw-surface"]=(dr=t["--persona-components-collapsibleWidget-surface"])!=null?dr:t["--persona-surface"],t["--cw-border"]=(ht=t["--persona-components-collapsibleWidget-border"])!=null?ht:t["--persona-border"],t["--persona-message-border"]=(Gt=t["--persona-components-message-border"])!=null?Gt:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let T=x.toolbar;T.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,t["--persona-dropdown-bg"]=(Xt=t["--persona-dropdown-bg"])!=null?Xt:T.copyMenuBackground),T.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,t["--persona-dropdown-border"]=(qn=t["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,t["--persona-dropdown-shadow"]=(Xr=t["--persona-dropdown-shadow"])!=null?Xr:T.copyMenuShadow),T.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(rr=t["--persona-dropdown-radius"])!=null?rr:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(pr=t["--persona-dropdown-item-hover-bg"])!=null?pr:T.copyMenuItemHoverBackground),T.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(x!=null&&x.tab){let T=x.tab;T.background&&(t["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(t["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(t["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(t["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(t["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(t["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(t["--persona-artifact-tab-list-padding"]=T.listPadding)}if(x!=null&&x.pane){let T=x.pane;if(T.toolbarBackground){let Vn=(zn=ss(e,T.toolbarBackground))!=null?zn:T.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Vn}}return t}var Cu={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 zg={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"}}},Au=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Js=()=>{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"},Vg=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Js()},tl=e=>Vg(e),Kg=e=>as(e),Jg=e=>{var t;let n=as(void 0,{validate:!1});return as({...e,palette:{...n.palette,colors:{...zg.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},is=e=>{let n=tl(e),t=Au(e==null?void 0:e.theme),r=Au(e==null?void 0:e.darkTheme);return n==="dark"?Jg(Ks(t!=null?t:{},r!=null?r:{})):Kg(t)},Gg=e=>ti(e),so=(e,n)=>{var o;let t=is(n),r=Gg(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ni=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Js())});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(Js());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 Su=require("idiomorph"),ri=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Su.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var oi={index:-1,draft:""};function Tu(e){let{direction:n,history:t,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(t.length===0)return{handled:!1,state:o};if(n==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<t.length-1){let i=o.index+1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...oi}}}function Eu(e,n){var t,r,s,o,a,i,d,l,u,p,f,m,x,v,E,S,R,I,W,P,w,H,_,$,N,U,z,oe,We,He,Oe,de,we,ke,Pe,re,Le,K;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(I=(R=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:R.length)!=null?I:0,(H=(w=(P=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?H:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(z=(U=(N=e.reasoning)==null?void 0:N.chunks)==null?void 0:U.length)!=null?z:0,(Oe=(He=(We=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:He.length)!=null?Oe:0,(Pe=(ke=(we=(de=e.reasoning)==null?void 0:de.chunks)==null?void 0:we[e.reasoning.chunks.length-1])==null?void 0:ke.slice(-32))!=null?Pe:"",(Le=(re=e.contentParts)==null?void 0:re.length)!=null?Le:0,(K=e.stopReason)!=null?K:"",n].join("\0")}function Mu(){return new Map}function ku(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Lu(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Pu(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function si(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Gs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Xs(e,n){return Gs(e)-e.scrollTop<=n}function ai(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!n&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function ii(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},bn=1e5,ao=bn+1;var Qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Xg=["pre","code","a","script","style"],li=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Qs.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Qs.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Qs.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Qs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Qs.buffer}},Wu=[{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"}],Ys=new Map;for(let e of Wu)Ys.set(e.name,e);var Ru=e=>{Ys.set(e.name,e)},Hu=e=>{Wu.some(n=>n.name===e)||Ys.delete(e)},Bu=()=>Array.from(Ys.keys()),Zs=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Ys.get(e))!=null?r:null},ci=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
15
+ `);return o<0?"":e.slice(0,o)}return e},Qg=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},Yg=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},nl=/\s/,Zg=(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},ef=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(nl.test(o[i])){let l=i;for(;l<o.length&&nl.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!nl.test(o[u]);)l.appendChild(Qg(r,o[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},tf=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Yg(r,l,n,t.value)),t.value+=1));s.replaceChild(a,e)},ea=(e,n,t,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((p=r==null?void 0:r.skipTags)!=null?p:Xg).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Zg(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?ef:tf;for(let m of i)u(m,t,l);return s.innerHTML},di=(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},ta=(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},Iu=new WeakMap,nf=(e,n)=>{var o;if(!e.styles)return;let t=Iu.get(n);if(t||(t=new Set,Iu.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},rl=new WeakMap,rf=(e,n)=>{if(!e.onAttach)return;let t=rl.get(n);if(t||(t=new Map,rl.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},Du=e=>{let n=rl.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},ol=(e,n)=>{nf(e,n),rf(e,n)};function sl(e,n=bn){let t=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var na=0,io=null;function al(e=document){var t;if(na++,na===1){let r=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;io={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,na=Math.max(0,na-1),na===0&&io)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=io.originalOverflow,s.style.position=io.originalPosition,s.style.top=io.originalTop,s.style.width=io.originalWidth,o.scrollTo(0,io.scrollY),io=null}}}var pi={side:"right",width:"420px",animate:!0,reveal:"resize"},on=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},lo=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},ir=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:pi.side,width:(s=n==null?void 0:n.width)!=null?s:pi.width,animate:(o=n==null?void 0:n.animate)!=null?o:pi.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:pi.reveal}};var xr={"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 ra=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
16
16
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
17
17
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
18
18
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -20,14 +20,14 @@ _Details: ${n.message}_`:r}var os=class e{constructor(t={},n){this.config=t;this
20
20
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
21
21
  </span>
22
22
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
23
- `,n.addEventListener("click",t);let r=o=>{var I,O,P,C,R,_,$,D,U,z,oe,We,He,Oe;let a=(I=o.launcher)!=null?I:{},i=on(o),d=n.querySelector("[data-role='launcher-title']");if(d){let de=(O=a.title)!=null?O:"Chat Assistant";d.textContent=de,d.setAttribute("title",de)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let de=(P=a.subtitle)!=null?P:"Get answers fast";l.textContent=de,l.setAttribute("title",de)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let de=(C=a.agentIconSize)!=null?C:"40px";if(p.style.height=de,p.style.width=de,p.innerHTML="",a.agentIconName){let we=parseFloat(de)||24,ke=be(a.agentIconName,we*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(p.appendChild(ke),p.style.display=""):(p.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(_=a.agentIconText)!=null?_:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let de=($=a.agentIconSize)!=null?$:"40px";f.style.height=de,f.style.width=de,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let de=(D=a.callToActionIconSize)!=null?D:"32px";m.style.height=de,m.style.width=de,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let we=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,we=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let ke=parseFloat(de)||24,Pe=Math.max(ke-we,8),re=be(a.callToActionIconName,Pe,"currentColor",2);re?m.appendChild(re):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let v=a.position&&xr[a.position]?xr[a.position]:xr["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",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?T:`${x} ${v}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:yn));let S="1px solid var(--persona-border, #e5e7eb)",W="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(We=a.border)!=null?We:S,n.style.boxShadow=(He=a.shadow)!=null?He:W,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Oe=a.collapsedMaxWidth)!=null?Oe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var tf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ui=(e,t={})=>{var x,T,S,W,I,O;let{showClose:n=!0,wrapperClassName:r=tf,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(T=s!=null?s:a.closeButtonSize)!=null?T:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(S=a.closeButtonTooltipText)!=null?S:"Close chat",p=(W=a.closeButtonShowTooltip)!=null?W:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(I=a.closeButtonIconName)!=null?I:"x",m=(O=a.closeButtonIconText)!=null?O:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let v=be(f,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let P=a.closeButtonBorderWidth||"0px",C=a.closeButtonBorderColor||"transparent";l.style.border=`${P} solid ${C}`,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,C=()=>{if(P)return;let _=l.ownerDocument,$=_.body;if(!$)return;P=Er(_,"div","persona-clear-chat-tooltip"),P.textContent=u;let D=Er(_,"div");D.className="persona-clear-chat-tooltip-arrow",P.appendChild(D);let U=l.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(ao),P.style.left=`${U.left+U.width/2}px`,P.style.top=`${U.top-8}px`,P.style.transform="translate(-50%, -100%)",$.appendChild(P)},R=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};d.addEventListener("mouseenter",C),d.addEventListener("mouseleave",R),l.addEventListener("focus",C),l.addEventListener("blur",R),d._cleanupTooltip=()=>{R(),d.removeEventListener("mouseenter",C),d.removeEventListener("mouseleave",R),l.removeEventListener("focus",C),l.removeEventListener("blur",R)}}return{button:l,wrapper:d}},nf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mi=(e,t={})=>{var P,C,R,_,$,D,U,z,oe,We,He,Oe,de;let{wrapperClassName:n=nf,buttonSize:r,iconSize:s="20px"}=t,a=(C=((P=e==null?void 0:e.launcher)!=null?P:{}).clearChat)!=null?C:{},i=(R=r!=null?r:a.size)!=null?R:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",l=($=a.iconColor)!=null?$:"",u=(D=a.backgroundColor)!=null?D:"",p=(U=a.borderWidth)!=null?U:"",f=(z=a.borderColor)!=null?z:"",m=(oe=a.borderRadius)!=null?oe:"",v=(We=a.paddingX)!=null?We:"",x=(He=a.paddingY)!=null?He:"",T=(Oe=a.tooltipText)!=null?Oe:"Clear chat",S=(de=a.showTooltip)!=null?de:!0,W=h("div",n),I=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");I.style.height=i,I.style.width=i,I.type="button",I.setAttribute("aria-label",T),I.style.color=l||Mn.actionIconColor;let O=be(d,s,"currentColor",1);if(O&&(O.style.display="block",I.appendChild(O)),u&&(I.style.backgroundColor=u,I.classList.remove("hover:persona-bg-gray-100")),p||f){let we=p||"0px",ke=f||"transparent";I.style.border=`${we} solid ${ke}`,I.classList.remove("persona-border-none")}if(m&&(I.style.borderRadius=m,I.classList.remove("persona-rounded-full")),v&&(I.style.paddingLeft=v,I.style.paddingRight=v),x&&(I.style.paddingTop=x,I.style.paddingBottom=x),W.appendChild(I),S&&T){let we=null,ke=()=>{if(we)return;let re=I.ownerDocument,Le=re.body;if(!Le)return;we=Er(re,"div","persona-clear-chat-tooltip"),we.textContent=T;let K=Er(re,"div");K.className="persona-clear-chat-tooltip-arrow",we.appendChild(K);let ue=I.getBoundingClientRect();we.style.position="fixed",we.style.zIndex=String(ao),we.style.left=`${ue.left+ue.width/2}px`,we.style.top=`${ue.top-8}px`,we.style.transform="translate(-50%, -100%)",Le.appendChild(we)},Pe=()=>{we&&we.parentNode&&(we.parentNode.removeChild(we),we=null)};W.addEventListener("mouseenter",ke),W.addEventListener("mouseleave",Pe),I.addEventListener("focus",ke),I.addEventListener("blur",Pe),W._cleanupTooltip=()=>{Pe(),W.removeEventListener("mouseenter",ke),W.removeEventListener("mouseleave",Pe),I.removeEventListener("focus",ke),I.removeEventListener("blur",Pe)}}return{button:I,wrapper:W}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},_r=e=>{var P,C,R,_,$,D,U,z,oe,We,He,Oe,de,we,ke,Pe;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(P=t==null?void 0:t.launcher)!=null?P:{},o=(C=s.headerIconSize)!=null?C:"48px",a=(R=s.closeButtonPlacement)!=null?R:"inline",i=(_=s.headerIconHidden)!=null?_:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let re=parseFloat(o)||24,Le=be(d,re*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(D=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?D:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let re=h("img");re.src=t.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=o,re.style.width=o,l.replaceChildren(re)}else l.textContent=(oe=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=Mn.titleColor,p.textContent=(He=(We=t==null?void 0:t.launcher)==null?void 0:We.title)!=null?He:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Mn.subtitleColor,f.textContent=(de=(Oe=t==null?void 0:t.launcher)==null?void 0:Oe.subtitle)!=null?de:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let m=(we=s.clearChat)!=null?we:{},v=(ke=m.enabled)!=null?ke:!0,x=(Pe=m.placement)!=null?Pe:"inline",T=null,S=null;if(v){let Le=mi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=Le.button,S=Le.wrapper,x==="top-right"&&(S.style.right="48px"),x==="inline"&&r.appendChild(S)}let W=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:O}=ui(t,{showClose:n,wrapperClassName:W});return a!=="top-right"&&r.appendChild(O),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:I,closeButtonWrapper:O,clearChatButton:T,clearChatButtonWrapper:S}},No=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function co(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(ao)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let T=be(m.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",T=>{T.stopPropagation(),u(),n(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function _t(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=be(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function oa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let f=be(t,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=n,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function sa(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of t){let p;u.icon?p=_t({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function gi(e){var m,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let u=h("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let p=be(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,T;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(T=d.border)!=null?T:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=co({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let T=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",T?"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 il=e=>{var r;let t=_r({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function rf(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=be(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=co({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ll=e=>{var W,I,O,P,C,R,_,$,D;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(W=t==null?void 0:t.launcher)!=null?W:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=gi({label:(I=a.title)!=null?I:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,u=(O=l.querySelector(".persona-combo-btn-label"))!=null?O: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=Mn.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(u),rf(l,s==null?void 0:s.trailingActions,(C=s==null?void 0:s.onAction)!=null?C:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||z()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let U=s==null?void 0:s.titleRowHover;U&&(l.style.borderRadius=(R=U.borderRadius)!=null?R:"10px",l.style.padding=(_=U.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 z,oe;l.style.backgroundColor=(z=U.background)!=null?z:"",l.style.borderColor=(oe=U.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=($=a.closeButtonSize)!=null?$:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Mn.actionIconColor;let v=(D=a.closeButtonIconName)!=null?D:"x",x=be(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let T=h("div");T.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:S,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},fi={default:il,minimal:ll},cl=e=>{var t;return(t=fi[e])!=null?t:fi.default},ls=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=cl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var hi=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},yi=e=>{var P,C,R,_,$,D,U,z,oe,We,He,Oe;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",s=t.iconName,o=(_=t.stopIconName)!=null?_:"square",a=($=t.tooltipText)!=null?$:"Send message",i=(D=t.stopTooltipText)!=null?D:"Stop generating",d=(z=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?z:"Send",l=(We=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?We:"Stop",u=(He=t.showTooltip)!=null?He:!1,p=(Oe=t.size)!=null?Oe:"40px",f=t.backgroundColor,m=t.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let T=null,S=null;if(n){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let de=parseFloat(p)||24,we=(m==null?void 0:m.trim())||"currentColor";s?(T=be(s,de,we,2),T?x.appendChild(T):x.textContent=r):x.textContent=r,S=be(o,de,we,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let W=null;u&&a&&(W=h("div","persona-send-button-tooltip"),W.textContent=a,v.appendChild(W)),x.setAttribute("aria-label",a),v.appendChild(x);let I="send";return{button:x,wrapper:v,setMode:de=>{if(de===I)return;I=de;let we=de==="stop"?i:a;if(x.setAttribute("aria-label",we),W&&(W.textContent=we),n){if(T&&S){let ke=de==="stop"?S:T;x.replaceChildren(ke)}}else x.textContent=de==="stop"?l:d}}},bi=e=>{var W,I,O,P,C,R,_,$,D,U,z,oe;let t=(W=e==null?void 0:e.voiceRecognition)!=null?W:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((I=t.provider)==null?void 0:I.type)==="runtype";if(!(r||s))return null;let a=(P=(O=e==null?void 0:e.sendButton)==null?void 0:O.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=(C=t.iconName)!=null?C:"mic",u=(R=t.iconSize)!=null?R:a,p=parseFloat(u)||24,f=($=t.backgroundColor)!=null?$:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,m=(U=t.iconColor)!=null?U:(D=e==null?void 0:e.sendButton)==null?void 0:D.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=be(l,p,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let T=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&T){let We=h("div","persona-send-button-tooltip");We.textContent=T,i.appendChild(We)}return{button:d,wrapper:i}},xi=e=>{var v,x,T,S,W,I,O,P;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(T=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?T:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((S=t.allowedTypes)!=null?S:Fr).join(","),s.multiple=((W=t.maxFiles)!=null?W:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(I=t.buttonTooltipText)!=null?I:"Attach file");let i=(O=t.buttonIconName)!=null?O:"paperclip",d=n,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=be(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",C=>{C.preventDefault(),s.click()}),o.appendChild(a);let f=(P=t.buttonTooltipText)!=null?P:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},vi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},wi=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var cs=e=>{var v,x,T,S,W,I;let{config:t}=e,n=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let r=wi(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=hi(t);a();let i=yi(t),d=bi(t),l=xi(t),u=vi(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),p.append(f,m),s.append(p),s.addEventListener("click",O=>{O.target!==i.button&&O.target!==i.wrapper&&O.target!==(d==null?void 0:d.button)&&O.target!==(d==null?void 0:d.wrapper)&&O.target!==(l==null?void 0:l.button)&&O.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,u),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(W=l==null?void 0:l.input)!=null?W:null,attachmentPreviewsContainer:(I=l==null?void 0:l.previewsContainer)!=null?I:null,actionsRow:p,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var Bu=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=h("span","persona-pill-peek__icon"),n=be("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=be("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},Du=e=>{var v,x,T,S,W,I;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=wi();r.style.display="none";let s=vi(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=hi(t);o.style.maxHeight="100px",a();let i=yi(t),d=bi(t),l=xi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",O=>{O.target!==i.button&&O.target!==i.wrapper&&O.target!==(d==null?void 0:d.button)&&O.target!==(d==null?void 0:d.wrapper)&&O.target!==(l==null?void 0:l.button)&&O.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&n.append(l.previewsContainer),n.append(u,r,s);let m=u;return{footer:n,suggestions:r,composerForm:u,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(W=l==null?void 0:l.input)!=null?W:null,attachmentPreviewsContainer:(I=l==null?void 0:l.previewsContainer)!=null?I:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Nu=e=>{var u,p,f,m,v,x,T,S,W,I,O,P,C,R,_,$,D;let t=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,n=on(e);if(lo(e)){let U=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},z=h("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(v=U.expandedSize)!=null?v:"anchored",z.style.zIndex=String((T=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?T:yn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let We=h("div","persona-widget-pill-root");return We.setAttribute("data-persona-composer-bar",""),We.dataset.state="collapsed",We.dataset.expandedSize=(S=U.expandedSize)!=null?S:"anchored",We.style.zIndex=String((I=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?I:yn),{wrapper:z,panel:oe,pillRoot:We}}if(n){let U=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(z),{wrapper:U,panel:z}}if(!t){let U=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(P=(O=e==null?void 0:e.launcher)==null?void 0:O.width)!=null?P:"100%";return U.style.width=oe,z.style.width="100%",U.appendChild(z),{wrapper:U,panel:z}}let s=(C=e==null?void 0:e.launcher)!=null?C:{},o=s.position&&xr[s.position]?xr[s.position]:xr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((_=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?_:yn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(D=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?D:e==null?void 0:e.launcherWidth,l=d!=null?d:Xn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},of=(e,t)=>{var O,P,C,R,_,$,D,U,z;let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=ui(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(C=(P=(O=e==null?void 0:e.launcher)==null?void 0:O.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(o){let oe=mi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(_=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?_:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(D=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",u.append(p,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let T=h("div","persona-composer-overlay persona-pointer-events-none");T.setAttribute("data-persona-composer-overlay",""),T.style.position="absolute",T.style.left="0",T.style.right="0",T.style.bottom="0",T.style.zIndex="20";let S=Du({config:e}),{root:W,textNode:I}=Bu();return n.append(d,s,l,T),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:T,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:s,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:W,peekTextNode:I}},Ou=(e,t=!0)=>{var T,S,W,I,O,P,C,R,_;if(lo(e))return of(e,t);let n=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let r=(T=e==null?void 0:e.layout)==null?void 0:T.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=r?ls(e,r,{showClose:t}):_r({config:e,showClose:t}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(I=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?I:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(P=(O=e==null?void 0:e.copy)==null?void 0:O.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=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=cs({config:e}),v=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;s?No(n,o,e):(o.header.style.display="none",No(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(m.footer.style.display="none"),n.append(m.footer),n.append(x),{container:n,body:a,messagesWrapper:u,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var sf=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}},af=(e,t)=>{if(!e)return null;let n=sf(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},lf=(e,t)=>{let n=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},cf=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},dl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},pl=320,_u=320,df=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),pf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),uf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),mf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),gf=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${pl}px`,l.style.maxHeight=`${_u}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),cf(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},ff=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!dl(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${pl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},hf=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!dl(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${pl}px`,s.style.maxHeight=`${_u}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},yf=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!dl(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Oo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},ul=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Oo};if(t){let s=t(r);if(s!==null)return s}return Oo()},bf=(e,t)=>{let n=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Fu=(e,t)=>{let n=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},xf=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},ml=(e,t,n)=>{var m,v,x,T,S,W;let r=(m=t.showCopy)!=null?m:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let I=h("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let a=(T=t.visibility)!=null?T:"hover",i=(S=t.align)!=null?S:"right",d=(W=t.layout)!=null?W:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(I,O,P)=>{let C=_t({icon:I,label:O,size:14,className:"persona-message-action-btn"});return C.setAttribute("data-action",P),C};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},ds=(e,t,n,r,s,o)=>{var re,Le,K,ue,he,ge,me,Xe,V,ne,Re,fe,le,ie,Ye,Ae,pe;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,l=a.timestamp,u=(Le=d==null?void 0:d.show)!=null?Le:!1,p=(K=l==null?void 0:l.show)!=null?K:!1,f=(ue=d==null?void 0:d.position)!=null?ue:"left",m=(he=l==null?void 0:l.position)!=null?he:"below",v=xf(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=df(e),S=(me=(ge=e.content)==null?void 0:ge.trim())!=null?me:"",I=T.length>0&&S===Va,O=li((V=(Xe=o==null?void 0:o.widgetConfig)==null?void 0:Xe.features)==null?void 0:V.streamAnimation),P=(fe=(Re=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.features)==null?void 0:Re.streamAnimation)==null?void 0:fe.plugins,C=e.role==="assistant"&&O.type!=="none"?Zs(O.type,P):null,R=e.role==="assistant"&&((le=C==null?void 0:C.isAnimating)==null?void 0:le.call(C,e))===!0,_=e.role==="assistant"&&C!==null&&(!!e.streaming||R);_&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),_&&C&&(C.containerClass&&$.classList.add(C.containerClass),$.style.setProperty("--persona-stream-step",`${O.speed}ms`),$.style.setProperty("--persona-stream-duration",`${O.duration}ms`));let D=_?ci((ie=e.content)!=null?ie:"",O.buffer,C,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",U=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=U;_&&(C==null?void 0:C.wrap)==="char"?z=ea(U,"char",e.id,{skipTags:C.skipTags}):_&&(C==null?void 0:C.wrap)==="word"&&(z=ea(U,"word",e.id,{skipTags:C.skipTags}));let oe=null;if(I?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",$.appendChild(oe)):$.innerHTML=z,_&&(C!=null&&C.useCaret)&&!I&&S){let Q=di(),je=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),At=je[je.length-1];if(At!=null&&At.parentNode)At.parentNode.insertBefore(Q,At.nextSibling);else{let X=$.lastElementChild;X?X.appendChild(Q):$.appendChild(Q)}}if(p&&m==="inline"&&e.createdAt){let Q=Fu(e,l);Q.classList.add("persona-ml-2","persona-inline"),$.appendChild(Q)}if(T.length>0){let Q=gf(T,!I&&!!S,()=>{I&&oe&&(oe.style.display="")});Q?x.appendChild(Q):I&&oe&&(oe.style.display="")}let We=pf(e);if(We.length>0){let Q=ff(We);Q&&x.appendChild(Q)}let He=uf(e);if(He.length>0){let Q=hf(He);Q&&x.appendChild(Q)}let Oe=mf(e);if(Oe.length>0){let Q=yf(Oe);Q&&x.appendChild(Q)}if(x.appendChild($),p&&m==="below"&&e.createdAt){let Q=Fu(e,l);Q.classList.add("persona-mt-1"),x.appendChild(Q)}let de=e.role==="assistant"?af(e.stopReason,(pe=(Ae=o==null?void 0:o.widgetConfig)==null?void 0:Ae.copy)==null?void 0:pe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(D&&D.trim()),je=O.placeholder==="skeleton",At=je&&O.buffer==="line"&&Q;if(Q)At&&x.appendChild(ta());else if(je)x.appendChild(ta());else{let X=ul("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);X&&x.appendChild(X)}}if(de&&e.stopReason&&!e.streaming&&(S||($.style.display="none"),x.appendChild(lf(e.stopReason,de))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=ml(e,r,s);x.appendChild(Q)}if(!u||e.role==="system")return x;let ke=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Pe=bf(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ke.append(x,Pe):ke.append(Pe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ke},$u=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ds(e,t,n,r,s,o)};var ps=new Set,vf=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),wf=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
24
- `):""},ju=(e,t)=>{let n=ps.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=be(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},gl=(e,t)=>{var He,Oe,de,we,ke,Pe,re,Le,K,ue,he;let n=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Oe=(He=t==null?void 0:t.features)==null?void 0:He.reasoningDisplay)!=null?Oe:{},o=s.expandable!==!1,a=o&&ps.has(e.id),i=n.status!=="complete",d=wf(e,(de=s.previewMaxLines)!=null?de:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(we=t==null?void 0:t.reasoning)!=null?we:{},v=String((ke=n.startedAt)!=null?ke:Date.now()),x=()=>{let ge=h("span","");return ge.setAttribute("data-tool-elapsed",v),ge.textContent=Oa(n),ge},T=(Pe=m.renderCollapsedSummary)==null?void 0:Pe.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Oa(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(p.textContent=T,u.appendChild(p)):T instanceof HTMLElement?u.appendChild(T):(p.textContent=f,u.appendChild(p));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=eu(n),u.appendChild(S);let W=(re=s.loadingAnimation)!=null?re:"none",I=m.activeTextTemplate,O=m.completeTextTemplate,P=i?I:O,C=T instanceof HTMLElement,R=(ge,me,Xe)=>{let V=Xe;for(let ne of me){let Re=h("span","persona-tool-char");Re.style.setProperty("--char-index",String(V)),Re.textContent=ne===" "?"\xA0":ne,ge.appendChild(Re),V++}return V},_=(ge,me)=>{p.textContent="";let Xe=Fa(ge,""),V=0;for(let ne of Xe){let Re=ne.styles.length>0?(()=>{let fe=h("span",ne.styles.map(le=>`persona-tool-text-${le}`).join(" "));return p.appendChild(fe),fe})():p;if(ne.isDuration&&i)Re.appendChild(x());else{let fe=ne.isDuration?Oa(n):ne.text;me?V=R(Re,fe,V):Re.appendChild(document.createTextNode(fe))}}};if(!C&&P)if(S.style.display="none",p.style.display="",i&&W!=="none"){let ge=(Le=m.loadingAnimationDuration)!=null?Le:2e3;p.setAttribute("data-preserve-animation","true"),W==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),_(P,!1)):(p.classList.add(`persona-tool-loading-${W}`),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),W==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),_(P,!0))}else _(P,!1);else if(!C&&i&&W!=="none"){p.style.display="";let ge=(K=m.loadingAnimationDuration)!=null?K:2e3;if(p.setAttribute("data-preserve-animation","true"),W==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`);else{p.classList.add(`persona-tool-loading-${W}`),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),W==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let me=p.textContent||f;p.textContent="",R(p,me,0)}n.status==="complete"&&(p.style.display="none")}else C||(n.status==="complete"?p.style.display="none":p.style.display="");let $=null;if(o){$=h("div","persona-flex persona-items-center");let me=be(a?"chevron-up":"chevron-down",16,"currentColor",2);me?$.appendChild(me):$.textContent=a?"Hide":"Show";let Xe=h("div","persona-flex persona-items-center persona-ml-auto");Xe.append($),l.append(u,Xe)}else l.append(u);let D=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","reasoning"),D.style.display="none",D.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let ge=(he=(ue=t==null?void 0:t.reasoning)==null?void 0:ue.renderCollapsedPreview)==null?void 0:he.call(ue,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});vf(D,ge)||(D.textContent=d),D.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,D),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let z=n.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let me=be(a?"chevron-up":"chevron-down",16,"currentColor",2);me?$.appendChild(me):$.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",D.style.display=a?"none":D.textContent||D.childNodes.length?"":"none"})(),r.append(l,D,U),r};var us=new Set,Cf=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Af=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
- `);let s=ns(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Sf=(e,t)=>{var u,p,f,m,v;let n=e.toolCall,r=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=Af(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?tu(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Gi(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Gi(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Uu=(e,t,n)=>{var u;let r=us.has(e),s=(u=n==null?void 0:n.toolCall)!=null?u:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=be(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},fl=(e,t)=>{var z,oe,We,He,Oe,de,we,ke,Pe;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!n)return s;let o=(We=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?We:{},a=o.expandable!==!1,i=a&&us.has(e.id),{summary:d,previewText:l,isActive:u}=Sf(e,t),p=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((He=n.startedAt)!=null?He:Date.now()),x=()=>{let re=h("span","");return re.setAttribute("data-tool-elapsed",v),re.textContent=Us(n),re},T=(de=r.renderCollapsedSummary)==null?void 0:de.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Oe=o.collapsedMode)!=null?Oe:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Us(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(m.textContent=T,f.appendChild(m)):T instanceof HTMLElement?f.appendChild(T):(m.textContent=d,f.appendChild(m));let S=(we=o.loadingAnimation)!=null?we:"none",W=r.activeTextTemplate,I=r.completeTextTemplate,O=u?W:I,P=T instanceof HTMLElement,C=(re,Le,K)=>{let ue=K;for(let he of Le){let ge=h("span","persona-tool-char");ge.style.setProperty("--char-index",String(ue)),ge.textContent=he===" "?"\xA0":he,re.appendChild(ge),ue++}return ue},R=(re,Le)=>{var ge;m.textContent="";let K=((ge=n.name)==null?void 0:ge.trim())||"tool",ue=Fa(re,K),he=0;for(let me of ue){let Xe=me.styles.length>0?(()=>{let V=h("span",me.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return m.appendChild(V),V})():m;if(me.isDuration&&u)Xe.appendChild(x());else{let V=me.isDuration?Us(n):me.text;Le?he=C(Xe,V,he):Xe.appendChild(document.createTextNode(V))}}};if(!P)if(u&&S!=="none"){let re=(ke=r.loadingAnimationDuration)!=null?ke:2e3;if(m.setAttribute("data-preserve-animation","true"),S==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),O&&R(O,!1);else if(m.classList.add(`persona-tool-loading-${S}`),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),O)R(O,!0);else{let Le=m.textContent||d;m.textContent="",C(m,Le,0)}}else O&&R(O,!1);let _=null;if(a){_=h("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"currentColor",Le=be(i?"chevron-up":"chevron-down",16,re,2);Le?_.appendChild(Le):_.textContent=i?"Hide":"Show";let K=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(_),p.append(f,K)}else p.append(f);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let re=(Pe=r.renderCollapsedPreview)==null?void 0:Pe.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});Cf($,re)||($.textContent=l),$.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,$),s;let D=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(D.style.display=i?"":"none",r.contentBackgroundColor&&(D.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(D.style.color=r.contentTextColor),r.contentPaddingX&&(D.style.paddingLeft=r.contentPaddingX,D.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(D.style.paddingTop=r.contentPaddingY,D.style.paddingBottom=r.contentPaddingY),n.name){let re=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=n.name,D.appendChild(re)}if(n.args!==void 0){let re=h("div","persona-space-y-1"),Le=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Le.style.color=r.labelTextColor),Le.textContent="Arguments";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(n.args),re.append(Le,K),D.appendChild(re)}if(n.chunks&&n.chunks.length){let re=h("div","persona-space-y-1"),Le=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Le.style.color=r.labelTextColor),Le.textContent="Activity";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=n.chunks.join(""),re.append(Le,K),D.appendChild(re)}if(n.status==="complete"&&n.result!==void 0){let re=h("div","persona-space-y-1"),Le=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Le.style.color=r.labelTextColor),Le.textContent="Result";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(n.result),re.append(Le,K),D.appendChild(re)}if(n.status==="complete"&&typeof n.duration=="number"){let re=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${n.duration}ms`,D.appendChild(re)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"currentColor",Le=be(i?"chevron-up":"chevron-down",16,re,2);Le?_.appendChild(Le):_.textContent=i?"Hide":"Show"}D.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(p,$,D),s};var po=require("partial-json");var yl="ask_user_question",hl=8,ms="data-persona-ask-sheet-for",Ef="Other",Tf="Other\u2026",zu="Type your own answer here",Vu="Send",Mf="Next",kf="Back",Lf="Submit all",Pf="Skip",If=3,bl="data-ask-current-index",xl="data-ask-question-count",Ku="data-ask-answers",vl="data-ask-grouped",Ju="data-ask-layout",Wf=e=>e.layout==="pills"?"pills":"rows",Rf=e=>e.getAttribute(Ju)==="pills"?"pills":"rows",qu=!1,Gu=e=>e.replace(/["\\]/g,"\\$&"),$r=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===yl,Ci=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},jr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=(0,po.parse)(s,po.STR|po.OBJ|po.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},aa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>hl&&!qu&&(qu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${hl}.`)),t.slice(0,hl)},Hf=e=>{var t;return(t=aa(e)[0])!=null?t:null},Bf=(e,t)=>{var n;return(n=aa(e)[t])!=null?n:null},Xu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Qu=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Df=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Qu(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Nf=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Of=(e,t,n,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<If;m++)o.appendChild(Nf(r));return o}if(d.forEach((m,v)=>{o.appendChild(Df(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?Ef:Tf;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=t.freeTextPlaceholder)!=null?u:zu,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:m),x.appendChild(T),v.appendChild(x);let S=Qu(r,a,d.length);S&&v.appendChild(S),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=t.freeTextLabel)!=null?f:m,o.appendChild(v)}}return o},Yu=(e,t)=>{var o,a;let r=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:zu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Vu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Ff=e=>{var r;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Vu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},_f=(e,t,n)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:kf,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:Pf,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:Lf:(f=n.nextLabel)!=null?f:Mf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Fo=e=>{let t=e.getAttribute(Ku);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zu=(e,t)=>{e.setAttribute(Ku,JSON.stringify(t))},lr=e=>{var n;let t=Number((n=e.getAttribute(bl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},$f=(e,t)=>{e.setAttribute(bl,String(Math.max(0,Math.floor(t))))},gs=e=>{var n;let t=Number((n=e.getAttribute(xl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},uo=e=>e.getAttribute(vl)==="true",jf=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Uf=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ai=(e,t)=>{let{payload:n}=jr(t),r=aa(n),s=Fo(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},em=e=>{let t=Fo(e),n=lr(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},tm=e=>{if(!uo(e))return;let t=Fo(e),n=lr(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},wl=(e,t,n)=>{let r=Ci(n),s=Rf(e),{payload:o,complete:a}=jr(t),i=uo(e),d=lr(e),l=gs(e),u=i?Bf(o,d):Hf(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let W=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=W,v.classList.toggle("persona-ask-question-skeleton",!W&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let W=Of(u,r,a,s);x.replaceWith(W)}if(s!=="rows"){let W=e.querySelector('[data-ask-free-text-row="true"]');W&&W.replaceWith(Yu(r,s))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!T?e.appendChild(Ff(r)):(!p||i)&&T&&T.remove(),e.setAttribute("data-multi-select",p?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let W=_f(d,l,r);S?S.replaceWith(W):e.appendChild(W)}else S&&S.remove();em(e),tm(e)},qf=(e,t,n)=>{let r=Ci(t),s=Wf(r),o=e.toolCall.id,a=aa(n),i=Math.max(1,a.length),d=i>1,l=jf(e,a),u=d?Uf(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(ms,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(xl,String(i)),p.setAttribute(bl,String(u)),p.setAttribute(vl,d?"true":"false"),p.setAttribute(Ju,s),Zu(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`),Xu(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),p.appendChild(f);let T=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),p.appendChild(T),s!=="rows"&&p.appendChild(Yu(r,s)),wl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},zf=(e,t,n)=>{let{payload:r}=jr(t),s=Math.max(1,aa(r).length);s>gs(e)&&(e.setAttribute(xl,String(s)),s>1&&!uo(e)&&e.setAttribute(vl,"true")),wl(e,t,n)},nm=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Ci(t);Xu(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=jr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},fs=(e,t,n)=>{if(!n||!$r(e)||Ci(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==s&&l.remove()});let a=n.querySelector(`[${ms}="${Gu(s)}"]`);if(a){zf(a,e,t);return}let{payload:i}=jr(e),d=qf(e,t,i);n.appendChild(d)},mo=(e,t)=>{if(!e)return;let n=t?`[${ms}="${Gu(t)}"]`:`[${ms}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Cl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),go=(e,t)=>{let n=Fo(e),r=lr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Zu(e,n),em(e),tm(e)},Si=(e,t,n,r)=>{let s=gs(e),o=Math.max(0,Math.min(s-1,r));$f(e,o),wl(e,t,n)};var Al=(e,t)=>{var x,T,S,W,I,O,P,C,R,_,$,D;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(T=r==null?void 0:r.borderColor)!=null?T:"var(--persona-approval-border, #fef08a)",!n)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=r==null?void 0:r.titleColor)!=null?S:"currentColor",u=be(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(W=r==null?void 0:r.title)!=null?W:"Approval Required",f.appendChild(m),!s){let U=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");U.setAttribute("data-approval-status",n.status),n.status==="approved"?(U.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",U.style.color="var(--persona-palette-colors-success-700, #15803d)",U.textContent="Approved"):n.status==="denied"?(U.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",U.style.color="var(--persona-palette-colors-error-700, #b91c1c)",U.textContent="Denied"):n.status==="timeout"&&(U.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",U.style.color="var(--persona-palette-colors-warning-700, #b45309)",U.textContent="Timeout"),f.appendChild(U)}p.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=n.description,p.appendChild(v),n.parameters){let U=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&&(U.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(U.style.color=r.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=ns(n.parameters),p.appendChild(U)}if(s){let U=h("div","persona-flex persona-gap-2 persona-mt-2");U.setAttribute("data-approval-buttons","true");let z=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");z.type="button",z.style.backgroundColor=(I=r==null?void 0:r.approveButtonColor)!=null?I:"var(--persona-approval-approve-bg, #22c55e)",z.style.color=(O=r==null?void 0:r.approveButtonTextColor)!=null?O:"#ffffff",z.setAttribute("data-approval-action","approve");let oe=be("shield-check",14,(P=r==null?void 0:r.approveButtonTextColor)!=null?P:"#ffffff",2);oe&&(oe.style.marginRight="4px",z.appendChild(oe));let We=document.createTextNode((C=r==null?void 0:r.approveLabel)!=null?C:"Approve");z.appendChild(We);let He=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");He.type="button",He.style.backgroundColor=(R=r==null?void 0:r.denyButtonColor)!=null?R:"transparent",He.style.color=(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",He.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,He.setAttribute("data-approval-action","deny");let Oe=be("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);Oe&&(Oe.style.marginRight="4px",He.appendChild(Oe));let de=document.createTextNode((D=r==null?void 0:r.denyLabel)!=null?D:"Deny");He.appendChild(de),U.append(z,He),p.appendChild(U)}return a.append(i,p),o.appendChild(a),o};var rm=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(v),t.push(v)}),e.appendChild(u)}}};var ia=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var la=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Vf=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Kf=new Set(["step_start","execution_start"]),Jf=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Gf=new Set(["step_complete","agent_turn_complete"]),Xf=new Set(["flow_complete","agent_complete"]),om=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),am=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,_o=(e,t)=>{let n=e[t];return am(n)?n:void 0};function Sl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ei(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Qf(e,t){return typeof t.type=="string"?t.type:e}function Yf(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Zf(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function sm(e){var r,s,o,a,i;let t=_o(e,"result"),n=[_o(e,"tokens"),_o(e,"totalTokens"),t?_o(t,"tokens"):void 0,_o(e,"usage"),t?_o(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?s:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Qn(e.outputTokens))!=null?o:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function eh(e){var n,r,s,o,a;let t=_o(e,"result");return(a=(s=(r=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?r:Qn(e.execution_time))!=null?s:Qn(e.duration))!=null?a:t?(o=Qn(t.executionTime))!=null?o:Qn(t.executionTimeMs):void 0}function th(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ca=class{constructor(t=th){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ei(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!am(n)){om.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Qf(t,n),s=this.now();if(Vf.has(r)){this.startRun(s);return}if(Kf.has(r)){this.run||this.startRun(s);return}if(Jf.has(r)){if(!Zf(r,n))return;let a=Yf(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Sl(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ei(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Gf.has(r)){if(!this.run)return;let a=this.run,i=sm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Sl(a.visibleCharCount),u=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:Ei(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Xf.has(r)){if(!this.run)return;let a=this.run,i=sm(n),d=i!=null?i:a.exactOutputTokens+Sl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:Ei(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(om.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=eh(n);return o!=null?o:r-t.startedAt}};function hs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var nh={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)"}},rh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},oh=["flowName","stepName","reasoningText","text","name","tool","toolName"],sh=100;function ah(e,t){let n={...nh,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return rh}function ih(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function lh(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function ch(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function dh(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function ph(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function uh(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function mh(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function gh(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function El(e,t,n,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");hs(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var z,oe;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=be(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&x.appendChild(T);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),W=(z=r.timestampFormat)!=null?z:"relative";S.textContent=W==="relative"?ih(e.timestamp,n):lh(e.timestamp);let I=null;r.showSequenceNumbers!==!1&&(I=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(t+1));let O=ah(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=O.bg,P.style.color=O.text,P.style.borderColor=O.text+"50",P.textContent=e.type;let C=(oe=r.descriptionFields)!=null?oe:oh,R=ch(e.payload,C),_=null;R&&(_=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=R);let $=h("div","persona-flex-1 persona-min-w-0"),D=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),U=be("clipboard","12px","currentColor",1.5);return U&&D.appendChild(U),D.addEventListener("click",async We=>{We.stopPropagation(),await dh(ph(e)),D.innerHTML="";let He=be("check","12px","currentColor",1.5);He&&D.appendChild(He),setTimeout(()=>{D.innerHTML="";let Oe=be("clipboard","12px","currentColor",1.5);Oe&&D.appendChild(Oe)},1500)}),v.appendChild(x),v.appendChild(S),I&&v.appendChild(I),v.appendChild(P),_&&v.appendChild(_),v.appendChild($),v.appendChild(D),m.appendChild(v),d&&m.appendChild(gh(e,a,i)),m}}function im(e){var v,x,T,S,W;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",p=(W=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?W:{},f=o.find(I=>I.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let I=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(I)return{element:I,update:()=>{},destroy:()=>{}}}return m();function m(){let I=p.classNames,O=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hs(O,I==null?void 0:I.panel);let P=[],C="",R="",_=null,$=[],D={},U=0,z=si(),oe=0,We=0,He=!1,Oe=null,de=!1,we=0,ke=new Set,Pe=new Map,re="",Le="",K=null,ue,he,ge,me,Xe,V=null,ne=null,Re=null;function fe(){let ae=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),xe=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");hs(xe,I==null?void 0:I.headerBar);let Ct=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ct.textContent="Events",ue=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"),ue.textContent="0",a){ne=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Dn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Dn.textContent="Throughput",V=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),V.textContent="-- tok/s",Re=h("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Re.style.display="none",Re.style.pointerEvents="none";let Zn=ne,xn=Re,Nn=()=>{if(!xn.textContent)return;let vr=Zn.getBoundingClientRect(),On=ae.getBoundingClientRect();xn.style.left=`${vr.left-On.left}px`,xn.style.top=`${vr.bottom-On.top+4}px`,xn.style.display="block"},mt=()=>{xn.style.display="none"};ne.addEventListener("mouseenter",Nn),ne.addEventListener("mouseleave",mt),ne.appendChild(Dn),ne.appendChild(V)}let jt=h("div","persona-flex-1");he=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 en=h("option","");en.value="",en.textContent="All events",he.appendChild(en),ge=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ge.type="button",ge.title="Copy All";let Mt=be("clipboard-copy","12px","currentColor",1.5);Mt&&ge.appendChild(Mt);let Et=h("span","persona-text-xs");Et.textContent="Copy All",ge.appendChild(Et),xe.appendChild(Ct),xe.appendChild(ue),ne&&xe.appendChild(ne),xe.appendChild(jt),xe.appendChild(he),xe.appendChild(ge);let yt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hs(yt,I==null?void 0:I.searchBar);let xt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=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");xt&&zt.appendChild(xt),me=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"),hs(me,I==null?void 0:I.searchInput),me.type="text",me.placeholder="Search event payloads...",Xe=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Xe.type="button",Xe.style.display="none";let tt=be("x","12px","currentColor",2);return tt&&Xe.appendChild(tt),yt.appendChild(zt),yt.appendChild(me),yt.appendChild(Xe),ae.appendChild(xe),ae.appendChild(yt),Re&&ae.appendChild(Re),ae}let le,ie=o.find(ae=>ae.renderEventStreamToolbar);if(ie!=null&&ie.renderEventStreamToolbar&&s){let ae=ie.renderEventStreamToolbar({config:s,defaultRenderer:()=>fe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:xe=>{C=xe,Bn(),se()},onSearchChange:xe=>{R=xe,Bn(),se()}});le=ae!=null?ae:fe()}else le=fe();let Ye=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");Ye.style.display="none";function Ae(){if(!a||!V||!ne)return;let ae=a();V.textContent=uh(ae);let xe=mh(ae);Re&&(Re.textContent=xe,xe||(Re.style.display="none")),xe?ne.setAttribute("aria-label",xe):ne.removeAttribute("aria-label")}let pe=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Q=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Q.style.height="100%";let je=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");hs(je,I==null?void 0:I.scrollIndicator),je.style.display="none",je.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let At=be(l,"14px","currentColor",2);At&&je.appendChild(At);let X=h("span","");X.textContent=u,je.appendChild(X);let Fe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Fe.style.display="none",pe.appendChild(Q),pe.appendChild(Fe),pe.appendChild(je),O.setAttribute("tabindex","0"),O.appendChild(le),O.appendChild(Ye),O.appendChild(pe);function kn(){let ae=t.getAll(),xe={};for(let Et of ae)xe[Et.type]=(xe[Et.type]||0)+1;let Ct=Object.keys(xe).sort(),jt=Ct.length!==$.length||!Ct.every((Et,yt)=>Et===$[yt]),en=!jt&&Ct.some(Et=>xe[Et]!==D[Et]),bn=ae.length!==Object.values(D).reduce((Et,yt)=>Et+yt,0);if(!jt&&!en&&!bn||($=Ct,D=xe,!he))return;let Mt=he.value;if(he.options[0].textContent="All events",jt){for(;he.options.length>1;)he.remove(1);for(let Et of Ct){let yt=h("option","");yt.value=Et,yt.textContent=`${Et} (${xe[Et]||0})`,he.appendChild(yt)}Mt&&Ct.includes(Mt)?he.value=Mt:Mt&&(he.value="",C="")}else for(let Et=1;Et<he.options.length;Et++){let yt=he.options[Et];yt.textContent=`${yt.value} (${xe[yt.value]||0})`}}function Ot(){let ae=t.getAll();if(C&&(ae=ae.filter(xe=>xe.type===C)),R){let xe=R.toLowerCase();ae=ae.filter(Ct=>Ct.type.toLowerCase().includes(xe)||Ct.payload.toLowerCase().includes(xe))}return ae}function cn(){return C!==""||R!==""}function Bn(){U=0,oe=0,z.resume(),je.style.display="none"}function Yn(ae){ke.has(ae)?ke.delete(ae):ke.add(ae),K=ae;let xe=Q.scrollTop,Ct=z.isFollowing();de=!0,z.pause(),se(),Q.scrollTop=xe,Ct&&z.resume(),de=!1}function B(){return Xs(Q,50)}function se(){We=Date.now(),He=!1,Ae(),kn();let ae=t.getEvictedCount();ae>0?(Ye.textContent=`${ae.toLocaleString()} older events truncated`,Ye.style.display=""):Ye.style.display="none",P=Ot();let xe=P.length,Ct=t.getSize()>0;ue&&(ue.textContent=String(t.getSize())),xe===0&&Ct&&cn()?(Fe.textContent=R?`No events matching '${R}'`:"No events matching filter",Fe.style.display="",Q.style.display="none"):(Fe.style.display="none",Q.style.display=""),ge&&(ge.title=cn()?`Copy Filtered (${xe})`:"Copy All"),d&&!z.isFollowing()&&xe>U&&(oe+=xe-U,X.textContent=u?`${u}${oe>0?` (${oe})`:""}`:"",je.style.display=""),U=xe;let jt=t.getAll(),en=jt.length>0?jt[0].timestamp:0,bn=new Set(P.map(yt=>yt.id));for(let yt of ke)bn.has(yt)||ke.delete(yt);let Mt=C!==re||R!==Le,Et=Pe.size===0&&P.length>0;if(Mt||Et||P.length===0){Q.innerHTML="",Pe.clear();let yt=document.createDocumentFragment();for(let xt=0;xt<P.length;xt++){let zt=El(P[xt],xt,en,p,ke,Yn,o,s);Pe.set(P[xt].id,zt),yt.appendChild(zt)}Q.appendChild(yt),re=C,Le=R,K=null}else{if(K!==null){let xt=Pe.get(K);if(xt&&xt.parentNode===Q){let zt=P.findIndex(tt=>tt.id===K);if(zt>=0){let tt=El(P[zt],zt,en,p,ke,Yn,o,s);Q.insertBefore(tt,xt),xt.remove(),Pe.set(K,tt)}}K=null}let yt=new Set(P.map(xt=>xt.id));for(let[xt,zt]of Pe)yt.has(xt)||(zt.remove(),Pe.delete(xt));for(let xt=0;xt<P.length;xt++){let zt=P[xt];if(!Pe.has(zt.id)){let tt=El(zt,xt,en,p,ke,Yn,o,s);Pe.set(zt.id,tt),Q.appendChild(tt)}}}z.isFollowing()&&(Q.scrollTop=Q.scrollHeight)}function De(){if(Date.now()-We>=sh){Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),se();return}He||(He=!0,Oe=requestAnimationFrame(()=>{Oe=null,se()}))}let Qe=(ae,xe)=>{if(!ge)return;ge.innerHTML="";let Ct=be(ae,"12px","currentColor",1.5);Ct&&ge.appendChild(Ct);let jt=h("span","persona-text-xs");jt.textContent="Copy All",ge.appendChild(jt),setTimeout(()=>{ge.innerHTML="";let en=be("clipboard-copy","12px","currentColor",1.5);en&&ge.appendChild(en);let bn=h("span","persona-text-xs");bn.textContent="Copy All",ge.appendChild(bn),ge.disabled=!1},xe)},_e=async()=>{if(ge){ge.disabled=!0;try{let ae;cn()?ae=P:n?(ae=await n(),ae.length===0&&(ae=t.getAll())):ae=t.getAll();let xe=ae.map(Ct=>{try{return JSON.parse(Ct.payload)}catch{return Ct.payload}});await navigator.clipboard.writeText(JSON.stringify(xe,null,2)),Qe("check",1500)}catch{Qe("x",1500)}}},$e=()=>{he&&(C=he.value,Bn(),se())},ot=()=>{!me||!Xe||(Xe.style.display=me.value?"":"none",_&&clearTimeout(_),_=setTimeout(()=>{R=me.value,Bn(),se()},150))},St=()=>{!me||!Xe||(me.value="",R="",Xe.style.display="none",_&&clearTimeout(_),Bn(),se())},$t=()=>{if(de)return;let ae=Q.scrollTop,{action:xe,nextLastScrollTop:Ct}=ai({following:z.isFollowing(),currentScrollTop:ae,lastScrollTop:we,nearBottom:B(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});we=Ct,xe==="resume"?(z.resume(),oe=0,je.style.display="none"):xe==="pause"&&(z.pause(),d&&(X.textContent=u,je.style.display=""))},Jt=ae=>{let xe=ii({following:z.isFollowing(),deltaY:ae.deltaY,nearBottom:B(),resumeWhenNearBottom:!0});xe==="pause"?(z.pause(),d&&(X.textContent=u,je.style.display="")):xe==="resume"&&(z.resume(),oe=0,je.style.display="none")},J=()=>{d&&(Q.scrollTop=Q.scrollHeight,z.resume(),oe=0,je.style.display="none")},ft=ae=>{let xe=ae.target;if(!xe||xe.closest("button"))return;let Ct=xe.closest("[data-event-id]");if(!Ct)return;let jt=Ct.getAttribute("data-event-id");jt&&Yn(jt)},rt=ae=>{if((ae.metaKey||ae.ctrlKey)&&ae.key==="f"){ae.preventDefault(),me==null||me.focus(),me==null||me.select();return}ae.key==="Escape"&&(me&&document.activeElement===me?(St(),me.blur(),O.focus()):r&&r())};ge&&ge.addEventListener("click",_e),he&&he.addEventListener("change",$e),me&&me.addEventListener("input",ot),Xe&&Xe.addEventListener("click",St),Q.addEventListener("scroll",$t),Q.addEventListener("wheel",Jt,{passive:!0}),Q.addEventListener("click",ft),je.addEventListener("click",J),O.addEventListener("keydown",rt);function qt(){_&&clearTimeout(_),Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),He=!1,Pe.clear(),ge&&ge.removeEventListener("click",_e),he&&he.removeEventListener("change",$e),me&&me.removeEventListener("input",ot),Xe&&Xe.removeEventListener("click",St),Q.removeEventListener("scroll",$t),Q.removeEventListener("wheel",Jt),Q.removeEventListener("click",ft),je.removeEventListener("click",J),O.removeEventListener("keydown",rt)}return{element:O,update:De,destroy:qt}}}function lm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(l.append(u,p),i.append(d,l),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var cm=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>lm(e,t)});if(u)return u}return lm(e,t)};var Tl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Ur=new Tl;Ur.register("PersonaArtifactCard",cm);function fh(e){var s;let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function dm(e,t){var he,ge,me,Xe;let n=(ge=(he=e.features)==null?void 0:he.artifacts)==null?void 0:ge.layout,s=((me=n==null?void 0:n.toolbarPreset)!=null?me:"default")==="document",o=(Xe=n==null?void 0:n.panePadding)==null?void 0:Xe.trim(),a=e.markdown?Lo(e.markdown):null,i=es(e.sanitize),d=V=>{let ne=a?a(V):Po(V);return i?i(ne):ne},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};l&&l.addEventListener("click",()=>{var V;u(),(V=t.onDismiss)==null||V.call(t)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var V;u(),(V=t.onDismiss)==null||V.call(t)});let x="rendered",T=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?_t({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):_t({icon:"eye",label:"Rendered view"}),W=s?_t({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):_t({icon:"code-2",label:"Source"}),I=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),O=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,R=!!(P&&C&&C.length>0),_=null,$,D=null,U=null;if(s&&(O||P)&&!R){if($=O?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let V=be("chevron-down",14,"currentColor",2);V&&$.appendChild(V)}}else s&&R?(_=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=O?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=_t({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),_.append($,D)):s?$=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=_t({icon:"copy",label:"Copy"});let z=s?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"}),oe=s?_t({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:"Close"}),We=()=>{var le,ie,Ye;let V=(le=Pe.find(Ae=>Ae.id===re))!=null?le:Pe[Pe.length-1],ne=(ie=V==null?void 0:V.id)!=null?ie:null,Re=(V==null?void 0:V.artifactType)==="markdown"&&(Ye=V.markdown)!=null?Ye:"",fe=V?JSON.stringify({component:V.component,props:V.props},null,2):"";return{markdown:Re,jsonPayload:fe,id:ne}},He=async()=>{var le;let{markdown:V,jsonPayload:ne}=We(),Re=(le=Pe.find(ie=>ie.id===re))!=null?le:Pe[Pe.length-1],fe=(Re==null?void 0:Re.artifactType)==="markdown"?V:Re?ne:"";try{await navigator.clipboard.writeText(fe)}catch{}};if($.addEventListener("click",async()=>{let V=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(V&&R){let{markdown:ne,jsonPayload:Re,id:fe}=We();try{await V({actionId:"primary",artifactId:fe,markdown:ne,jsonPayload:Re})}catch{}return}await He()}),D&&(C!=null&&C.length)){let V=()=>{var Re;return(Re=p.closest("[data-persona-root]"))!=null?Re:document.body},ne=()=>{U=co({items:C.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:fe,jsonPayload:le,id:ie}=We(),Ye=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ye?await Ye({actionId:Re,artifactId:ie,markdown:fe,jsonPayload:le}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(fe):Re==="json"||Re==="source"?await navigator.clipboard.writeText(le):await navigator.clipboard.writeText(fe||le)}catch{}},anchor:_!=null?_:D,position:"bottom-right",portal:V()})};p.isConnected?ne():requestAnimationFrame(ne),D.addEventListener("click",Re=>{Re.stopPropagation(),U==null||U.toggle()})}z.addEventListener("click",async()=>{var V;try{await((V=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:V.call(n))}catch{}K()}),oe.addEventListener("click",()=>{var V;u(),(V=t.onDismiss)==null||V.call(t)});let Oe=()=>{s&&(S.setAttribute("aria-pressed",x==="rendered"?"true":"false"),W.setAttribute("aria-pressed",x==="source"?"true":"false"))};S.addEventListener("click",()=>{x="rendered",Oe(),K()}),W.addEventListener("click",()=>{x="source",Oe(),K()});let de=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),T.append(S,W),_?I.append(_,z,oe):I.append($,z,oe),f.append(T,de,I),Oe()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let we=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(we.style.paddingLeft=o,we.style.paddingRight=o,ke.style.padding=o),p.appendChild(f),p.appendChild(we),p.appendChild(ke);let Pe=[],re=null,Le=!1,K=()=>{var fe,le,ie,Ye;let V=s&&Pe.length<=1;we.classList.toggle("persona-hidden",V),we.replaceChildren();for(let Ae of Pe){let pe=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");pe.type="button",pe.textContent=Ae.title||Ae.id.slice(0,8),Ae.id===re&&pe.classList.add("persona-bg-persona-container","persona-border-persona-border"),pe.addEventListener("click",()=>t.onSelect(Ae.id)),we.appendChild(pe)}ke.replaceChildren();let ne=re&&Pe.find(Ae=>Ae.id===re)||Pe[Pe.length-1];if(!ne)return;if(s){let Ae=ne.artifactType==="markdown"?"MD":(fe=ne.component)!=null?fe:"Component",Q=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${Q} \xB7 ${Ae}`}else m.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&x==="source"){let pe=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");pe.textContent=(le=ne.markdown)!=null?le:"",ke.appendChild(pe);return}let Ae=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ae.innerHTML=d((ie=ne.markdown)!=null?ie:""),ke.appendChild(Ae);return}let Re=ne.component?Ur.get(ne.component):void 0;if(Re){let pe={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Q=Re((Ye=ne.props)!=null?Ye:{},pe);if(Q){ke.appendChild(Q);return}}catch{}}ke.appendChild(fh(ne))},ue=()=>{var ne;let V=Pe.length>0;if(p.classList.toggle("persona-hidden",!V),l){let Re=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,le=((ne=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;V&&le&&Le?(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(V){var ne,Re,fe;Pe=V.artifacts,re=(fe=(Re=V.selectedId)!=null?Re:(ne=V.artifacts[V.artifacts.length-1])==null?void 0:ne.id)!=null?fe:null,Pe.length>0&&(Le=!0),K(),ue()},setMobileOpen(V){Le=V,!V&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ue()}}}function cr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function pm(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!cr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function hh(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ti(e,t){var d,l,u,p,f,m,v,x,T,S;if(!cr(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),hh(e),pm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(T=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=n==null?void 0:n.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"),pm(e,t)}var um=["panel","seamless"];function Mi(e,t){var i,d,l,u,p,f;for(let m of um)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!cr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",s=um.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function mm(e,t){var n,r,s;return!t||!cr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function yh(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function bh(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function xh(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function vh(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function gm(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function fm(e,t,n,r,s,o){let a=yh(s,200),i=vh(t,n,r,200);i=Math.max(a,i);let d=bh(o);return d!==null&&(i=Math.min(i,d)),xh(e,a,i)}var hm={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"}},Ml=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,T;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=hm[a])!=null?x:hm.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let 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 C,R;let W=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");W.htmlFor=`${t.id}-${a}-${S.name}`;let I=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");I.textContent=S.label,W.appendChild(I);let O=(C=S.type)!=null?C:"text",P;O==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=O),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=`${t.id}-${a}-${S.name}`,P.name=S.name,P.placeholder=(R=S.placeholder)!=null?R:"",S.required&&(P.required=!0),W.appendChild(P),u.appendChild(W)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(T=i.submitLabel)!=null?T:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async S=>{var P,C;S.preventDefault();let W=(P=n.formEndpoint)!=null?P:"/form",I=new FormData(u),O={};I.forEach((R,_)=>{O[_]=R}),O.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let _=await R.json();f.textContent=(C=_.message)!=null?C:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(R){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var kl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},da=new kl;var ym=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var wh=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Ch=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},pa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wh(e),n=Ch(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Ll=e=>typeof e=="string"?e:e==null?"":String(e),$o={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ll(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=Ll(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Ll(n.text)}}},bm=e=>Array.isArray(e)?e.map(t=>String(t)):[],ua=e=>{let t=new Set(bm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(bm(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ah=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Sh=e=>e.map(t=>({...t,streaming:!1})),Eh=e=>e.map(t=>({...t,status:"complete"})),ki=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Ah(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?Sh(n.messages):void 0,artifacts:n.artifacts?Eh(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var ys=require("partial-json");function Th(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Mh(e,t){if(!Th(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Li(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=(0,ys.parse)(n,ys.STR|ys.OBJ),o=Mh(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function xm(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Pi(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=Ur.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function vm(){let e=Li();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function wm(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Ii(e){let t=wm(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Wi(e){let t=wm(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var kh=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ri(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=kh}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,m.appendChild(x),f.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let C=1;C<=5;C++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${l[C-1]}`),R.title=l[C-1],R.dataset.rating=String(C),R.innerHTML=`
23
+ `,t.addEventListener("click",n);let r=o=>{var I,W,P,w,H,_,$,N,U,z,oe,We,He,Oe;let a=(I=o.launcher)!=null?I:{},i=on(o),d=t.querySelector("[data-role='launcher-title']");if(d){let de=(W=a.title)!=null?W:"Chat Assistant";d.textContent=de,d.setAttribute("title",de)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let de=(P=a.subtitle)!=null?P:"Get answers fast";l.textContent=de,l.setAttribute("title",de)}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 de=(w=a.agentIconSize)!=null?w:"40px";if(p.style.height=de,p.style.width=de,p.innerHTML="",a.agentIconName){let we=parseFloat(de)||24,ke=ye(a.agentIconName,we*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(p.appendChild(ke),p.style.display=""):(p.textContent=(H=a.agentIconText)!=null?H:"\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 de=($=a.agentIconSize)!=null?$:"40px";f.style.height=de,f.style.width=de,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let de=(N=a.callToActionIconSize)!=null?N:"32px";m.style.height=de,m.style.width=de,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let we=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,we=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let ke=parseFloat(de)||24,Pe=Math.max(ke-we,8),re=ye(a.callToActionIconName,Pe,"currentColor",2);re?m.appendChild(re):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let x=a.position&&xr[a.position]?xr[a.position]:xr["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?E:`${v} ${x}`,i||(t.style.zIndex=String((oe=a.zIndex)!=null?oe:bn));let S="1px solid var(--persona-border, #e5e7eb)",R="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=(We=a.border)!=null?We:S,t.style.boxShadow=(He=a.shadow)!=null?He:R,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=(Oe=a.collapsedMaxWidth)!=null?Oe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var of="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ui=(e,n={})=>{var v,E,S,R,I,W;let{showClose:t=!0,wrapperClassName:r=of,buttonSize:s,iconSize:o="28px"}=n,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=s!=null?s:a.closeButtonSize)!=null?E:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(S=a.closeButtonTooltipText)!=null?S:"Close chat",p=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(I=a.closeButtonIconName)!=null?I:"x",m=(W=a.closeButtonIconText)!=null?W:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let x=ye(f,o,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let P=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${P} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let P=null,w=()=>{if(P)return;let _=l.ownerDocument,$=_.body;if(!$)return;P=Tr(_,"div","persona-clear-chat-tooltip"),P.textContent=u;let N=Tr(_,"div");N.className="persona-clear-chat-tooltip-arrow",P.appendChild(N);let U=l.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(ao),P.style.left=`${U.left+U.width/2}px`,P.style.top=`${U.top-8}px`,P.style.transform="translate(-50%, -100%)",$.appendChild(P)},H=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",H),l.addEventListener("focus",w),l.addEventListener("blur",H),d._cleanupTooltip=()=>{H(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",H),l.removeEventListener("focus",w),l.removeEventListener("blur",H)}}return{button:l,wrapper:d}},sf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mi=(e,n={})=>{var P,w,H,_,$,N,U,z,oe,We,He,Oe,de;let{wrapperClassName:t=sf,buttonSize:r,iconSize:s="20px"}=n,a=(w=((P=e==null?void 0:e.launcher)!=null?P:{}).clearChat)!=null?w:{},i=(H=r!=null?r:a.size)!=null?H:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",l=($=a.iconColor)!=null?$:"",u=(N=a.backgroundColor)!=null?N:"",p=(U=a.borderWidth)!=null?U:"",f=(z=a.borderColor)!=null?z:"",m=(oe=a.borderRadius)!=null?oe:"",x=(We=a.paddingX)!=null?We:"",v=(He=a.paddingY)!=null?He:"",E=(Oe=a.tooltipText)!=null?Oe:"Clear chat",S=(de=a.showTooltip)!=null?de:!0,R=h("div",t),I=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");I.style.height=i,I.style.width=i,I.type="button",I.setAttribute("aria-label",E),I.style.color=l||Mn.actionIconColor;let W=ye(d,s,"currentColor",1);if(W&&(W.style.display="block",I.appendChild(W)),u&&(I.style.backgroundColor=u,I.classList.remove("hover:persona-bg-gray-100")),p||f){let we=p||"0px",ke=f||"transparent";I.style.border=`${we} solid ${ke}`,I.classList.remove("persona-border-none")}if(m&&(I.style.borderRadius=m,I.classList.remove("persona-rounded-full")),x&&(I.style.paddingLeft=x,I.style.paddingRight=x),v&&(I.style.paddingTop=v,I.style.paddingBottom=v),R.appendChild(I),S&&E){let we=null,ke=()=>{if(we)return;let re=I.ownerDocument,Le=re.body;if(!Le)return;we=Tr(re,"div","persona-clear-chat-tooltip"),we.textContent=E;let K=Tr(re,"div");K.className="persona-clear-chat-tooltip-arrow",we.appendChild(K);let ue=I.getBoundingClientRect();we.style.position="fixed",we.style.zIndex=String(ao),we.style.left=`${ue.left+ue.width/2}px`,we.style.top=`${ue.top-8}px`,we.style.transform="translate(-50%, -100%)",Le.appendChild(we)},Pe=()=>{we&&we.parentNode&&(we.parentNode.removeChild(we),we=null)};R.addEventListener("mouseenter",ke),R.addEventListener("mouseleave",Pe),I.addEventListener("focus",ke),I.addEventListener("blur",Pe),R._cleanupTooltip=()=>{Pe(),R.removeEventListener("mouseenter",ke),R.removeEventListener("mouseleave",Pe),I.removeEventListener("focus",ke),I.removeEventListener("blur",Pe)}}return{button:I,wrapper:R}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},_r=e=>{var P,w,H,_,$,N,U,z,oe,We,He,Oe,de,we,ke,Pe;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(P=n==null?void 0:n.launcher)!=null?P:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(H=s.closeButtonPlacement)!=null?H:"inline",i=(_=s.headerIconHidden)!=null?_:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let re=parseFloat(o)||24,Le=ye(d,re*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(N=($=n==null?void 0:n.launcher)==null?void 0:$.agentIconText)!=null?N:"\u{1F4AC}"}else if((U=n==null?void 0:n.launcher)!=null&&U.iconUrl){let re=h("img");re.src=n.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=o,re.style.width=o,l.replaceChildren(re)}else l.textContent=(oe=(z=n==null?void 0:n.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=Mn.titleColor,p.textContent=(He=(We=n==null?void 0:n.launcher)==null?void 0:We.title)!=null?He:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Mn.subtitleColor,f.textContent=(de=(Oe=n==null?void 0:n.launcher)==null?void 0:Oe.subtitle)!=null?de:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let m=(we=s.clearChat)!=null?we:{},x=(ke=m.enabled)!=null?ke:!0,v=(Pe=m.placement)!=null?Pe:"inline",E=null,S=null;if(x){let Le=mi(n,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=Le.button,S=Le.wrapper,v==="top-right"&&(S.style.right="48px"),v==="inline"&&r.appendChild(S)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:W}=ui(n,{showClose:t,wrapperClassName:R});return a!=="top-right"&&r.appendChild(W),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:I,closeButtonWrapper:W,clearChatButton:E,clearChatButtonWrapper:S}},No=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function co(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(ao)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of n){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let E=ye(m.icon,16,"currentColor",1.5);E&&x.appendChild(E)}let v=document.createElement("span");v.textContent=m.label,x.appendChild(v),x.addEventListener("click",E=>{E.stopPropagation(),u(),t(m.id)}),a.appendChild(x)}let i=null;function d(){if(!o)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!a.contains(x.target)&&!r.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function _t(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=ye(n,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function oa(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=ye(n,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function sa(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=_t({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function gi(e){var m,x;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let u=h("span","persona-combo-btn-label");u.textContent=n,l.appendChild(u);let p=ye(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=co({items:r,onSelect:v=>{l.setAttribute("aria-expanded","false"),s(v)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",v=>{v.stopPropagation();let E=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),f.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{u.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var il=e=>{var r;let n=_r({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function af(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=ye(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=co({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 ll=e=>{var R,I,W,P,w,H,_,$,N;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(R=n==null?void 0:n.launcher)!=null?R:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=gi({label:(I=a.title)!=null?I:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,u=(W=l.querySelector(".persona-combo-btn-label"))!=null?W: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=Mn.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(u),af(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||z()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let U=s==null?void 0:s.titleRowHover;U&&(l.style.borderRadius=(H=U.borderRadius)!=null?H:"10px",l.style.padding=(_=U.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 z,oe;l.style.backgroundColor=(z=U.background)!=null?z:"",l.style.borderColor=(oe=U.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=($=a.closeButtonSize)!=null?$:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||Mn.actionIconColor;let x=(N=a.closeButtonIconName)!=null?N:"x",v=ye(x,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let E=h("div");E.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:E,headerTitle:u,headerSubtitle:S,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},fi={default:il,minimal:ll},cl=e=>{var n;return(n=fi[e])!=null?n:fi.default},ls=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let x=h("div");return x.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=cl(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var hi=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},bi=e=>{var P,w,H,_,$,N,U,z,oe,We,He,Oe;let n=(P=e==null?void 0:e.sendButton)!=null?P:{},t=(w=n.useIcon)!=null?w:!1,r=(H=n.iconText)!=null?H:"\u2191",s=n.iconName,o=(_=n.stopIconName)!=null?_:"square",a=($=n.tooltipText)!=null?$:"Send message",i=(N=n.stopTooltipText)!=null?N:"Stop generating",d=(z=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?z:"Send",l=(We=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?We:"Stop",u=(He=n.showTooltip)!=null?He:!1,p=(Oe=n.size)!=null?Oe:"40px",f=n.backgroundColor,m=n.textColor,x=h("div","persona-send-button-wrapper"),v=h("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let E=null,S=null;if(t){v.style.width=p,v.style.height=p,v.style.minWidth=p,v.style.minHeight=p,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",m?v.style.color=m:v.style.color="var(--persona-button-primary-fg, #ffffff)";let de=parseFloat(p)||24,we=(m==null?void 0:m.trim())||"currentColor";s?(E=ye(s,de,we,2),E?v.appendChild(E):v.textContent=r):v.textContent=r,S=ye(o,de,we,2),f?v.style.backgroundColor=f:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,m?v.style.color=m:v.classList.add("persona-text-white");n.borderWidth&&(v.style.borderWidth=n.borderWidth,v.style.borderStyle="solid"),n.borderColor&&(v.style.borderColor=n.borderColor),n.paddingX?(v.style.paddingLeft=n.paddingX,v.style.paddingRight=n.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),n.paddingY?(v.style.paddingTop=n.paddingY,v.style.paddingBottom=n.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let R=null;u&&a&&(R=h("div","persona-send-button-tooltip"),R.textContent=a,x.appendChild(R)),v.setAttribute("aria-label",a),x.appendChild(v);let I="send";return{button:v,wrapper:x,setMode:de=>{if(de===I)return;I=de;let we=de==="stop"?i:a;if(v.setAttribute("aria-label",we),R&&(R.textContent=we),t){if(E&&S){let ke=de==="stop"?S:E;v.replaceChildren(ke)}}else v.textContent=de==="stop"?l:d}}},yi=e=>{var R,I,W,P,w,H,_,$,N,U,z,oe;let n=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((I=n.provider)==null?void 0:I.type)==="runtype";if(!(r||s))return null;let a=(P=(W=e==null?void 0:e.sendButton)==null?void 0:W.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=(w=n.iconName)!=null?w:"mic",u=(H=n.iconSize)!=null?H:a,p=parseFloat(u)||24,f=($=n.backgroundColor)!=null?$:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,m=(U=n.iconColor)!=null?U:(N=e==null?void 0:e.sendButton)==null?void 0:N.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let v=ye(l,p,m||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let E=(z=n.tooltipText)!=null?z:"Start voice recognition";if(((oe=n.showTooltip)!=null?oe:!1)&&E){let We=h("div","persona-send-button-tooltip");We.textContent=E,i.appendChild(We)}return{button:d,wrapper:i}},xi=e=>{var x,v,E,S,R,I,W,P;let n=(x=e==null?void 0:e.attachments)!=null?x:{};if(n.enabled!==!0)return null;let t=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((S=n.allowedTypes)!=null?S:Fr).join(","),s.multiple=((R=n.maxFiles)!=null?R:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(I=n.buttonTooltipText)!=null?I:"Attach file");let i=(W=n.buttonIconName)!=null?W:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=ye(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let f=(P=n.buttonTooltipText)!=null?P:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},vi=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},wi=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var cs=e=>{var x,v,E,S,R,I;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=wi(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=hi(n);a();let i=bi(n),d=yi(n),l=xi(n),u=vi(n);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),p.append(f,m),s.append(p),s.addEventListener("click",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,u),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(I=l==null?void 0:l.previewsContainer)!=null?I:null,actionsRow:p,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var Nu=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=ye("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=ye("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},Ou=e=>{var x,v,E,S,R,I;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=wi();r.style.display="none";let s=vi(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=hi(n);o.style.maxHeight="100px",a();let i=bi(n),d=yi(n),l=xi(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",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&t.append(l.previewsContainer),t.append(u,r,s);let m=u;return{footer:t,suggestions:r,composerForm:u,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:s,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(I=l==null?void 0:l.previewsContainer)!=null?I:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Fu=e=>{var u,p,f,m,x,v,E,S,R,I,W,P,w,H,_,$,N;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=on(e);if(lo(e)){let U=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},z=h("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(x=U.expandedSize)!=null?x:"anchored",z.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:bn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let We=h("div","persona-widget-pill-root");return We.setAttribute("data-persona-composer-bar",""),We.dataset.state="collapsed",We.dataset.expandedSize=(S=U.expandedSize)!=null?S:"anchored",We.style.zIndex=String((I=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?I:bn),{wrapper:z,panel:oe,pillRoot:We}}if(t){let U=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(z),{wrapper:U,panel:z}}if(!n){let U=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(P=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?P:"100%";return U.style.width=oe,z.style.width="100%",U.appendChild(z),{wrapper:U,panel:z}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&xr[s.position]?xr[s.position]:xr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((_=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?_:bn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(N=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?N:e==null?void 0:e.launcherWidth,l=d!=null?d:Xn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},lf=(e,n)=>{var W,P,w,H,_,$,N,U,z;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=ui(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(P=(W=e==null?void 0:e.launcher)==null?void 0:W.clearChat)==null?void 0:P.enabled)!=null?w:!0,a=null,i=null;if(o){let oe=mi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(_=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?_:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(N=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",u.append(p,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),x=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let E=h("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let S=Ou({config:e}),{root:R,textNode:I}=Nu();return t.append(d,s,l,E),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:m,composerOverlay:E,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:s,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:R,peekTextNode:I}},_u=(e,n=!0)=>{var E,S,R,I,W,P,w,H,_;if(lo(e))return lf(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=(E=e==null?void 0:e.layout)==null?void 0:E.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=r?ls(e,r,{showClose:n}):_r({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(I=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?I:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(P=(W=e==null?void 0:e.copy)==null?void 0:W.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=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((H=e==null?void 0:e.copy)==null?void 0:H.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=cs({config:e}),x=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;s?No(t,o,e):(o.header.style.display="none",No(t,o,e)),t.append(a);let v=h("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",x||(m.footer.style.display="none"),t.append(m.footer),t.append(v),{container:t,body:a,messagesWrapper:u,composerOverlay:v,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var cf=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}},df=(e,n)=>{if(!e)return null;let t=cf(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},pf=(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},uf=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},dl=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(":"))},pl=320,ju=320,mf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),gf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),ff=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),hf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),bf=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${pl}px`,l.style.maxHeight=`${ju}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),uf(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},yf=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(!dl(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${pl}px`,n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},xf=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(!dl(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${pl}px`,s.style.maxHeight=`${ju}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},vf=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(!dl(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Oo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},ul=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Oo};if(n){let s=n(r);if(s!==null)return s}return Oo()},wf=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},$u=(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},Cf=(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},ml=(e,n,t)=>{var m,x,v,E,S,R;let r=(m=n.showCopy)!=null?m:!0,s=(x=n.showUpvote)!=null?x:!0,o=(v=n.showDownvote)!=null?v:!0;if(!r&&!s&&!o){let I=h("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let a=(E=n.visibility)!=null?E:"hover",i=(S=n.align)!=null?S:"right",d=(R=n.layout)!=null?R:"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=(I,W,P)=>{let w=_t({icon:I,label:W,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",P),w};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},ds=(e,n,t,r,s,o)=>{var re,Le,K,ue,he,ge,me,Xe,V,ne,Re,fe,le,ie,Ye,Ae,pe;let a=t!=null?t:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,l=a.timestamp,u=(Le=d==null?void 0:d.show)!=null?Le:!1,p=(K=l==null?void 0:l.show)!=null?K:!1,f=(ue=d==null?void 0:d.position)!=null?ue:"left",m=(he=l==null?void 0:l.position)!=null?he:"below",x=Cf(e.role,i),v=h("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=mf(e),S=(me=(ge=e.content)==null?void 0:ge.trim())!=null?me:"",I=E.length>0&&S===Va,W=li((V=(Xe=o==null?void 0:o.widgetConfig)==null?void 0:Xe.features)==null?void 0:V.streamAnimation),P=(fe=(Re=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.features)==null?void 0:Re.streamAnimation)==null?void 0:fe.plugins,w=e.role==="assistant"&&W.type!=="none"?Zs(W.type,P):null,H=e.role==="assistant"&&((le=w==null?void 0:w.isAnimating)==null?void 0:le.call(w,e))===!0,_=e.role==="assistant"&&w!==null&&(!!e.streaming||H);_&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),_&&w&&(w.containerClass&&$.classList.add(w.containerClass),$.style.setProperty("--persona-stream-step",`${W.speed}ms`),$.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let N=_?ci((ie=e.content)!=null?ie:"",W.buffer,w,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",U=n({text:N,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=U;_&&(w==null?void 0:w.wrap)==="char"?z=ea(U,"char",e.id,{skipTags:w.skipTags}):_&&(w==null?void 0:w.wrap)==="word"&&(z=ea(U,"word",e.id,{skipTags:w.skipTags}));let oe=null;if(I?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",$.appendChild(oe)):$.innerHTML=z,_&&(w!=null&&w.useCaret)&&!I&&S){let Q=di(),je=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),At=je[je.length-1];if(At!=null&&At.parentNode)At.parentNode.insertBefore(Q,At.nextSibling);else{let X=$.lastElementChild;X?X.appendChild(Q):$.appendChild(Q)}}if(p&&m==="inline"&&e.createdAt){let Q=$u(e,l);Q.classList.add("persona-ml-2","persona-inline"),$.appendChild(Q)}if(E.length>0){let Q=bf(E,!I&&!!S,()=>{I&&oe&&(oe.style.display="")});Q?v.appendChild(Q):I&&oe&&(oe.style.display="")}let We=gf(e);if(We.length>0){let Q=yf(We);Q&&v.appendChild(Q)}let He=ff(e);if(He.length>0){let Q=xf(He);Q&&v.appendChild(Q)}let Oe=hf(e);if(Oe.length>0){let Q=vf(Oe);Q&&v.appendChild(Q)}if(v.appendChild($),p&&m==="below"&&e.createdAt){let Q=$u(e,l);Q.classList.add("persona-mt-1"),v.appendChild(Q)}let de=e.role==="assistant"?df(e.stopReason,(pe=(Ae=o==null?void 0:o.widgetConfig)==null?void 0:Ae.copy)==null?void 0:pe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(N&&N.trim()),je=W.placeholder==="skeleton",At=je&&W.buffer==="line"&&Q;if(Q)At&&v.appendChild(ta());else if(je)v.appendChild(ta());else{let X=ul("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);X&&v.appendChild(X)}}if(de&&e.stopReason&&!e.streaming&&(S||($.style.display="none"),v.appendChild(pf(e.stopReason,de))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=ml(e,r,s);v.appendChild(Q)}if(!u||e.role==="system")return v;let ke=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Pe=wf(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ke.append(v,Pe):ke.append(Pe,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ke},Uu=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ds(e,n,t,r,s,o)};var ps=new Set,Af=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Sf=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
24
+ `):""},qu=(e,n)=>{let t=ps.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},gl=(e,n)=>{var He,Oe,de,we,ke,Pe,re,Le,K,ue,he;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let s=(Oe=(He=n==null?void 0:n.features)==null?void 0:He.reasoningDisplay)!=null?Oe:{},o=s.expandable!==!1,a=o&&ps.has(e.id),i=t.status!=="complete",d=Sf(e,(de=s.previewMaxLines)!=null?de:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(we=n==null?void 0:n.reasoning)!=null?we:{},x=String((ke=t.startedAt)!=null?ke:Date.now()),v=()=>{let ge=h("span","");return ge.setAttribute("data-tool-elapsed",x),ge.textContent=Oa(t),ge},E=(Pe=m.renderCollapsedSummary)==null?void 0:Pe.call(m,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:Oa(t),createElapsedElement:v});typeof E=="string"&&E.trim()?(p.textContent=E,u.appendChild(p)):E instanceof HTMLElement?u.appendChild(E):(p.textContent=f,u.appendChild(p));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=nu(t),u.appendChild(S);let R=(re=s.loadingAnimation)!=null?re:"none",I=m.activeTextTemplate,W=m.completeTextTemplate,P=i?I:W,w=E instanceof HTMLElement,H=(ge,me,Xe)=>{let V=Xe;for(let ne of me){let Re=h("span","persona-tool-char");Re.style.setProperty("--char-index",String(V)),Re.textContent=ne===" "?"\xA0":ne,ge.appendChild(Re),V++}return V},_=(ge,me)=>{p.textContent="";let Xe=Fa(ge,""),V=0;for(let ne of Xe){let Re=ne.styles.length>0?(()=>{let fe=h("span",ne.styles.map(le=>`persona-tool-text-${le}`).join(" "));return p.appendChild(fe),fe})():p;if(ne.isDuration&&i)Re.appendChild(v());else{let fe=ne.isDuration?Oa(t):ne.text;me?V=H(Re,fe,V):Re.appendChild(document.createTextNode(fe))}}};if(!w&&P)if(S.style.display="none",p.style.display="",i&&R!=="none"){let ge=(Le=m.loadingAnimationDuration)!=null?Le:2e3;p.setAttribute("data-preserve-animation","true"),R==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),_(P,!1)):(p.classList.add(`persona-tool-loading-${R}`),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),_(P,!0))}else _(P,!1);else if(!w&&i&&R!=="none"){p.style.display="";let ge=(K=m.loadingAnimationDuration)!=null?K:2e3;if(p.setAttribute("data-preserve-animation","true"),R==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`);else{p.classList.add(`persona-tool-loading-${R}`),p.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let me=p.textContent||f;p.textContent="",H(p,me,0)}t.status==="complete"&&(p.style.display="none")}else w||(t.status==="complete"?p.style.display="none":p.style.display="");let $=null;if(o){$=h("div","persona-flex persona-items-center");let me=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);me?$.appendChild(me):$.textContent=a?"Hide":"Show";let Xe=h("div","persona-flex persona-items-center persona-ml-auto");Xe.append($),l.append(u,Xe)}else l.append(u);let N=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","reasoning"),N.style.display="none",N.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let ge=(he=(ue=n==null?void 0:n.reasoning)==null?void 0:ue.renderCollapsedPreview)==null?void 0:he.call(ue,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});Af(N,ge)||(N.textContent=d),N.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,N),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let z=t.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let me=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);me?$.appendChild(me):$.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",N.style.display=a?"none":N.textContent||N.childNodes.length?"":"none"})(),r.append(l,N,U),r};var us=new Set,Tf=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Ef=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
25
+ `);let s=ns(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
26
+ `):""},Mf=(e,n)=>{var u,p,f,m,x;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=Ef(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?ru(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(m=n==null?void 0:n.toolCall)!=null?m:{},l=a;return s==="tool-name"?l=((x=t.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Gi(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Gi(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},zu=(e,n,t)=>{var u;let r=us.has(e),s=(u=t==null?void 0:t.toolCall)!=null?u:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=ye(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},fl=(e,n)=>{var z,oe,We,He,Oe,de,we,ke,Pe;let t=e.toolCall,r=(z=n==null?void 0:n.toolCall)!=null?z:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(We=(oe=n==null?void 0:n.features)==null?void 0:oe.toolCallDisplay)!=null?We:{},a=o.expandable!==!1,i=a&&us.has(e.id),{summary:d,previewText:l,isActive:u}=Mf(e,n),p=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let x=String((He=t.startedAt)!=null?He:Date.now()),v=()=>{let re=h("span","");return re.setAttribute("data-tool-elapsed",x),re.textContent=Us(t),re},E=(de=r.renderCollapsedSummary)==null?void 0:de.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Oe=o.collapsedMode)!=null?Oe:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Us(t),createElapsedElement:v});typeof E=="string"&&E.trim()?(m.textContent=E,f.appendChild(m)):E instanceof HTMLElement?f.appendChild(E):(m.textContent=d,f.appendChild(m));let S=(we=o.loadingAnimation)!=null?we:"none",R=r.activeTextTemplate,I=r.completeTextTemplate,W=u?R:I,P=E instanceof HTMLElement,w=(re,Le,K)=>{let ue=K;for(let he of Le){let ge=h("span","persona-tool-char");ge.style.setProperty("--char-index",String(ue)),ge.textContent=he===" "?"\xA0":he,re.appendChild(ge),ue++}return ue},H=(re,Le)=>{var ge;m.textContent="";let K=((ge=t.name)==null?void 0:ge.trim())||"tool",ue=Fa(re,K),he=0;for(let me of ue){let Xe=me.styles.length>0?(()=>{let V=h("span",me.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return m.appendChild(V),V})():m;if(me.isDuration&&u)Xe.appendChild(v());else{let V=me.isDuration?Us(t):me.text;Le?he=w(Xe,V,he):Xe.appendChild(document.createTextNode(V))}}};if(!P)if(u&&S!=="none"){let re=(ke=r.loadingAnimationDuration)!=null?ke:2e3;if(m.setAttribute("data-preserve-animation","true"),S==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),W&&H(W,!1);else if(m.classList.add(`persona-tool-loading-${S}`),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),W)H(W,!0);else{let Le=m.textContent||d;m.textContent="",w(m,Le,0)}}else W&&H(W,!1);let _=null;if(a){_=h("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"currentColor",Le=ye(i?"chevron-up":"chevron-down",16,re,2);Le?_.appendChild(Le):_.textContent=i?"Hide":"Show";let K=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(_),p.append(f,K)}else p.append(f);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let re=(Pe=r.renderCollapsedPreview)==null?void 0:Pe.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});Tf($,re)||($.textContent=l),$.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,$),s;let N=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(N.style.display=i?"":"none",r.contentBackgroundColor&&(N.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(N.style.color=r.contentTextColor),r.contentPaddingX&&(N.style.paddingLeft=r.contentPaddingX,N.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(N.style.paddingTop=r.contentPaddingY,N.style.paddingBottom=r.contentPaddingY),t.name){let re=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=t.name,N.appendChild(re)}if(t.args!==void 0){let re=h("div","persona-space-y-1"),Le=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Le.style.color=r.labelTextColor),Le.textContent="Arguments";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(t.args),re.append(Le,K),N.appendChild(re)}if(t.chunks&&t.chunks.length){let re=h("div","persona-space-y-1"),Le=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Le.style.color=r.labelTextColor),Le.textContent="Activity";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=t.chunks.join(""),re.append(Le,K),N.appendChild(re)}if(t.status==="complete"&&t.result!==void 0){let re=h("div","persona-space-y-1"),Le=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Le.style.color=r.labelTextColor),Le.textContent="Result";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(t.result),re.append(Le,K),N.appendChild(re)}if(t.status==="complete"&&typeof t.duration=="number"){let re=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${t.duration}ms`,N.appendChild(re)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"currentColor",Le=ye(i?"chevron-up":"chevron-down",16,re,2);Le?_.appendChild(Le):_.textContent=i?"Hide":"Show"}N.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(p,$,N),s};var po=require("partial-json");var bl="ask_user_question",hl=8,ms="data-persona-ask-sheet-for",kf="Other",Lf="Other\u2026",Ku="Type your own answer here",Ju="Send",Pf="Next",If="Back",Wf="Submit all",Rf="Skip",Hf=3,yl="data-ask-current-index",xl="data-ask-question-count",Gu="data-ask-answers",vl="data-ask-grouped",Xu="data-ask-layout",Bf=e=>e.layout==="pills"?"pills":"rows",Df=e=>e.getAttribute(Xu)==="pills"?"pills":"rows",Vu=!1,Qu=e=>e.replace(/["\\]/g,"\\$&"),$r=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===bl,Ci=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},jr=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=(0,po.parse)(s,po.STR|po.OBJ|po.ARR);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},aa=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>hl&&!Vu&&(Vu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${hl}.`)),n.slice(0,hl)},Nf=e=>{var n;return(n=aa(e)[0])!=null?n:null},Of=(e,n)=>{var t;return(t=aa(e)[n])!=null?t:null},Yu=(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))},Zu=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},Ff=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Zu(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},_f=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},$f=(e,n,t,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<Hf;m++)o.appendChild(_f(r));return o}if(d.forEach((m,x)=>{o.appendChild(Ff(m,x,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?kf:Lf;if(r==="rows"){let x=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=h("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(u=n.freeTextPlaceholder)!=null?u:Ku,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:m),v.appendChild(E),x.appendChild(v);let S=Zu(r,a,d.length);S&&x.appendChild(S),o.appendChild(x)}else{let x=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=n.freeTextLabel)!=null?f:m,o.appendChild(x)}}return o},em=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:Ku,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Ju,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},jf=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:Ju,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},Uf=(e,n,t)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=t.backLabel)!=null?l:If,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:Rf,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:Wf:(f=t.nextLabel)!=null?f:Pf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Fo=e=>{let n=e.getAttribute(Gu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},tm=(e,n)=>{e.setAttribute(Gu,JSON.stringify(n))},lr=e=>{var t;let n=Number((t=e.getAttribute(yl))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},qf=(e,n)=>{e.setAttribute(yl,String(Math.max(0,Math.floor(n))))},gs=e=>{var t;let n=Number((t=e.getAttribute(xl))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},uo=e=>e.getAttribute(vl)==="true",zf=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Vf=(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)))},Ai=(e,n)=>{let{payload:t}=jr(n),r=aa(t),s=Fo(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},nm=e=>{let n=Fo(e),t=lr(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},rm=e=>{if(!uo(e))return;let n=Fo(e),t=lr(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},wl=(e,n,t)=>{let r=Ci(t),s=Df(e),{payload:o,complete:a}=jr(n),i=uo(e),d=lr(e),l=gs(e),u=i?Of(o,d):Nf(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let R=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=R,x.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=$f(u,r,a,s);v.replaceWith(R)}if(s!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(em(r,s))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!E?e.appendChild(jf(r)):(!p||i)&&E&&E.remove(),e.setAttribute("data-multi-select",p?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=Uf(d,l,r);S?S.replaceWith(R):e.appendChild(R)}else S&&S.remove();nm(e),rm(e)},Kf=(e,n,t)=>{let r=Ci(n),s=Bf(r),o=e.toolCall.id,a=aa(t),i=Math.max(1,a.length),d=i>1,l=zf(e,a),u=d?Vf(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(ms,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(xl,String(i)),p.setAttribute(yl,String(u)),p.setAttribute(vl,d?"true":"false"),p.setAttribute(Xu,s),tm(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`),Yu(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let x=h("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),p.appendChild(f);let E=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),p.appendChild(E),s!=="rows"&&p.appendChild(em(r,s)),wl(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Jf=(e,n,t)=>{let{payload:r}=jr(n),s=Math.max(1,aa(r).length);s>gs(e)&&(e.setAttribute(xl,String(s)),s>1&&!uo(e)&&e.setAttribute(vl,"true")),wl(e,n,t)},om=(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);Yu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=jr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},fs=(e,n,t)=>{if(!t||!$r(e)||Ci(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==s&&l.remove()});let a=t.querySelector(`[${ms}="${Qu(s)}"]`);if(a){Jf(a,e,n);return}let{payload:i}=jr(e),d=Kf(e,n,i);t.appendChild(d)},mo=(e,n)=>{if(!e)return;let t=n?`[${ms}="${Qu(n)}"]`:`[${ms}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Cl=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),go=(e,n)=>{let t=Fo(e),r=lr(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,tm(e,t),nm(e),rm(e)},Si=(e,n,t,r)=>{let s=gs(e),o=Math.max(0,Math.min(s-1,r));qf(e,o),wl(e,n,t)};var Al=(e,n)=>{var v,E,S,R,I,W,P,w,H,_,$,N;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=r==null?void 0:r.titleColor)!=null?S:"currentColor",u=ye(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(R=r==null?void 0:r.title)!=null?R:"Approval Required",f.appendChild(m),!s){let U=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");U.setAttribute("data-approval-status",t.status),t.status==="approved"?(U.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",U.style.color="var(--persona-palette-colors-success-700, #15803d)",U.textContent="Approved"):t.status==="denied"?(U.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",U.style.color="var(--persona-palette-colors-error-700, #b91c1c)",U.textContent="Denied"):t.status==="timeout"&&(U.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",U.style.color="var(--persona-palette-colors-warning-700, #b45309)",U.textContent="Timeout"),f.appendChild(U)}p.appendChild(f);let x=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(x.style.color=r.descriptionColor),x.textContent=t.description,p.appendChild(x),t.parameters){let U=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&&(U.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(U.style.color=r.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=ns(t.parameters),p.appendChild(U)}if(s){let U=h("div","persona-flex persona-gap-2 persona-mt-2");U.setAttribute("data-approval-buttons","true");let z=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");z.type="button",z.style.backgroundColor=(I=r==null?void 0:r.approveButtonColor)!=null?I:"var(--persona-approval-approve-bg, #22c55e)",z.style.color=(W=r==null?void 0:r.approveButtonTextColor)!=null?W:"#ffffff",z.setAttribute("data-approval-action","approve");let oe=ye("shield-check",14,(P=r==null?void 0:r.approveButtonTextColor)!=null?P:"#ffffff",2);oe&&(oe.style.marginRight="4px",z.appendChild(oe));let We=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");z.appendChild(We);let He=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");He.type="button",He.style.backgroundColor=(H=r==null?void 0:r.denyButtonColor)!=null?H:"transparent",He.style.color=(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",He.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,He.setAttribute("data-approval-action","deny");let Oe=ye("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);Oe&&(Oe.style.marginRight="4px",He.appendChild(Oe));let de=document.createTextNode((N=r==null?void 0:r.denyLabel)!=null?N:"Deny");He.appendChild(de),U.append(z,He),p.appendChild(U)}return a.append(i,p),o.appendChild(a),o};var sm=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let x=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=m,x.disabled=p,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(x),n.push(x)}),e.appendChild(u)}}};var ia=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 la=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};var Gf=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Xf=new Set(["step_start","execution_start"]),Qf=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Yf=new Set(["step_complete","agent_turn_complete"]),Zf=new Set(["flow_complete","agent_complete"]),am=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),lm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,_o=(e,n)=>{let t=e[n];return lm(t)?t:void 0};function Sl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ti(e,n){if(!(e<=0||n===void 0||n<250))return e/(n/1e3)}function eh(e,n){return typeof n.type=="string"?n.type:e}function th(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function nh(e,n){return e==="step_delta"||e==="step_chunk"?n.stepType!=="tool"&&n.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof n.contentType=="string"?n.contentType:typeof n.content_type=="string"?n.content_type:void 0)==="text"}function im(e){var r,s,o,a,i;let n=_o(e,"result"),t=[_o(e,"tokens"),_o(e,"totalTokens"),n?_o(n,"tokens"):void 0,_o(e,"usage"),n?_o(n,"usage"):void 0];for(let d of t){if(!d)continue;let l=(s=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?s:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Qn(e.outputTokens))!=null?o:Qn(e.completionTokens))!=null?i:n?(a=Qn(n.outputTokens))!=null?a:Qn(n.completionTokens):void 0}function rh(e){var t,r,s,o,a;let n=_o(e,"result");return(a=(s=(r=(t=Qn(e.executionTime))!=null?t:Qn(e.executionTimeMs))!=null?r:Qn(e.execution_time))!=null?s:Qn(e.duration))!=null?a:n?(o=Qn(n.executionTime))!=null?o:Qn(n.executionTimeMs):void 0}function oh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ca=class{constructor(n=oh){this.metric={status:"idle"};this.run=null;this.now=n}getMetric(){let n=this.run;if(n&&this.metric.status==="running"&&n.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-n.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:Ti(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(n){this.run={startedAt:n,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(n,t){var o;if(!lm(t)){am.has(n)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=eh(n,t),s=this.now();if(Gf.has(r)){this.startRun(s);return}if(Xf.has(r)){this.run||this.startRun(s);return}if(Qf.has(r)){if(!nh(r,t))return;let a=th(t);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Sl(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ti(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Yf.has(r)){if(!this.run)return;let a=this.run,i=im(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Sl(a.visibleCharCount),u=this.resolveDuration(a,t,s);this.metric={status:"running",tokensPerSecond:Ti(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Zf.has(r)){if(!this.run)return;let a=this.run,i=im(t),d=i!=null?i:a.exactOutputTokens+Sl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,t,s);this.metric={status:"complete",tokensPerSecond:Ti(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(am.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(n,t,r){let s=n.firstDeltaAt!==void 0?r-n.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=rh(t);return o!=null?o:r-n.startedAt}};function hs(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var sh={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)"}},ah={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ih=["flowName","stepName","reasoningText","text","name","tool","toolName"],lh=100;function ch(e,n){let t={...sh,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return ah}function dh(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function ph(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function uh(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function mh(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 gh(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 fh(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function hh(e){let n=[];return e.outputTokens!==void 0&&n.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&n.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&n.push(e.source),n.join(" \xB7 ")}function bh(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Tl(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");hs(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var z,oe;let m=h("div",""),x=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let v=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=(z=r.timestampFormat)!=null?z:"relative";S.textContent=R==="relative"?dh(e.timestamp,t):ph(e.timestamp);let I=null;r.showSequenceNumbers!==!1&&(I=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(n+1));let W=ch(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=W.bg,P.style.color=W.text,P.style.borderColor=W.text+"50",P.textContent=e.type;let w=(oe=r.descriptionFields)!=null?oe:ih,H=uh(e.payload,w),_=null;H&&(_=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=H);let $=h("div","persona-flex-1 persona-min-w-0"),N=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"),U=ye("clipboard","12px","currentColor",1.5);return U&&N.appendChild(U),N.addEventListener("click",async We=>{We.stopPropagation(),await mh(gh(e)),N.innerHTML="";let He=ye("check","12px","currentColor",1.5);He&&N.appendChild(He),setTimeout(()=>{N.innerHTML="";let Oe=ye("clipboard","12px","currentColor",1.5);Oe&&N.appendChild(Oe)},1500)}),x.appendChild(v),x.appendChild(S),I&&x.appendChild(I),x.appendChild(P),_&&x.appendChild(_),x.appendChild($),x.appendChild(N),m.appendChild(x),d&&m.appendChild(bh(e,a,i)),m}}function cm(e){var x,v,E,S,R;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(x=s==null?void 0:s.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(E=i==null?void 0:i.label)!=null?E:"",p=(R=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?R:{},f=o.find(I=>I.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let I=f.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>m().element,onClose:r});if(I)return{element:I,update:()=>{},destroy:()=>{}}}return m();function m(){let I=p.classNames,W=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hs(W,I==null?void 0:I.panel);let P=[],w="",H="",_=null,$=[],N={},U=0,z=si(),oe=0,We=0,He=!1,Oe=null,de=!1,we=0,ke=new Set,Pe=new Map,re="",Le="",K=null,ue,he,ge,me,Xe,V=null,ne=null,Re=null;function fe(){let ae=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),xe=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");hs(xe,I==null?void 0:I.headerBar);let Ct=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ct.textContent="Events",ue=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"),ue.textContent="0",a){ne=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Dn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Dn.textContent="Throughput",V=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),V.textContent="-- tok/s",Re=h("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Re.style.display="none",Re.style.pointerEvents="none";let Zn=ne,xn=Re,Nn=()=>{if(!xn.textContent)return;let vr=Zn.getBoundingClientRect(),On=ae.getBoundingClientRect();xn.style.left=`${vr.left-On.left}px`,xn.style.top=`${vr.bottom-On.top+4}px`,xn.style.display="block"},mt=()=>{xn.style.display="none"};ne.addEventListener("mouseenter",Nn),ne.addEventListener("mouseleave",mt),ne.appendChild(Dn),ne.appendChild(V)}let jt=h("div","persona-flex-1");he=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 en=h("option","");en.value="",en.textContent="All events",he.appendChild(en),ge=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ge.type="button",ge.title="Copy All";let Mt=ye("clipboard-copy","12px","currentColor",1.5);Mt&&ge.appendChild(Mt);let Tt=h("span","persona-text-xs");Tt.textContent="Copy All",ge.appendChild(Tt),xe.appendChild(Ct),xe.appendChild(ue),ne&&xe.appendChild(ne),xe.appendChild(jt),xe.appendChild(he),xe.appendChild(ge);let bt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hs(bt,I==null?void 0:I.searchBar);let xt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=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");xt&&zt.appendChild(xt),me=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"),hs(me,I==null?void 0:I.searchInput),me.type="text",me.placeholder="Search event payloads...",Xe=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Xe.type="button",Xe.style.display="none";let tt=ye("x","12px","currentColor",2);return tt&&Xe.appendChild(tt),bt.appendChild(zt),bt.appendChild(me),bt.appendChild(Xe),ae.appendChild(xe),ae.appendChild(bt),Re&&ae.appendChild(Re),ae}let le,ie=o.find(ae=>ae.renderEventStreamToolbar);if(ie!=null&&ie.renderEventStreamToolbar&&s){let ae=ie.renderEventStreamToolbar({config:s,defaultRenderer:()=>fe(),eventCount:n.getSize(),filteredCount:0,onFilterChange:xe=>{w=xe,Bn(),se()},onSearchChange:xe=>{H=xe,Bn(),se()}});le=ae!=null?ae:fe()}else le=fe();let Ye=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");Ye.style.display="none";function Ae(){if(!a||!V||!ne)return;let ae=a();V.textContent=fh(ae);let xe=hh(ae);Re&&(Re.textContent=xe,xe||(Re.style.display="none")),xe?ne.setAttribute("aria-label",xe):ne.removeAttribute("aria-label")}let pe=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Q=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Q.style.height="100%";let je=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");hs(je,I==null?void 0:I.scrollIndicator),je.style.display="none",je.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let At=ye(l,"14px","currentColor",2);At&&je.appendChild(At);let X=h("span","");X.textContent=u,je.appendChild(X);let Fe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Fe.style.display="none",pe.appendChild(Q),pe.appendChild(Fe),pe.appendChild(je),W.setAttribute("tabindex","0"),W.appendChild(le),W.appendChild(Ye),W.appendChild(pe);function kn(){let ae=n.getAll(),xe={};for(let Tt of ae)xe[Tt.type]=(xe[Tt.type]||0)+1;let Ct=Object.keys(xe).sort(),jt=Ct.length!==$.length||!Ct.every((Tt,bt)=>Tt===$[bt]),en=!jt&&Ct.some(Tt=>xe[Tt]!==N[Tt]),yn=ae.length!==Object.values(N).reduce((Tt,bt)=>Tt+bt,0);if(!jt&&!en&&!yn||($=Ct,N=xe,!he))return;let Mt=he.value;if(he.options[0].textContent="All events",jt){for(;he.options.length>1;)he.remove(1);for(let Tt of Ct){let bt=h("option","");bt.value=Tt,bt.textContent=`${Tt} (${xe[Tt]||0})`,he.appendChild(bt)}Mt&&Ct.includes(Mt)?he.value=Mt:Mt&&(he.value="",w="")}else for(let Tt=1;Tt<he.options.length;Tt++){let bt=he.options[Tt];bt.textContent=`${bt.value} (${xe[bt.value]||0})`}}function Ot(){let ae=n.getAll();if(w&&(ae=ae.filter(xe=>xe.type===w)),H){let xe=H.toLowerCase();ae=ae.filter(Ct=>Ct.type.toLowerCase().includes(xe)||Ct.payload.toLowerCase().includes(xe))}return ae}function cn(){return w!==""||H!==""}function Bn(){U=0,oe=0,z.resume(),je.style.display="none"}function Yn(ae){ke.has(ae)?ke.delete(ae):ke.add(ae),K=ae;let xe=Q.scrollTop,Ct=z.isFollowing();de=!0,z.pause(),se(),Q.scrollTop=xe,Ct&&z.resume(),de=!1}function D(){return Xs(Q,50)}function se(){We=Date.now(),He=!1,Ae(),kn();let ae=n.getEvictedCount();ae>0?(Ye.textContent=`${ae.toLocaleString()} older events truncated`,Ye.style.display=""):Ye.style.display="none",P=Ot();let xe=P.length,Ct=n.getSize()>0;ue&&(ue.textContent=String(n.getSize())),xe===0&&Ct&&cn()?(Fe.textContent=H?`No events matching '${H}'`:"No events matching filter",Fe.style.display="",Q.style.display="none"):(Fe.style.display="none",Q.style.display=""),ge&&(ge.title=cn()?`Copy Filtered (${xe})`:"Copy All"),d&&!z.isFollowing()&&xe>U&&(oe+=xe-U,X.textContent=u?`${u}${oe>0?` (${oe})`:""}`:"",je.style.display=""),U=xe;let jt=n.getAll(),en=jt.length>0?jt[0].timestamp:0,yn=new Set(P.map(bt=>bt.id));for(let bt of ke)yn.has(bt)||ke.delete(bt);let Mt=w!==re||H!==Le,Tt=Pe.size===0&&P.length>0;if(Mt||Tt||P.length===0){Q.innerHTML="",Pe.clear();let bt=document.createDocumentFragment();for(let xt=0;xt<P.length;xt++){let zt=Tl(P[xt],xt,en,p,ke,Yn,o,s);Pe.set(P[xt].id,zt),bt.appendChild(zt)}Q.appendChild(bt),re=w,Le=H,K=null}else{if(K!==null){let xt=Pe.get(K);if(xt&&xt.parentNode===Q){let zt=P.findIndex(tt=>tt.id===K);if(zt>=0){let tt=Tl(P[zt],zt,en,p,ke,Yn,o,s);Q.insertBefore(tt,xt),xt.remove(),Pe.set(K,tt)}}K=null}let bt=new Set(P.map(xt=>xt.id));for(let[xt,zt]of Pe)bt.has(xt)||(zt.remove(),Pe.delete(xt));for(let xt=0;xt<P.length;xt++){let zt=P[xt];if(!Pe.has(zt.id)){let tt=Tl(zt,xt,en,p,ke,Yn,o,s);Pe.set(zt.id,tt),Q.appendChild(tt)}}}z.isFollowing()&&(Q.scrollTop=Q.scrollHeight)}function De(){if(Date.now()-We>=lh){Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),se();return}He||(He=!0,Oe=requestAnimationFrame(()=>{Oe=null,se()}))}let Qe=(ae,xe)=>{if(!ge)return;ge.innerHTML="";let Ct=ye(ae,"12px","currentColor",1.5);Ct&&ge.appendChild(Ct);let jt=h("span","persona-text-xs");jt.textContent="Copy All",ge.appendChild(jt),setTimeout(()=>{ge.innerHTML="";let en=ye("clipboard-copy","12px","currentColor",1.5);en&&ge.appendChild(en);let yn=h("span","persona-text-xs");yn.textContent="Copy All",ge.appendChild(yn),ge.disabled=!1},xe)},_e=async()=>{if(ge){ge.disabled=!0;try{let ae;cn()?ae=P:t?(ae=await t(),ae.length===0&&(ae=n.getAll())):ae=n.getAll();let xe=ae.map(Ct=>{try{return JSON.parse(Ct.payload)}catch{return Ct.payload}});await navigator.clipboard.writeText(JSON.stringify(xe,null,2)),Qe("check",1500)}catch{Qe("x",1500)}}},$e=()=>{he&&(w=he.value,Bn(),se())},ot=()=>{!me||!Xe||(Xe.style.display=me.value?"":"none",_&&clearTimeout(_),_=setTimeout(()=>{H=me.value,Bn(),se()},150))},St=()=>{!me||!Xe||(me.value="",H="",Xe.style.display="none",_&&clearTimeout(_),Bn(),se())},$t=()=>{if(de)return;let ae=Q.scrollTop,{action:xe,nextLastScrollTop:Ct}=ai({following:z.isFollowing(),currentScrollTop:ae,lastScrollTop:we,nearBottom:D(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});we=Ct,xe==="resume"?(z.resume(),oe=0,je.style.display="none"):xe==="pause"&&(z.pause(),d&&(X.textContent=u,je.style.display=""))},Jt=ae=>{let xe=ii({following:z.isFollowing(),deltaY:ae.deltaY,nearBottom:D(),resumeWhenNearBottom:!0});xe==="pause"?(z.pause(),d&&(X.textContent=u,je.style.display="")):xe==="resume"&&(z.resume(),oe=0,je.style.display="none")},J=()=>{d&&(Q.scrollTop=Q.scrollHeight,z.resume(),oe=0,je.style.display="none")},ft=ae=>{let xe=ae.target;if(!xe||xe.closest("button"))return;let Ct=xe.closest("[data-event-id]");if(!Ct)return;let jt=Ct.getAttribute("data-event-id");jt&&Yn(jt)},rt=ae=>{if((ae.metaKey||ae.ctrlKey)&&ae.key==="f"){ae.preventDefault(),me==null||me.focus(),me==null||me.select();return}ae.key==="Escape"&&(me&&document.activeElement===me?(St(),me.blur(),W.focus()):r&&r())};ge&&ge.addEventListener("click",_e),he&&he.addEventListener("change",$e),me&&me.addEventListener("input",ot),Xe&&Xe.addEventListener("click",St),Q.addEventListener("scroll",$t),Q.addEventListener("wheel",Jt,{passive:!0}),Q.addEventListener("click",ft),je.addEventListener("click",J),W.addEventListener("keydown",rt);function qt(){_&&clearTimeout(_),Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),He=!1,Pe.clear(),ge&&ge.removeEventListener("click",_e),he&&he.removeEventListener("change",$e),me&&me.removeEventListener("input",ot),Xe&&Xe.removeEventListener("click",St),Q.removeEventListener("scroll",$t),Q.removeEventListener("wheel",Jt),Q.removeEventListener("click",ft),je.removeEventListener("click",J),W.removeEventListener("keydown",rt)}return{element:W,update:De,destroy:qt}}}function dm(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(l.append(u,p),i.append(d,l),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var pm=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>dm(e,n)});if(u)return u}return dm(e,n)};var El=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)})}},Ur=new El;Ur.register("PersonaArtifactCard",pm);function yh(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function um(e,n){var he,ge,me,Xe;let t=(ge=(he=e.features)==null?void 0:he.artifacts)==null?void 0:ge.layout,s=((me=t==null?void 0:t.toolbarPreset)!=null?me:"default")==="document",o=(Xe=t==null?void 0:t.panePadding)==null?void 0:Xe.trim(),a=e.markdown?Lo(e.markdown):null,i=es(e.sanitize),d=V=>{let ne=a?a(V):Po(V);return i?i(ne):ne},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};l&&l.addEventListener("click",()=>{var V;u(),(V=n.onDismiss)==null||V.call(n)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var V;u(),(V=n.onDismiss)==null||V.call(n)});let v="rendered",E=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?_t({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):_t({icon:"eye",label:"Rendered view"}),R=s?_t({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):_t({icon:"code-2",label:"Source"}),I=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),W=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,P=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,H=!!(P&&w&&w.length>0),_=null,$,N=null,U=null;if(s&&(W||P)&&!H){if($=W?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let V=ye("chevron-down",14,"currentColor",2);V&&$.appendChild(V)}}else s&&H?(_=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=W?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N=_t({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),_.append($,N)):s?$=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=_t({icon:"copy",label:"Copy"});let z=s?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"}),oe=s?_t({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:"Close"}),We=()=>{var le,ie,Ye;let V=(le=Pe.find(Ae=>Ae.id===re))!=null?le:Pe[Pe.length-1],ne=(ie=V==null?void 0:V.id)!=null?ie:null,Re=(V==null?void 0:V.artifactType)==="markdown"&&(Ye=V.markdown)!=null?Ye:"",fe=V?JSON.stringify({component:V.component,props:V.props},null,2):"";return{markdown:Re,jsonPayload:fe,id:ne}},He=async()=>{var le;let{markdown:V,jsonPayload:ne}=We(),Re=(le=Pe.find(ie=>ie.id===re))!=null?le:Pe[Pe.length-1],fe=(Re==null?void 0:Re.artifactType)==="markdown"?V:Re?ne:"";try{await navigator.clipboard.writeText(fe)}catch{}};if($.addEventListener("click",async()=>{let V=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(V&&H){let{markdown:ne,jsonPayload:Re,id:fe}=We();try{await V({actionId:"primary",artifactId:fe,markdown:ne,jsonPayload:Re})}catch{}return}await He()}),N&&(w!=null&&w.length)){let V=()=>{var Re;return(Re=p.closest("[data-persona-root]"))!=null?Re:document.body},ne=()=>{U=co({items:w.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:fe,jsonPayload:le,id:ie}=We(),Ye=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ye?await Ye({actionId:Re,artifactId:ie,markdown:fe,jsonPayload:le}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(fe):Re==="json"||Re==="source"?await navigator.clipboard.writeText(le):await navigator.clipboard.writeText(fe||le)}catch{}},anchor:_!=null?_:N,position:"bottom-right",portal:V()})};p.isConnected?ne():requestAnimationFrame(ne),N.addEventListener("click",Re=>{Re.stopPropagation(),U==null||U.toggle()})}z.addEventListener("click",async()=>{var V;try{await((V=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:V.call(t))}catch{}K()}),oe.addEventListener("click",()=>{var V;u(),(V=n.onDismiss)==null||V.call(n)});let Oe=()=>{s&&(S.setAttribute("aria-pressed",v==="rendered"?"true":"false"),R.setAttribute("aria-pressed",v==="source"?"true":"false"))};S.addEventListener("click",()=>{v="rendered",Oe(),K()}),R.addEventListener("click",()=>{v="source",Oe(),K()});let de=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),E.append(S,R),_?I.append(_,z,oe):I.append($,z,oe),f.append(E,de,I),Oe()):(f.appendChild(m),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let we=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(we.style.paddingLeft=o,we.style.paddingRight=o,ke.style.padding=o),p.appendChild(f),p.appendChild(we),p.appendChild(ke);let Pe=[],re=null,Le=!1,K=()=>{var fe,le,ie,Ye;let V=s&&Pe.length<=1;we.classList.toggle("persona-hidden",V),we.replaceChildren();for(let Ae of Pe){let pe=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");pe.type="button",pe.textContent=Ae.title||Ae.id.slice(0,8),Ae.id===re&&pe.classList.add("persona-bg-persona-container","persona-border-persona-border"),pe.addEventListener("click",()=>n.onSelect(Ae.id)),we.appendChild(pe)}ke.replaceChildren();let ne=re&&Pe.find(Ae=>Ae.id===re)||Pe[Pe.length-1];if(!ne)return;if(s){let Ae=ne.artifactType==="markdown"?"MD":(fe=ne.component)!=null?fe:"Component",Q=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${Q} \xB7 ${Ae}`}else m.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&v==="source"){let pe=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");pe.textContent=(le=ne.markdown)!=null?le:"",ke.appendChild(pe);return}let Ae=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ae.innerHTML=d((ie=ne.markdown)!=null?ie:""),ke.appendChild(Ae);return}let Re=ne.component?Ur.get(ne.component):void 0;if(Re){let pe={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Q=Re((Ye=ne.props)!=null?Ye:{},pe);if(Q){ke.appendChild(Q);return}}catch{}}ke.appendChild(yh(ne))},ue=()=>{var ne;let V=Pe.length>0;if(p.classList.toggle("persona-hidden",!V),l){let Re=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,le=((ne=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;V&&le&&Le?(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(V){var ne,Re,fe;Pe=V.artifacts,re=(fe=(Re=V.selectedId)!=null?Re:(ne=V.artifacts[V.artifacts.length-1])==null?void 0:ne.id)!=null?fe:null,Pe.length>0&&(Le=!0),K(),ue()},setMobileOpen(V){Le=V,!V&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ue()}}}function cr(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 mm(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!cr(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function xh(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 Ei(e,n){var d,l,u,p,f,m,x,v,E,S;if(!cr(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"),xh(e),mm(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=t==null?void 0:t.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(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"),mm(e,n)}var gm=["panel","seamless"];function Mi(e,n){var i,d,l,u,p,f;for(let m of gm)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!cr(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=gm.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function fm(e,n){var t,r,s;return!n||!cr(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function vh(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 wh(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 Ch(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Ah(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function hm(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function bm(e,n,t,r,s,o){let a=vh(s,200),i=Ah(n,t,r,200);i=Math.max(a,i);let d=wh(o);return d!==null&&(i=Math.min(i,d)),Ch(e,a,i)}var ym={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"}},Ml=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,v,E;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(v=ym[a])!=null?v:ym.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let 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 w,H;let R=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${n.id}-${a}-${S.name}`;let I=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");I.textContent=S.label,R.appendChild(I);let W=(w=S.type)!=null?w:"text",P;W==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=W),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=(H=S.placeholder)!=null?H:"",S.required&&(P.required=!0),R.appendChild(P),u.appendChild(R)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async S=>{var P,w;S.preventDefault();let R=(P=t.formEndpoint)!=null?P:"/form",I=new FormData(u),W={};I.forEach((H,_)=>{W[_]=H}),W.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let H=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let _=await H.json();f.textContent=(w=_.message)!=null?w:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(H){f.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var kl=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},da=new kl;var xm=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Sh=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Th=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},pa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Sh(e),t=Th(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Ll=e=>typeof e=="string"?e:e==null?"":String(e),$o={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ll(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Ll(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Ll(t.text)}}},vm=e=>Array.isArray(e)?e.map(n=>String(n)):[],ua=e=>{let n=new Set(vm(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(vm(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var Eh=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}},Mh=e=>e.map(n=>({...n,streaming:!1})),kh=e=>e.map(n=>({...n,status:"complete"})),ki=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?Eh(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?Mh(t.messages):void 0,artifacts:t.artifacts?kh(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var bs=require("partial-json");function Lh(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Ph(e,n){if(!Lh(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 Li(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=(0,bs.parse)(t,bs.STR|bs.OBJ),o=Ph(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function wm(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Pi(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=Ur.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Cm(){let e=Li();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Am(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 Ii(e){let n=Am(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 Wi(e){let n=Am(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 Ih=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ri(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Ih}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,m.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,m.appendChild(v),f.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let w=1;w<=5;w++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),H.title=l[w-1],H.dataset.rating=String(w),H.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
29
29
  </svg>
30
- `,R.addEventListener("click",()=>{p=C,S.forEach((_,$)=>{let D=$<C;_.classList.toggle("selected",D),_.setAttribute("aria-checked",$===C-1?"true":"false")})}),S.push(R),T.appendChild(R)}f.appendChild(T);let W=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=o,W.rows=3,W.setAttribute("aria-label","Additional comments"),C.appendChild(W),f.appendChild(C)}let I=document.createElement("div");I.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=i,O.addEventListener("click",()=>{n==null||n(),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){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let C=(W==null?void 0:W.value.trim())||void 0;await t(p,C),u.remove()}catch(C){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(O),I.appendChild(P),f.appendChild(I),u.appendChild(f),u}function Hi(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,v.appendChild(T),m.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=l;let O=document.createElement("span");O.className="persona-feedback-label-high",O.textContent=u,W.appendChild(I),W.appendChild(O);let P=document.createElement("div");P.className="persona-feedback-numbers";let C=[];for(let U=0;U<=10;U++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${U} out of 10`),z.textContent=String(U),z.dataset.rating=String(U),U<=6?z.classList.add("persona-feedback-detractor"):U<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{f=U,C.forEach((oe,We)=>{oe.classList.toggle("selected",We===U),oe.setAttribute("aria-checked",We===U?"true":"false")})}),C.push(z),P.appendChild(z)}S.appendChild(W),S.appendChild(P),m.appendChild(S);let R=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=o,R.rows=3,R.setAttribute("aria-label","Additional comments"),U.appendChild(R),m.appendChild(U)}let _=document.createElement("div");_.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{n==null||n(),p.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let U=(R==null?void 0:R.value.trim())||void 0;await t(f,U),p.remove()}catch(U){D.disabled=!1,D.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),_.appendChild($),_.appendChild(D),m.appendChild(_),p.appendChild(m),p}var bs="persona-chat-history",Lh=30*1e3,Ph={"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 Ih(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Ph[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function Bi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Wh(e){var t,n,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Rh(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Pl=e=>!e||typeof e!="object"?{}:{...e},Cm=e=>e.map(t=>({...t,streaming:!1})),Am=(e,t,n)=>{let r=e!=null&&e.markdown?Lo(e.markdown):null,s=es(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=Po(a),s?s(d):d}};function Sm(e){var i,d,l,u;let t=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=be(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var Di=(e,t,n)=>{var tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac,Sc,Ec,Tc,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Jc;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=Za(t),s=da.getForInstance(r.plugins);r.components&&Ur.registerAll(r.components);let o=ym(),i=r.persistState===!1?null:(tc=r.storageAdapter)!=null?tc:ki(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let g=r.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:b}=g;return b&&(u=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=c!=null?c:{messages:[],metadata:{}},y=p(g);y.metadata&&(d=Pl(y.metadata)),(nc=y.messages)!=null&&nc.length&&(r={...r,initialMessages:y.messages}),(rc=y.artifacts)!=null&&rc.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(oc=y.selectedArtifactId)!=null?oc: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:{}});(sc=c.messages)!=null&&sc.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var y;d=(y=c({...d}))!=null?y:{},zo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[$o.message,$o.messageAndClick],T=ua({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let S=(ic=(ac=r.launcher)==null?void 0:ac.enabled)!=null?ic:!0,W=(cc=(lc=r.launcher)==null?void 0:lc.autoExpand)!=null?cc:!1,I=(dc=r.autoFocusInput)!=null?dc:!1,O=W,P=S,C=(uc=(pc=r.layout)==null?void 0:pc.header)==null?void 0:uc.layout,R=!1,_=()=>lo(r),$=()=>S||_(),D=_()?!1:S?W:!0,U=!1,z=null,oe=()=>{U=!0,z&&clearTimeout(z),z=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},We=Am(r,T,oe),He=(gc=(mc=r.features)==null?void 0:mc.showReasoning)!=null?gc:!0,Oe=(hc=(fc=r.features)==null?void 0:fc.showToolCalls)!=null?hc:!0,de=(bc=(yc=r.features)==null?void 0:yc.showEventStreamToggle)!=null?bc:!1,we=(vc=(xc=r.features)==null?void 0:xc.scrollToBottom)!=null?vc:{},Pe=`${(Cc=typeof r.persistState=="object"?(wc=r.persistState)==null?void 0:wc.keyPrefix:void 0)!=null?Cc:"persona-"}event-stream`,re=de?new la(Pe):null,Le=(Ec=(Sc=(Ac=r.features)==null?void 0:Ac.eventStream)==null?void 0:Sc.maxEvents)!=null?Ec:2e3,K=de?new ia(Le,re):null,ue=de?new ca:null,he=null,ge=!1,me=null,Xe=0;re==null||re.open().then(()=>K==null?void 0:K.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let V={onCopy:c=>{var g,y;o.emit("message:copy",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onCopy)==null||y.call(g,c)},onFeedback:c=>{var g,y;o.emit("message:feedback",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},ne=(Tc=r.statusIndicator)!=null?Tc:{},Re=c=>{var g,y,b,L;return c==="idle"?(g=ne.idleText)!=null?g:hn.idle:c==="connecting"?(y=ne.connectingText)!=null?y:hn.connecting:c==="connected"?(b=ne.connectedText)!=null?b:hn.connected:c==="error"?(L=ne.errorText)!=null?L:hn.error:hn[c]};function fe(c,g,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",c.appendChild(L)}else c.textContent=g}let{wrapper:le,panel:ie,pillRoot:Ye}=Nu(r),Ae=Ou(r,$()),{container:pe,body:Q,messagesWrapper:je,suggestions:At,textarea:X,sendButton:Fe,sendButtonWrapper:kn,composerForm:Ot,statusText:cn,introTitle:Bn,introSubtitle:Yn,closeButton:B,iconHolder:se,headerTitle:De,headerSubtitle:Qe,header:_e,footer:$e,actionsRow:ot,leftActions:St,rightActions:$t}=Ae,Jt=Ae.setSendButtonMode,J=Ae.micButton,ft=Ae.micButtonWrapper,rt=Ae.attachmentButton,qt=Ae.attachmentButtonWrapper,ae=Ae.attachmentInput,xe=Ae.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Q.classList.add("persona-relative");let Ct=12,jt=()=>{var c;return(c=we.label)!=null?c:""},en=()=>{var c;return(c=we.iconName)!=null?c:"arrow-down"},bn=()=>we.enabled!==!1,Mt=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");Mt.type="button",Mt.style.display="none",Mt.setAttribute("data-persona-scroll-to-bottom","true");let Et=h("span","persona-flex persona-items-center"),yt=h("span","");Mt.append(Et,yt),pe.appendChild(Mt);let xt=()=>{let g=$e.style.display==="none"?0:$e.offsetHeight;Mt.style.bottom=`${g+Ct}px`};xt();let zt=()=>{let c=!!jt();Mt.setAttribute("aria-label",jt()||"Jump to latest"),Mt.title=jt(),Mt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Et.innerHTML="";let g=be(en(),"14px","currentColor",2);g?(Et.appendChild(g),Et.style.display=""):Et.style.display="none",yt.textContent=jt(),yt.style.display=c?"":"none"};zt();let tt=null,Dn=null,Zn=s.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:r,defaultRenderer:()=>{let g=_r({config:r,showClose:$()});return No(pe,g,r),g.header},onClose:()=>Ht(!1,"user")});if(c){let g=pe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),_e=c)}}let xn=()=>{var g,y,b,L;if(!K)return;if(ge=!0,!he&&K&&(he=im({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Nn(),config:r,plugins:s,getThroughput:()=>{var N;return(N=ue==null?void 0:ue.getMetric())!=null?N:{status:"idle"}}})),he&&(Q.style.display="none",(g=$e.parentNode)==null||g.insertBefore(he.element,$e),he.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(L=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:L.toggleButtonActive;N&&N.split(/\s+/).forEach(F=>F&&mt.classList.add(F))}let c=()=>{if(!ge)return;let N=Date.now();N-Xe>=200&&(he==null||he.update(),Xe=N),me=requestAnimationFrame(c)};Xe=0,me=requestAnimationFrame(c),Rr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,g,y;if(ge){if(ge=!1,he&&he.element.remove(),Q.style.display="",mt){mt.style.boxShadow="";let b=(y=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(L=>L&&mt.classList.remove(L))}me!==null&&(cancelAnimationFrame(me),me=null),Rr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(de){let c=(kc=(Mc=r.features)==null?void 0:Mc.eventStream)==null?void 0:kc.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=h("button",g),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&mt.appendChild(y);let b=Ae.clearChatButtonWrapper,L=Ae.closeButtonWrapper,N=b||L;N&&N.parentNode===_e?_e.insertBefore(mt,N):_e.appendChild(mt),mt.addEventListener("click",()=>{ge?Nn():xn()})}let vr=c=>{var b,L,N;let g=r.attachments;if(!(g!=null&&g.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let 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=g.allowedTypes)!=null?b:Fr).join(","),F.multiple=((L=g.maxFiles)!=null?L:4)>1,F.style.display="none",F.setAttribute("aria-label",(N=g.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(F)}},On=s.find(c=>c.renderComposer);if(On!=null&&On.renderComposer){let c=r.composer,g=On.renderComposer({config:r,defaultRenderer:()=>cs({config:r}).footer,onSubmit:y=>{var F;if(!E||E.isStreaming())return;let b=y.trim(),L=(F=tt==null?void 0:tt.hasAttachments())!=null?F:!1;if(!b&&!L)return;ks();let N;L&&(N=[],N.push(...tt.getContentParts()),b&&N.push(qs(b))),E.sendMessage(b,{contentParts:N}),L&&tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ae==null||ae.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:((Lc=r.voiceRecognition)==null?void 0:Lc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});g&&($e.replaceWith(g),$e=g)}let ho=c=>{let g=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),L=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");g&&(Ot=g),y&&(X=y),b&&(Fe=b),L&&(J=L,ft=L.parentElement),N&&(cn=N);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(At=F);let q=c.querySelector(".persona-attachment-button");q&&(rt=q,qt=q.parentElement),ae=c.querySelector('input[type="file"]'),xe=c.querySelector(".persona-attachment-previews");let H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(ot=H)};vr($e),ho($e);let Ln=(Hc=(Pc=r.layout)==null?void 0:Pc.contentMaxWidth)!=null?Hc:_()?(Rc=(Wc=(Ic=r.launcher)==null?void 0:Ic.composerBar)==null?void 0:Wc.contentMaxWidth)!=null?Rc:"720px":void 0;if(Ln&&(je.style.maxWidth=Ln,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%"),Ln&&Ot&&!_()&&(Ot.style.maxWidth=Ln,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Ln&&At&&!_()&&(At.style.maxWidth=Ln,At.style.marginLeft="auto",At.style.marginRight="auto"),Ln&&xe&&!_()&&(xe.style.maxWidth=Ln,xe.style.marginLeft="auto",xe.style.marginRight="auto"),(Bc=r.attachments)!=null&&Bc.enabled&&ae&&xe){tt=Do.fromConfig(r.attachments),tt.setPreviewsContainer(xe),ae.addEventListener("change",y=>{let b=y.target;tt==null||tt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,g=Sm(c);pe.appendChild(g)}(()=>{var b,L;let c=(L=(b=r.layout)==null?void 0:b.slots)!=null?L:{},g=N=>{switch(N){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return je;case"footer-top":return At;case"composer":return Ot;case"footer-bottom":return cn;default:return null}},y=(N,F)=>{var q;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")_e.insertBefore(F,_e.firstChild);else if(N==="header-right")_e.appendChild(F);else{let H=_e.querySelector(".persona-flex-col");H?(q=H.parentNode)==null||q.insertBefore(F,H.nextSibling):_e.appendChild(F)}break;case"body-top":{let H=Q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(F):Q.insertBefore(F,Q.firstChild);break}case"body-bottom":Q.appendChild(F);break;case"footer-top":At.replaceWith(F);break;case"footer-bottom":cn.replaceWith(F);break;default:break}};for(let[N,F]of Object.entries(c))if(F)try{let q=F({config:r,defaultContent:()=>g(N)});q&&y(N,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,q)}})();let zr=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 L=b.getAttribute("data-message-id");if(!L)return;let N=y.getAttribute("data-bubble-type");N==="reasoning"?(ps.has(L)?ps.delete(L):ps.add(L),ju(L,b)):N==="tool"&&(us.has(L)?us.delete(L):us.add(L),Uu(L,b,r)),ur.delete(L)};je.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))}),je.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))});let Mr=new Map;je.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 L=b.getAttribute("data-actions-for");if(!L)return;let N=y.getAttribute("data-action");if(N==="copy"){let H=E.getMessages().find(Ce=>Ce.id===L);if(H&&V.onCopy){let Ce=H.content||"";navigator.clipboard.writeText(Ce).then(()=>{y.classList.add("persona-message-action-success");let ce=be("check",14,"currentColor",2);ce&&(y.innerHTML="",y.appendChild(ce)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let te=be("copy",14,"currentColor",2);te&&(y.innerHTML="",y.appendChild(te))},2e3)}).catch(ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ce)}),V.onCopy(H)}}else if(N==="upvote"||N==="downvote"){let H=((F=Mr.get(L))!=null?F:null)===N,Ce=N==="upvote"?"thumbs-up":"thumbs-down";if(H){Mr.delete(L),y.classList.remove("persona-message-action-active");let ce=be(Ce,14,"currentColor",2);ce&&(y.innerHTML="",y.appendChild(ce))}else{let ce=N==="upvote"?"downvote":"upvote",te=b.querySelector(`[data-action="${ce}"]`);if(te){te.classList.remove("persona-message-action-active");let Ge=be(ce==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(te.innerHTML="",te.appendChild(Ge))}Mr.set(L,N),y.classList.add("persona-message-action-active");let ye=be(Ce,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ye)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Be=E.getMessages().find(nt=>nt.id===L);Be&&V.onFeedback&&V.onFeedback({type:N,messageId:Be.id,message:Be})}}}),je.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 L=b.getAttribute("data-message-id");if(!L)return;let N=y.getAttribute("data-approval-action");if(!N)return;let F=N==="approve"?"approved":"denied",H=E.getMessages().find(ce=>ce.id===L);if(!(H!=null&&H.approval))return;let Ce=b.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?E.resolveWebMcpApproval(L,F):E.resolveApproval(H.approval,F)});let vt=null,Fn=null,_n={artifacts:[],selectedId:null},vn=!1,It={current:null};je.addEventListener("click",c=>{var te,ye,Se,Be,nt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Se=(ye=(te=r.features)==null?void 0:te.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Se.call(ye,{type:"download",artifactId:b}))===!0)return;let N=E.getArtifactById(b),F=N==null?void 0:N.markdown,q=(N==null?void 0:N.title)||"artifact";if(!F){let Ge=y.closest("[data-open-artifact]"),lt=Ge==null?void 0:Ge.closest("[data-message-id]"),ct=lt==null?void 0:lt.getAttribute("data-message-id");if(ct){let Te=E.getMessages().find(Ue=>Ue.id===ct);if(Te!=null&&Te.rawContent)try{let Ue=JSON.parse(Te.rawContent);F=(Be=Ue==null?void 0:Ue.props)==null?void 0:Be.markdown,q=((nt=Ue==null?void 0:Ue.props)==null?void 0:nt.title)||q}catch{}}}if(!F)return;let H=new Blob([F],{type:"text/markdown"}),Ce=URL.createObjectURL(H),ce=document.createElement("a");ce.href=Ce,ce.download=`${q}.md`,ce.click(),URL.revokeObjectURL(Ce)}),je.addEventListener("click",c=>{var N,F,q;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((q=(F=(N=r.features)==null?void 0:N.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:q.call(F,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),vn=!1,E.selectArtifact(b),Un())}),je.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let er=Ae.composerOverlay,tr=(c,g,y)=>{var q,H,Ce,ce;let b=g.trim();if(!b||!It.current)return;let L=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",N=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:b,answers:y.structured,values:(H=y.values)!=null?H:y.source==="multi"?b.split(", "):[b],isFreeText:N,source:y.source},bubbles:!0,composed:!0})),mo(er,L);let F=It.current.getMessages().find(te=>{var ye;return((ye=te.toolCall)==null?void 0:ye.id)===L});(Ce=F==null?void 0:F.agentMetadata)!=null&&Ce.awaitingLocalTool?It.current.resolveAskUserQuestion(F,(ce=y.structured)!=null?ce:b):It.current.sendMessage(b)},$n=c=>{var L;let g=It.current;if(!g)return;let y=(L=c.getAttribute("data-tool-call-id"))!=null?L:"",b=g.getMessages().find(N=>{var F;return((F=N.toolCall)==null?void 0:F.id)===y});b&&g.persistAskUserQuestionProgress(b,{answers:Ai(c,b),currentIndex:lr(c)})},Vr=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),kr=c=>{var L,N,F;if(((N=(L=r.features)==null?void 0:L.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=lr(c),y=gs(c);if(g>=y-1)return;let b=(F=It.current)==null?void 0:F.getMessages().find(q=>{var H;return((H=q.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});b&&(Si(c,b,r,g+1),$n(c))};er.addEventListener("click",c=>{var N,F,q,H,Ce,ce,te,ye,Se,Be,nt,Ge,lt,ct;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 L=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),L==="dismiss"){let Me=(N=b.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),mo(er,Me);let Te=(F=It.current)==null?void 0:F.getMessages().find(Ue=>{var M;return((M=Ue.toolCall)==null?void 0:M.id)===Me});(q=Te==null?void 0:Te.agentMetadata)!=null&&q.awaitingLocalTool&&((H=It.current)==null||H.markAskUserQuestionResolved(Te),(Ce=It.current)==null||Ce.resolveAskUserQuestion(Te,"(dismissed)"));return}if(L==="pick"){let Me=y.getAttribute("data-option-label");if(!Me)return;let Te=b.getAttribute("data-multi-select")==="true",Ue=uo(b);if(Ue&&Te){let M=Fo(b)[lr(b)],Ee=new Set(Array.isArray(M)?M:[]);Ee.has(Me)?Ee.delete(Me):Ee.add(Me),go(b,Array.from(Ee)),$n(b);return}if(Ue){go(b,Me),$n(b),kr(b);return}if(Te){let M=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",M?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!M);let Ee=b.querySelector('[data-ask-user-action="submit-multi"]');Ee&&(Ee.disabled=Cl(b).length===0);return}tr(b,Me,{source:"pick",values:[Me]});return}if(L==="submit-multi"){let Me=Cl(b);if(Me.length===0)return;tr(b,Me.join(", "),{source:"multi",values:Me});return}if(L==="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(L==="focus-free-text"){let Me=b.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus();return}if(L==="submit-free-text"){let Me=b.querySelector('[data-ask-free-text-input="true"]'),Te=(ce=Me==null?void 0:Me.value)!=null?ce:"";if(!Te.trim())return;if(uo(b)){go(b,Te.trim()),$n(b),kr(b);return}tr(b,Te,{source:"free-text"});return}if(L==="next"||L==="back"){if(!It.current)return;let Me=(te=b.getAttribute("data-tool-call-id"))!=null?te:"",Te=It.current.getMessages().find(Ve=>{var ve;return((ve=Ve.toolCall)==null?void 0:ve.id)===Me});if(!Te)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),M=(Se=(ye=Ue==null?void 0:Ue.value)==null?void 0:ye.trim())!=null?Se:"";if(M){let Ve=Fo(b)[lr(b)];(typeof Ve!="string"||Ve!==M)&&go(b,M)}let Ee=L==="next"?1:-1,Ie=lr(b)+Ee;Si(b,Te,r,Ie),$n(b);return}if(L==="submit-all"){if(!It.current)return;let Me=(Be=b.getAttribute("data-tool-call-id"))!=null?Be:"",Te=It.current.getMessages().find(Ve=>{var ve;return((ve=Ve.toolCall)==null?void 0:ve.id)===Me});if(!Te)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),M=(Ge=(nt=Ue==null?void 0:Ue.value)==null?void 0:nt.trim())!=null?Ge:"";M&&go(b,M);let Ee=Ai(b,Te);It.current.persistAskUserQuestionProgress(Te,{answers:Ee,currentIndex:lr(b)});let Ie=Vr(Ee);tr(b,Ie||"(submitted)",{source:"submit-all",structured:Ee});return}if(L==="skip"){if(!It.current)return;let Me=(lt=b.getAttribute("data-tool-call-id"))!=null?lt:"",Te=It.current.getMessages().find(ve=>{var Pt;return((Pt=ve.toolCall)==null?void 0:Pt.id)===Me});if(!Te)return;let Ue=uo(b),M=lr(b),Ee=gs(b),Ie=M>=Ee-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),mo(er,Me),(ct=Te.agentMetadata)!=null&&ct.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Te),It.current.resolveAskUserQuestion(Te,"(dismissed)"));return}go(b,"");let Ve=b.querySelector('[data-ask-free-text-input="true"]');if(Ve&&(Ve.value=""),Ie){let ve=Ai(b,Te),Pt=Vr(ve);tr(b,Pt||"(skipped)",{source:"submit-all",structured:ve});return}Si(b,Te,r,M+1),$n(b);return}}),er.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let y=c.target;if(!((N=y.matches)!=null&&N.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let L=y.value;if(L.trim()){if(uo(b)){go(b,L.trim()),$n(b),kr(b);return}tr(b,L,{source:"free-text"})}});let Kr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let y=er.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),N=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];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",Kr);let jn=null,Rt=null,wn=null,nr=null,Jr=()=>{};function Lr(){nr==null||nr(),nr=null}let Gr=()=>{var F;if(!jn||!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=jn.firstElementChild;if(!b||b===Rt)return;let L=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${L}px`,Rt.style.zIndex="5";let N=b.offsetWidth-L/2;Rt.style.left=`${Math.max(0,N)}px`},wr=()=>{},Un=()=>{var y,b,L,N,F;if(!vt||!cr(r))return;Ti(e,r),Mi(e,r),wr();let c=(N=(L=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:L.narrowHostMaxWidth)!=null?N:520,g=ie.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),vt.update(_n),vn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(F=vt.backdrop)==null||F.classList.add("persona-hidden")):_n.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),Jr()};if(cr(r)){ie.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(pe),vt=dm(r,{onSelect:y=>{var b;return(b=It.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{vn=!0,Un()}}),vt.element.classList.add("persona-hidden"),jn=g,g.appendChild(c),g.appendChild(vt.element),vt.backdrop&&ie.appendChild(vt.backdrop),ie.appendChild(g),Jr=()=>{var b,L,N,F;if(!jn||!vt)return;if(!(((N=(L=(b=r.features)==null?void 0:b.artifacts)==null?void 0:L.layout)==null?void 0:N.resizable)===!0)){wn==null||wn(),wn=null,Lr(),Rt&&(Rt.remove(),Rt=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Rt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let H=e.ownerDocument,Ce=(F=H.defaultView)!=null?F:window,ce=te=>{var lt,ct;if(!vt||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;te.preventDefault(),Lr();let ye=te.clientX,Se=vt.element.getBoundingClientRect().width,Be=(ct=(lt=r.features)==null?void 0:lt.artifacts)==null?void 0:ct.layout,nt=Me=>{let Te=jn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),M=Ue?0:gm(jn,Ce),Ee=Ue?0:q.getBoundingClientRect().width||6,Ie=Se-(Me.clientX-ye),Ve=fm(Ie,Te,M,Ee,Be==null?void 0:Be.resizableMinWidth,Be==null?void 0:Be.resizableMaxWidth);vt.element.style.width=`${Ve}px`,vt.element.style.maxWidth="none",Gr()},Ge=()=>{H.removeEventListener("pointermove",nt),H.removeEventListener("pointerup",Ge),H.removeEventListener("pointercancel",Ge),nr=null;try{q.releasePointerCapture(te.pointerId)}catch{}};nr=Ge,H.addEventListener("pointermove",nt),H.addEventListener("pointerup",Ge),H.addEventListener("pointercancel",Ge);try{q.setPointerCapture(te.pointerId)}catch{}};q.addEventListener("pointerdown",ce),Rt=q,jn.insertBefore(q,vt.element),wn=()=>{q.removeEventListener("pointerdown",ce)}}if(Rt){let q=_n.artifacts.length>0&&!vn;Rt.classList.toggle("persona-hidden",!q),Gr()}},wr=()=>{var Ce,ce,te,ye,Se,Be,nt,Ge,lt,ct,Me,Te,Ue,M;if(!S||!vt||((ce=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?ce:!1)||on(r)&&ir(r).reveal==="emerge")return;let b=(te=e.ownerDocument.defaultView)!=null?te:window,L=(Se=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Se:!0,N=(nt=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?nt:640;if(L&&b.innerWidth<=N||!mm(r,S))return;let F=(ct=(lt=(Ge=r.launcher)==null?void 0:Ge.width)!=null?lt:r.launcherWidth)!=null?ct:Xn,q=(M=(Ue=(Te=(Me=r.features)==null?void 0:Me.artifacts)==null?void 0:Te.layout)==null?void 0:Ue.expandedPanelWidth)!=null?M:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!vn?(ie.style.width=q,ie.style.maxWidth=q):(ie.style.width=F,ie.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Un()}),Fn.observe(ie))}else ie.appendChild(pe),_()&&Ye&&(Ae.peekBanner&&Ye.appendChild(Ae.peekBanner),Ye.appendChild($e));e.appendChild(le),Ye&&e.appendChild(Ye);let dr=()=>{var Ve,ve,Pt,at,Yt,pn,Wt,An,un,et,dt,Sn,gn,Co,Ao,So,Yo,Zo,Vt,Eo,oo,bt,In,Dr,En,Wn,Bt,Ut;if(_()){ie.style.width="100%",ie.style.maxWidth="100%";let Dt=(ve=(Ve=r.launcher)==null?void 0:Ve.composerBar)!=null?ve:{},Kt=le.dataset.state==="expanded",Rn=(Pt=Dt.expandedSize)!=null?Pt:"anchored";if(!(Kt&&Rn!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let rn=(Yt=(at=r.theme)==null?void 0:at.components)==null?void 0:Yt.panel,Sr=is(r),Nr=(To,Ra)=>{var Ds;return To==null||To===""?Ra:(Ds=ss(Sr,To))!=null?Ds:To},Pa="1px solid var(--persona-border)",Ia="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Wa="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Nr(rn==null?void 0:rn.border,Pa),pe.style.borderRadius=Nr(rn==null?void 0:rn.borderRadius,Wa),pe.style.boxShadow=Nr(rn==null?void 0:rn.shadow,Ia),pe.style.overflow="hidden";return}let c=on(r),g=(Wt=(pn=r.launcher)==null?void 0:pn.sidebarMode)!=null?Wt:!1,y=c||g||((un=(An=r.launcher)==null?void 0:An.fullHeight)!=null?un:!1),b=((et=r.launcher)==null?void 0:et.enabled)===!1,L=(Sn=(dt=r.theme)==null?void 0:dt.components)==null?void 0:Sn.panel,N=is(r),F=(Dt,Kt)=>{var Rn;return Dt==null||Dt===""?Kt:(Rn=ss(N,Dt))!=null?Rn:Dt},q=(gn=e.ownerDocument.defaultView)!=null?gn:window,H=(Ao=(Co=r.launcher)==null?void 0:Co.mobileFullscreen)!=null?Ao:!0,Ce=(Yo=(So=r.launcher)==null?void 0:So.mobileBreakpoint)!=null?Yo:640,ce=q.innerWidth<=Ce,te=H&&ce&&S,ye=(Vt=(Zo=r.launcher)==null?void 0:Zo.position)!=null?Vt:"bottom-left",Se=ye==="bottom-left"||ye==="top-left",Be=(oo=(Eo=r.launcher)==null?void 0:Eo.zIndex)!=null?oo:yn,nt=g||te?"none":"1px solid var(--persona-border)",Ge=te?"none":g?Se?"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&&!te&&(Ge="none",nt="none");let lt=g||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=F(L==null?void 0:L.border,nt),Me=F(L==null?void 0:L.shadow,Ge),Te=F(L==null?void 0:L.borderRadius,lt),Ue=Q.scrollTop;e.style.cssText="",le.style.cssText="",ie.style.cssText="",pe.style.cssText="",Q.style.cssText="",$e.style.cssText="";let M=()=>{var Kt;if(Ue<=0)return;((Kt=Q.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(Q.scrollTop===Ue)return;let Rn=Q.scrollHeight-Q.clientHeight;Rn<=0||(Q.scrollTop=Math.min(Ue,Rn))})};if(te){le.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"),le.style.cssText=`
30
+ `,H.addEventListener("click",()=>{p=w,S.forEach((_,$)=>{let N=$<w;_.classList.toggle("selected",N),_.setAttribute("aria-checked",$===w-1?"true":"false")})}),S.push(H),E.appendChild(H)}f.appendChild(E);let R=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=o,R.rows=3,R.setAttribute("aria-label","Additional comments"),w.appendChild(R),f.appendChild(w)}let I=document.createElement("div");I.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{t==null||t(),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){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let w=(R==null?void 0:R.value.trim())||void 0;await n(p,w),u.remove()}catch(w){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),I.appendChild(W),I.appendChild(P),f.appendChild(I),u.appendChild(f),u}function Hi(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,x.appendChild(E),m.appendChild(x);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 R=document.createElement("div");R.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=l;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=u,R.appendChild(I),R.appendChild(W);let P=document.createElement("div");P.className="persona-feedback-numbers";let w=[];for(let U=0;U<=10;U++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${U} out of 10`),z.textContent=String(U),z.dataset.rating=String(U),U<=6?z.classList.add("persona-feedback-detractor"):U<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{f=U,w.forEach((oe,We)=>{oe.classList.toggle("selected",We===U),oe.setAttribute("aria-checked",We===U?"true":"false")})}),w.push(z),P.appendChild(z)}S.appendChild(R),S.appendChild(P),m.appendChild(S);let H=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=o,H.rows=3,H.setAttribute("aria-label","Additional comments"),U.appendChild(H),m.appendChild(U)}let _=document.createElement("div");_.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{t==null||t(),p.remove()});let N=document.createElement("button");return N.type="button",N.className="persona-feedback-btn persona-feedback-btn-submit",N.textContent=a,N.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let U=(H==null?void 0:H.value.trim())||void 0;await n(f,U),p.remove()}catch(U){N.disabled=!1,N.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),_.appendChild($),_.appendChild(N),m.appendChild(_),p.appendChild(m),p}var ys="persona-chat-history",Wh=30*1e3,Rh={"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 Hh(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=Rh[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function Bi(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 Bh(e){var n,t,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Dh(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Pl=e=>!e||typeof e!="object"?{}:{...e},Sm=e=>e.map(n=>({...n,streaming:!1})),Tm=(e,n,t)=>{let r=e!=null&&e.markdown?Lo(e.markdown):null,s=es(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=Po(a),s?s(d):d}};function Em(e){var i,d,l,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=ye(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,n.appendChild(p)}return n}var Di=(e,n,t)=>{var tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,xc,vc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Jc;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=Za(n),s=da.getForInstance(r.plugins);r.components&&Ur.registerAll(r.components);let o=xm(),i=r.persistState===!1?null:(tc=r.storageAdapter)!=null?tc:ki(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let g=r.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:y}=g;return y&&(u=!0),b}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let b=g!=null?g:{messages:[],metadata:{}};return p(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=p(g);b.metadata&&(d=Pl(b.metadata)),(nc=b.messages)!=null&&nc.length&&(r={...r,initialMessages:b.messages}),(rc=b.artifacts)!=null&&rc.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(oc=b.selectedArtifactId)!=null?oc: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:{}});(sc=c.messages)!=null&&sc.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var b;d=(b=c({...d}))!=null?b:{},zo()},x=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[$o.message,$o.messageAndClick],E=ua({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let S=(ic=(ac=r.launcher)==null?void 0:ac.enabled)!=null?ic:!0,R=(cc=(lc=r.launcher)==null?void 0:lc.autoExpand)!=null?cc:!1,I=(dc=r.autoFocusInput)!=null?dc:!1,W=R,P=S,w=(uc=(pc=r.layout)==null?void 0:pc.header)==null?void 0:uc.layout,H=!1,_=()=>lo(r),$=()=>S||_(),N=_()?!1:S?R:!0,U=!1,z=null,oe=()=>{U=!0,z&&clearTimeout(z),z=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},We=Tm(r,E,oe),He=(gc=(mc=r.features)==null?void 0:mc.showReasoning)!=null?gc:!0,Oe=(hc=(fc=r.features)==null?void 0:fc.showToolCalls)!=null?hc:!0,de=(yc=(bc=r.features)==null?void 0:bc.showEventStreamToggle)!=null?yc:!1,we=(vc=(xc=r.features)==null?void 0:xc.scrollToBottom)!=null?vc:{},Pe=`${(Cc=typeof r.persistState=="object"?(wc=r.persistState)==null?void 0:wc.keyPrefix:void 0)!=null?Cc:"persona-"}event-stream`,re=de?new la(Pe):null,Le=(Tc=(Sc=(Ac=r.features)==null?void 0:Ac.eventStream)==null?void 0:Sc.maxEvents)!=null?Tc:2e3,K=de?new ia(Le,re):null,ue=de?new ca:null,he=null,ge=!1,me=null,Xe=0;re==null||re.open().then(()=>K==null?void 0:K.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let V={onCopy:c=>{var g,b;o.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;o.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},ne=(Ec=r.statusIndicator)!=null?Ec:{},Re=c=>{var g,b,y,L;return c==="idle"?(g=ne.idleText)!=null?g:hn.idle:c==="connecting"?(b=ne.connectingText)!=null?b:hn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:hn.connected:c==="error"?(L=ne.errorText)!=null?L:hn.error:hn[c]};function fe(c,g,b,y){if(y==="idle"&&b.idleLink){c.textContent="";let L=document.createElement("a");L.href=b.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",c.appendChild(L)}else c.textContent=g}let{wrapper:le,panel:ie,pillRoot:Ye}=Fu(r),Ae=_u(r,$()),{container:pe,body:Q,messagesWrapper:je,suggestions:At,textarea:X,sendButton:Fe,sendButtonWrapper:kn,composerForm:Ot,statusText:cn,introTitle:Bn,introSubtitle:Yn,closeButton:D,iconHolder:se,headerTitle:De,headerSubtitle:Qe,header:_e,footer:$e,actionsRow:ot,leftActions:St,rightActions:$t}=Ae,Jt=Ae.setSendButtonMode,J=Ae.micButton,ft=Ae.micButtonWrapper,rt=Ae.attachmentButton,qt=Ae.attachmentButtonWrapper,ae=Ae.attachmentInput,xe=Ae.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Q.classList.add("persona-relative");let Ct=12,jt=()=>{var c;return(c=we.label)!=null?c:""},en=()=>{var c;return(c=we.iconName)!=null?c:"arrow-down"},yn=()=>we.enabled!==!1,Mt=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");Mt.type="button",Mt.style.display="none",Mt.setAttribute("data-persona-scroll-to-bottom","true");let Tt=h("span","persona-flex persona-items-center"),bt=h("span","");Mt.append(Tt,bt),pe.appendChild(Mt);let xt=()=>{let g=$e.style.display==="none"?0:$e.offsetHeight;Mt.style.bottom=`${g+Ct}px`};xt();let zt=()=>{let c=!!jt();Mt.setAttribute("aria-label",jt()||"Jump to latest"),Mt.title=jt(),Mt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Tt.innerHTML="";let g=ye(en(),"14px","currentColor",2);g?(Tt.appendChild(g),Tt.style.display=""):Tt.style.display="none",bt.textContent=jt(),bt.style.display=c?"":"none"};zt();let tt=null,Dn=null,Zn=s.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:r,defaultRenderer:()=>{let g=_r({config:r,showClose:$()});return No(pe,g,r),g.header},onClose:()=>Ht(!1,"user")});if(c){let g=pe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),_e=c)}}let xn=()=>{var g,b,y,L;if(!K)return;if(ge=!0,!he&&K&&(he=cm({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Nn(),config:r,plugins:s,getThroughput:()=>{var O;return(O=ue==null?void 0:ue.getMetric())!=null?O:{status:"idle"}}})),he&&(Q.style.display="none",(g=$e.parentNode)==null||g.insertBefore(he.element,$e),he.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let O=(L=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:L.toggleButtonActive;O&&O.split(/\s+/).forEach(F=>F&&mt.classList.add(F))}let c=()=>{if(!ge)return;let O=Date.now();O-Xe>=200&&(he==null||he.update(),Xe=O),me=requestAnimationFrame(c)};Xe=0,me=requestAnimationFrame(c),Rr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,g,b;if(ge){if(ge=!1,he&&he.element.remove(),Q.style.display="",mt){mt.style.boxShadow="";let y=(b=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;y&&y.split(/\s+/).forEach(L=>L&&mt.classList.remove(L))}me!==null&&(cancelAnimationFrame(me),me=null),Rr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(de){let c=(kc=(Mc=r.features)==null?void 0:Mc.eventStream)==null?void 0:kc.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=h("button",g),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let b=ye("activity","18px","currentColor",1.5);b&&mt.appendChild(b);let y=Ae.clearChatButtonWrapper,L=Ae.closeButtonWrapper,O=y||L;O&&O.parentNode===_e?_e.insertBefore(mt,O):_e.appendChild(mt),mt.addEventListener("click",()=>{ge?Nn():xn()})}let vr=c=>{var y,L,O;let g=r.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let F=c.querySelector("[data-persona-composer-form]");F!=null&&F.parentNode?F.parentNode.insertBefore(b,F):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let F=h("input");F.type="file",F.accept=((y=g.allowedTypes)!=null?y:Fr).join(","),F.multiple=((L=g.maxFiles)!=null?L:4)>1,F.style.display="none",F.setAttribute("aria-label",(O=g.buttonTooltipText)!=null?O:"Attach files"),c.appendChild(F)}},On=s.find(c=>c.renderComposer);if(On!=null&&On.renderComposer){let c=r.composer,g=On.renderComposer({config:r,defaultRenderer:()=>cs({config:r}).footer,onSubmit:b=>{var F;if(!T||T.isStreaming())return;let y=b.trim(),L=(F=tt==null?void 0:tt.hasAttachments())!=null?F:!1;if(!y&&!L)return;ks();let O;L&&(O=[],O.push(...tt.getContentParts()),y&&O.push(qs(y))),T.sendMessage(y,{contentParts:O}),L&&tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ae==null||ae.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},onVoiceToggle:((Lc=r.voiceRecognition)==null?void 0:Lc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});g&&($e.replaceWith(g),$e=g)}let ho=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),L=c.querySelector("[data-persona-composer-mic]"),O=c.querySelector("[data-persona-composer-status]");g&&(Ot=g),b&&(X=b),y&&(Fe=y),L&&(J=L,ft=L.parentElement),O&&(cn=O);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(At=F);let q=c.querySelector(".persona-attachment-button");q&&(rt=q,qt=q.parentElement),ae=c.querySelector('input[type="file"]'),xe=c.querySelector(".persona-attachment-previews");let B=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(ot=B)};vr($e),ho($e);let Ln=(Hc=(Pc=r.layout)==null?void 0:Pc.contentMaxWidth)!=null?Hc:_()?(Rc=(Wc=(Ic=r.launcher)==null?void 0:Ic.composerBar)==null?void 0:Wc.contentMaxWidth)!=null?Rc:"720px":void 0;if(Ln&&(je.style.maxWidth=Ln,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%"),Ln&&Ot&&!_()&&(Ot.style.maxWidth=Ln,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Ln&&At&&!_()&&(At.style.maxWidth=Ln,At.style.marginLeft="auto",At.style.marginRight="auto"),Ln&&xe&&!_()&&(xe.style.maxWidth=Ln,xe.style.marginLeft="auto",xe.style.marginRight="auto"),(Bc=r.attachments)!=null&&Bc.enabled&&ae&&xe){tt=Do.fromConfig(r.attachments),tt.setPreviewsContainer(xe),ae.addEventListener("change",b=>{let y=b.target;tt==null||tt.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=Em(c);pe.appendChild(g)}(()=>{var y,L;let c=(L=(y=r.layout)==null?void 0:y.slots)!=null?L:{},g=O=>{switch(O){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return je;case"footer-top":return At;case"composer":return Ot;case"footer-bottom":return cn;default:return null}},b=(O,F)=>{var q;switch(O){case"header-left":case"header-center":case"header-right":if(O==="header-left")_e.insertBefore(F,_e.firstChild);else if(O==="header-right")_e.appendChild(F);else{let B=_e.querySelector(".persona-flex-col");B?(q=B.parentNode)==null||q.insertBefore(F,B.nextSibling):_e.appendChild(F)}break;case"body-top":{let B=Q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(F):Q.insertBefore(F,Q.firstChild);break}case"body-bottom":Q.appendChild(F);break;case"footer-top":At.replaceWith(F);break;case"footer-bottom":cn.replaceWith(F);break;default:break}};for(let[O,F]of Object.entries(c))if(F)try{let q=F({config:r,defaultContent:()=>g(O)});q&&b(O,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${O}":`,q)}})();let zr=c=>{let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let y=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let L=y.getAttribute("data-message-id");if(!L)return;let O=b.getAttribute("data-bubble-type");O==="reasoning"?(ps.has(L)?ps.delete(L):ps.add(L),qu(L,y)):O==="tool"&&(us.has(L)?us.delete(L):us.add(L),zu(L,y,r)),ur.delete(L)};je.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))}),je.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))});let Mr=new Map;je.addEventListener("click",c=>{var F;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest("[data-actions-for]");if(!y)return;let L=y.getAttribute("data-actions-for");if(!L)return;let O=b.getAttribute("data-action");if(O==="copy"){let B=T.getMessages().find(Ce=>Ce.id===L);if(B&&V.onCopy){let Ce=B.content||"";navigator.clipboard.writeText(Ce).then(()=>{b.classList.add("persona-message-action-success");let ce=ye("check",14,"currentColor",2);ce&&(b.innerHTML="",b.appendChild(ce)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let te=ye("copy",14,"currentColor",2);te&&(b.innerHTML="",b.appendChild(te))},2e3)}).catch(ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ce)}),V.onCopy(B)}}else if(O==="upvote"||O==="downvote"){let B=((F=Mr.get(L))!=null?F:null)===O,Ce=O==="upvote"?"thumbs-up":"thumbs-down";if(B){Mr.delete(L),b.classList.remove("persona-message-action-active");let ce=ye(Ce,14,"currentColor",2);ce&&(b.innerHTML="",b.appendChild(ce))}else{let ce=O==="upvote"?"downvote":"upvote",te=y.querySelector(`[data-action="${ce}"]`);if(te){te.classList.remove("persona-message-action-active");let Ge=ye(ce==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(te.innerHTML="",te.appendChild(Ge))}Mr.set(L,O),b.classList.add("persona-message-action-active");let be=ye(Ce,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(be)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Be=T.getMessages().find(nt=>nt.id===L);Be&&V.onFeedback&&V.onFeedback({type:O,messageId:Be.id,message:Be})}}}),je.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest(".persona-approval-bubble");if(!y)return;let L=y.getAttribute("data-message-id");if(!L)return;let O=b.getAttribute("data-approval-action");if(!O)return;let F=O==="approve"?"approved":"denied",B=T.getMessages().find(ce=>ce.id===L);if(!(B!=null&&B.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?T.resolveWebMcpApproval(L,F):T.resolveApproval(B.approval,F)});let vt=null,Fn=null,_n={artifacts:[],selectedId:null},vn=!1,It={current:null};je.addEventListener("click",c=>{var te,be,Se,Be,nt;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((Se=(be=(te=r.features)==null?void 0:te.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Se.call(be,{type:"download",artifactId:y}))===!0)return;let O=T.getArtifactById(y),F=O==null?void 0:O.markdown,q=(O==null?void 0:O.title)||"artifact";if(!F){let Ge=b.closest("[data-open-artifact]"),lt=Ge==null?void 0:Ge.closest("[data-message-id]"),ct=lt==null?void 0:lt.getAttribute("data-message-id");if(ct){let Ee=T.getMessages().find(Ue=>Ue.id===ct);if(Ee!=null&&Ee.rawContent)try{let Ue=JSON.parse(Ee.rawContent);F=(Be=Ue==null?void 0:Ue.props)==null?void 0:Be.markdown,q=((nt=Ue==null?void 0:Ue.props)==null?void 0:nt.title)||q}catch{}}}if(!F)return;let B=new Blob([F],{type:"text/markdown"}),Ce=URL.createObjectURL(B),ce=document.createElement("a");ce.href=Ce,ce.download=`${q}.md`,ce.click(),URL.revokeObjectURL(Ce)}),je.addEventListener("click",c=>{var O,F,q;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((q=(F=(O=r.features)==null?void 0:O.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:q.call(F,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),vn=!1,T.selectArtifact(y),Un())}),je.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let er=Ae.composerOverlay,tr=(c,g,b)=>{var q,B,Ce,ce;let y=g.trim();if(!y||!It.current)return;let L=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",O=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:y,answers:b.structured,values:(B=b.values)!=null?B:b.source==="multi"?y.split(", "):[y],isFreeText:O,source:b.source},bubbles:!0,composed:!0})),mo(er,L);let F=It.current.getMessages().find(te=>{var be;return((be=te.toolCall)==null?void 0:be.id)===L});(Ce=F==null?void 0:F.agentMetadata)!=null&&Ce.awaitingLocalTool?It.current.resolveAskUserQuestion(F,(ce=b.structured)!=null?ce:y):It.current.sendMessage(y)},$n=c=>{var L;let g=It.current;if(!g)return;let b=(L=c.getAttribute("data-tool-call-id"))!=null?L:"",y=g.getMessages().find(O=>{var F;return((F=O.toolCall)==null?void 0:F.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:Ai(c,y),currentIndex:lr(c)})},Vr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),kr=c=>{var L,O,F;if(((O=(L=r.features)==null?void 0:L.askUserQuestion)==null?void 0:O.groupedAutoAdvance)===!1)return;let g=lr(c),b=gs(c);if(g>=b-1)return;let y=(F=It.current)==null?void 0:F.getMessages().find(q=>{var B;return((B=q.toolCall)==null?void 0:B.id)===c.getAttribute("data-tool-call-id")});y&&(Si(c,y,r,g+1),$n(c))};er.addEventListener("click",c=>{var O,F,q,B,Ce,ce,te,be,Se,Be,nt,Ge,lt,ct;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;let L=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),L==="dismiss"){let Me=(O=y.getAttribute("data-tool-call-id"))!=null?O:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),mo(er,Me);let Ee=(F=It.current)==null?void 0:F.getMessages().find(Ue=>{var M;return((M=Ue.toolCall)==null?void 0:M.id)===Me});(q=Ee==null?void 0:Ee.agentMetadata)!=null&&q.awaitingLocalTool&&((B=It.current)==null||B.markAskUserQuestionResolved(Ee),(Ce=It.current)==null||Ce.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(L==="pick"){let Me=b.getAttribute("data-option-label");if(!Me)return;let Ee=y.getAttribute("data-multi-select")==="true",Ue=uo(y);if(Ue&&Ee){let M=Fo(y)[lr(y)],Te=new Set(Array.isArray(M)?M:[]);Te.has(Me)?Te.delete(Me):Te.add(Me),go(y,Array.from(Te)),$n(y);return}if(Ue){go(y,Me),$n(y),kr(y);return}if(Ee){let M=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",M?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!M);let Te=y.querySelector('[data-ask-user-action="submit-multi"]');Te&&(Te.disabled=Cl(y).length===0);return}tr(y,Me,{source:"pick",values:[Me]});return}if(L==="submit-multi"){let Me=Cl(y);if(Me.length===0)return;tr(y,Me.join(", "),{source:"multi",values:Me});return}if(L==="open-free-text"){let Me=y.querySelector('[data-ask-free-text-row="true"]');if(Me){Me.classList.remove("persona-hidden");let Ee=Me.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(L==="focus-free-text"){let Me=y.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus();return}if(L==="submit-free-text"){let Me=y.querySelector('[data-ask-free-text-input="true"]'),Ee=(ce=Me==null?void 0:Me.value)!=null?ce:"";if(!Ee.trim())return;if(uo(y)){go(y,Ee.trim()),$n(y),kr(y);return}tr(y,Ee,{source:"free-text"});return}if(L==="next"||L==="back"){if(!It.current)return;let Me=(te=y.getAttribute("data-tool-call-id"))!=null?te:"",Ee=It.current.getMessages().find(Ve=>{var ve;return((ve=Ve.toolCall)==null?void 0:ve.id)===Me});if(!Ee)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),M=(Se=(be=Ue==null?void 0:Ue.value)==null?void 0:be.trim())!=null?Se:"";if(M){let Ve=Fo(y)[lr(y)];(typeof Ve!="string"||Ve!==M)&&go(y,M)}let Te=L==="next"?1:-1,Ie=lr(y)+Te;Si(y,Ee,r,Ie),$n(y);return}if(L==="submit-all"){if(!It.current)return;let Me=(Be=y.getAttribute("data-tool-call-id"))!=null?Be:"",Ee=It.current.getMessages().find(Ve=>{var ve;return((ve=Ve.toolCall)==null?void 0:ve.id)===Me});if(!Ee)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),M=(Ge=(nt=Ue==null?void 0:Ue.value)==null?void 0:nt.trim())!=null?Ge:"";M&&go(y,M);let Te=Ai(y,Ee);It.current.persistAskUserQuestionProgress(Ee,{answers:Te,currentIndex:lr(y)});let Ie=Vr(Te);tr(y,Ie||"(submitted)",{source:"submit-all",structured:Te});return}if(L==="skip"){if(!It.current)return;let Me=(lt=y.getAttribute("data-tool-call-id"))!=null?lt:"",Ee=It.current.getMessages().find(ve=>{var Pt;return((Pt=ve.toolCall)==null?void 0:Pt.id)===Me});if(!Ee)return;let Ue=uo(y),M=lr(y),Te=gs(y),Ie=M>=Te-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Me},bubbles:!0,composed:!0})),mo(er,Me),(ct=Ee.agentMetadata)!=null&&ct.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Ee),It.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}go(y,"");let Ve=y.querySelector('[data-ask-free-text-input="true"]');if(Ve&&(Ve.value=""),Ie){let ve=Ai(y,Ee),Pt=Vr(ve);tr(y,Pt||"(skipped)",{source:"submit-all",structured:ve});return}Si(y,Ee,r,M+1),$n(y);return}}),er.addEventListener("keydown",c=>{var O;if(c.key!=="Enter")return;let b=c.target;if(!((O=b.matches)!=null&&O.call(b,'[data-ask-free-text-input="true"]')))return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let L=b.value;if(L.trim()){if(uo(y)){go(y,L.trim()),$n(y),kr(y);return}tr(y,L,{source:"free-text"})}});let Kr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let b=er.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),O=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];O&&(c.preventDefault(),O.click())};document.addEventListener("keydown",Kr);let jn=null,Rt=null,wn=null,nr=null,Jr=()=>{};function Lr(){nr==null||nr(),nr=null}let Gr=()=>{var F;if(!jn||!Rt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((F=e.ownerDocument.defaultView)!=null?F:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){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 y=jn.firstElementChild;if(!y||y===Rt)return;let L=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${L}px`,Rt.style.zIndex="5";let O=y.offsetWidth-L/2;Rt.style.left=`${Math.max(0,O)}px`},wr=()=>{},Un=()=>{var b,y,L,O,F;if(!vt||!cr(r))return;Ei(e,r),Mi(e,r),wr();let c=(O=(L=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:L.narrowHostMaxWidth)!=null?O:520,g=ie.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),vt.update(_n),vn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(F=vt.backdrop)==null||F.classList.add("persona-hidden")):_n.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),Jr()};if(cr(r)){ie.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(pe),vt=um(r,{onSelect:b=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{vn=!0,Un()}}),vt.element.classList.add("persona-hidden"),jn=g,g.appendChild(c),g.appendChild(vt.element),vt.backdrop&&ie.appendChild(vt.backdrop),ie.appendChild(g),Jr=()=>{var y,L,O,F;if(!jn||!vt)return;if(!(((O=(L=(y=r.features)==null?void 0:y.artifacts)==null?void 0:L.layout)==null?void 0:O.resizable)===!0)){wn==null||wn(),wn=null,Lr(),Rt&&(Rt.remove(),Rt=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Rt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let B=e.ownerDocument,Ce=(F=B.defaultView)!=null?F:window,ce=te=>{var lt,ct;if(!vt||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;te.preventDefault(),Lr();let be=te.clientX,Se=vt.element.getBoundingClientRect().width,Be=(ct=(lt=r.features)==null?void 0:lt.artifacts)==null?void 0:ct.layout,nt=Me=>{let Ee=jn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),M=Ue?0:hm(jn,Ce),Te=Ue?0:q.getBoundingClientRect().width||6,Ie=Se-(Me.clientX-be),Ve=bm(Ie,Ee,M,Te,Be==null?void 0:Be.resizableMinWidth,Be==null?void 0:Be.resizableMaxWidth);vt.element.style.width=`${Ve}px`,vt.element.style.maxWidth="none",Gr()},Ge=()=>{B.removeEventListener("pointermove",nt),B.removeEventListener("pointerup",Ge),B.removeEventListener("pointercancel",Ge),nr=null;try{q.releasePointerCapture(te.pointerId)}catch{}};nr=Ge,B.addEventListener("pointermove",nt),B.addEventListener("pointerup",Ge),B.addEventListener("pointercancel",Ge);try{q.setPointerCapture(te.pointerId)}catch{}};q.addEventListener("pointerdown",ce),Rt=q,jn.insertBefore(q,vt.element),wn=()=>{q.removeEventListener("pointerdown",ce)}}if(Rt){let q=_n.artifacts.length>0&&!vn;Rt.classList.toggle("persona-hidden",!q),Gr()}},wr=()=>{var Ce,ce,te,be,Se,Be,nt,Ge,lt,ct,Me,Ee,Ue,M;if(!S||!vt||((ce=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?ce:!1)||on(r)&&ir(r).reveal==="emerge")return;let y=(te=e.ownerDocument.defaultView)!=null?te:window,L=(Se=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Se:!0,O=(nt=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?nt:640;if(L&&y.innerWidth<=O||!fm(r,S))return;let F=(ct=(lt=(Ge=r.launcher)==null?void 0:Ge.width)!=null?lt:r.launcherWidth)!=null?ct:Xn,q=(M=(Ue=(Ee=(Me=r.features)==null?void 0:Me.artifacts)==null?void 0:Ee.layout)==null?void 0:Ue.expandedPanelWidth)!=null?M:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!vn?(ie.style.width=q,ie.style.maxWidth=q):(ie.style.width=F,ie.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Un()}),Fn.observe(ie))}else ie.appendChild(pe),_()&&Ye&&(Ae.peekBanner&&Ye.appendChild(Ae.peekBanner),Ye.appendChild($e));e.appendChild(le),Ye&&e.appendChild(Ye);let dr=()=>{var Ve,ve,Pt,at,Yt,pn,Wt,An,un,et,dt,Sn,gn,Co,Ao,So,Yo,Zo,Vt,To,oo,yt,In,Dr,Tn,Wn,Bt,Ut;if(_()){ie.style.width="100%",ie.style.maxWidth="100%";let Dt=(ve=(Ve=r.launcher)==null?void 0:Ve.composerBar)!=null?ve:{},Kt=le.dataset.state==="expanded",Rn=(Pt=Dt.expandedSize)!=null?Pt:"anchored";if(!(Kt&&Rn!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let rn=(Yt=(at=r.theme)==null?void 0:at.components)==null?void 0:Yt.panel,Sr=is(r),Nr=(Eo,Ra)=>{var Ds;return Eo==null||Eo===""?Ra:(Ds=ss(Sr,Eo))!=null?Ds:Eo},Pa="1px solid var(--persona-border)",Ia="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Wa="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Nr(rn==null?void 0:rn.border,Pa),pe.style.borderRadius=Nr(rn==null?void 0:rn.borderRadius,Wa),pe.style.boxShadow=Nr(rn==null?void 0:rn.shadow,Ia),pe.style.overflow="hidden";return}let c=on(r),g=(Wt=(pn=r.launcher)==null?void 0:pn.sidebarMode)!=null?Wt:!1,b=c||g||((un=(An=r.launcher)==null?void 0:An.fullHeight)!=null?un:!1),y=((et=r.launcher)==null?void 0:et.enabled)===!1,L=(Sn=(dt=r.theme)==null?void 0:dt.components)==null?void 0:Sn.panel,O=is(r),F=(Dt,Kt)=>{var Rn;return Dt==null||Dt===""?Kt:(Rn=ss(O,Dt))!=null?Rn:Dt},q=(gn=e.ownerDocument.defaultView)!=null?gn:window,B=(Ao=(Co=r.launcher)==null?void 0:Co.mobileFullscreen)!=null?Ao:!0,Ce=(Yo=(So=r.launcher)==null?void 0:So.mobileBreakpoint)!=null?Yo:640,ce=q.innerWidth<=Ce,te=B&&ce&&S,be=(Vt=(Zo=r.launcher)==null?void 0:Zo.position)!=null?Vt:"bottom-left",Se=be==="bottom-left"||be==="top-left",Be=(oo=(To=r.launcher)==null?void 0:To.zIndex)!=null?oo:bn,nt=g||te?"none":"1px solid var(--persona-border)",Ge=te?"none":g?Se?"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&&!te&&(Ge="none",nt="none");let lt=g||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=F(L==null?void 0:L.border,nt),Me=F(L==null?void 0:L.shadow,Ge),Ee=F(L==null?void 0:L.borderRadius,lt),Ue=Q.scrollTop;e.style.cssText="",le.style.cssText="",ie.style.cssText="",pe.style.cssText="",Q.style.cssText="",$e.style.cssText="";let M=()=>{var Kt;if(Ue<=0)return;((Kt=Q.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(Q.scrollTop===Ue)return;let Rn=Q.scrollHeight-Q.clientHeight;Rn<=0||(Q.scrollTop=Math.min(Ue,Rn))})};if(te){le.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"),le.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:r}var os=class e{constructor(t={},n){this.config=t;this
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",$e.style.flexShrink="0",R=!0,M();return}let Ee=(In=(bt=r==null?void 0:r.launcher)==null?void 0:bt.width)!=null?In:r==null?void 0:r.launcherWidth,Ie=Ee!=null?Ee:Xn;if(!g&&!c)b&&y?(ie.style.width="100%",ie.style.maxWidth="100%"):(ie.style.width=Ie,ie.style.maxWidth=Ie);else if(c)if(ir(r).reveal==="emerge"){let Kt=ir(r).width;ie.style.width=Kt,ie.style.maxWidth=Kt}else ie.style.width="100%",ie.style.maxWidth="100%";if(wr(),ie.style.boxShadow=Me,ie.style.borderRadius=Te,pe.style.border=ct,pe.style.borderRadius=Te,c&&!te&&(L==null?void 0:L.border)===void 0&&(pe.style.border="none",ir(r).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.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%"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",b&&(le.style.overflow="hidden"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",ie.style.overflow="hidden",pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",$e.style.flexShrink="0"),le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!b&&!c&&((Dr=xr[ye])!=null?Dr:xr["bottom-right"]).split(" ").forEach(Kt=>le.classList.add(Kt)),g){let Dt=(Wn=(En=r.launcher)==null?void 0:En.sidebarWidth)!=null?Wn:"420px";le.style.cssText=`
66
+ `,Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",$e.style.flexShrink="0",H=!0,M();return}let Te=(In=(yt=r==null?void 0:r.launcher)==null?void 0:yt.width)!=null?In:r==null?void 0:r.launcherWidth,Ie=Te!=null?Te:Xn;if(!g&&!c)y&&b?(ie.style.width="100%",ie.style.maxWidth="100%"):(ie.style.width=Ie,ie.style.maxWidth=Ie);else if(c)if(ir(r).reveal==="emerge"){let Kt=ir(r).width;ie.style.width=Kt,ie.style.maxWidth=Kt}else ie.style.width="100%",ie.style.maxWidth="100%";if(wr(),ie.style.boxShadow=Me,ie.style.borderRadius=Ee,pe.style.border=ct,pe.style.borderRadius=Ee,c&&!te&&(L==null?void 0:L.border)===void 0&&(pe.style.border="none",ir(r).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",y&&(le.style.overflow="hidden"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",ie.style.overflow="hidden",pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",$e.style.flexShrink="0"),le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!y&&!c&&((Dr=xr[be])!=null?Dr:xr["bottom-right"]).split(" ").forEach(Kt=>le.classList.add(Kt)),g){let Dt=(Wn=(Tn=r.launcher)==null?void 0:Tn.sidebarWidth)!=null?Wn:"420px";le.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
@@ -88,7 +88,7 @@ _Details: ${n.message}_`:r}var os=class e{constructor(t={},n){this.config=t;this
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
90
  box-shadow: ${Me} !important;
91
- border-radius: ${Te} !important;
91
+ border-radius: ${Ee} !important;
92
92
  `,ie.style.setProperty("width","100%","important"),ie.style.setProperty("max-width","100%","important"),pe.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
@@ -98,19 +98,19 @@ _Details: ${n.message}_`:r}var os=class e{constructor(t={},n){this.config=t;this
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${Te} !important;
101
+ border-radius: ${Ee} !important;
102
102
  border: ${ct} !important;
103
103
  `,$e.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!b&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",Kt=g?"":"padding-top: 1.25em !important;",Rn=g?"":`z-index: ${(Ut=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?Ut:yn} !important;`;le.style.cssText+=Dt+Kt+Rn}M()};dr(),so(e,r),Ti(e,r),Mi(e,r);let ht=[];ht.push(()=>{document.removeEventListener("keydown",Kr)});let Gt=null,Xt=null;ht.push(()=>{Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null}),Fn&&ht.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),ht.push(()=>{wn==null||wn(),wn=null,Lr(),Rt&&(Rt.remove(),Rt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),de&&ht.push(()=>{me!==null&&(cancelAnimationFrame(me),me=null),he==null||he.destroy(),he=null,K==null||K.destroy(),K=null,re=null});let qn=null,Xr=()=>{qn&&(qn(),qn=null),r.colorScheme==="auto"&&(qn=ni(()=>{so(e,r)}))};Xr(),ht.push(()=>{qn&&(qn(),qn=null)});let rr=(Dc=r.features)==null?void 0:Dc.streamAnimation;if(rr!=null&&rr.type&&rr.type!=="none"){let c=Zs(rr.type,rr.plugins);c&&(ol(c,e),ht.push(()=>Hu(e)))}let pr=rm(At),zn=null,E,Vn=!1,ur=Eu(),Pr=new Map,Cr=new Map,xs=0,mr=si(),gr=0,fr=null,Ir=!1,yo=!1,ga=4,vs=24,fa=80,qo=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ws=(Oc=(Nc=r.voiceRecognition)==null?void 0:Nc.autoResume)!=null?Oc:!1,or=c=>{o.emit("voice:state",{active:gt.active,source:c,timestamp:Date.now()})},Pn=()=>{m(c=>({...c,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},ha=()=>{var b,L;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Pl(d.voiceState),g=!!c.active,y=Number((L=c.timestamp)!=null?L:0);gt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<Lh&&setTimeout(()=>{var N,F;gt.active||(gt.manuallyDeactivated=!1,((F=(N=r.voiceRecognition)==null?void 0:N.provider)==null?void 0:F.type)==="runtype"?E.toggleVoice().then(()=>{gt.active=E.isVoiceActive(),or("restore"),E.isVoiceActive()&&k()}):wo("restore"))},1e3)},ya=()=>E?Cm(E.getMessages()).filter(c=>!c.__skipPersist):[];function zo(c){if(!(i!=null&&i.save))return;let y={messages:c?Cm(c):E?ya():[],metadata:d,artifacts:_n.artifacts,selectedArtifactId:_n.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Wr=null,ba=()=>le.querySelector("#persona-scroll-container")||Q,bo=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),Ir=!1},Cs=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),yo=!1,bo()},Rr=()=>{if(!bn()||ge){Mt.parentNode&&Mt.remove(),Mt.style.display="none";return}Mt.parentNode!==pe&&pe.appendChild(Mt),xt();let c=Gs(Q)>0;Mt.style.display=mr.isFollowing()||!c?"none":""},As=()=>{mr.pause()&&(Cs(),Rr())},Qr=()=>{mr.resume(),Rr()},Yr=(c=!1)=>{mr.isFollowing()&&(!c&&!Vn||(fr!==null&&(cancelAnimationFrame(fr),fr=null),yo=!0,fr=requestAnimationFrame(()=>{fr=null,yo=!1,mr.isFollowing()&&xa(ba(),c?220:140)})))},xa=(c,g=500)=>{let y=c.scrollTop,b=Gs(c),L=b-y;if(Math.abs(L)<1){gr=c.scrollTop;return}if(Math.abs(L)>=fa){bo(),Ir=!0,c.scrollTop=b,gr=c.scrollTop,Ir=!1;return}bo();let N=performance.now();Ir=!0;let F=H=>1-Math.pow(1-H,3),q=H=>{if(!mr.isFollowing()){bo();return}let Ce=Gs(c);Ce!==b&&(b=Ce,L=b-y);let ce=H-N,te=Math.min(ce/g,1),ye=F(te),Se=y+L*ye;c.scrollTop=Se,gr=c.scrollTop,te<1?Wr=requestAnimationFrame(q):(c.scrollTop=b,gr=c.scrollTop,Wr=null,Ir=!1)};Wr=requestAnimationFrame(q)},va=c=>{let g=new Map;c.forEach(y=>{let b=qo.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),qo.clear(),g.forEach((y,b)=>{qo.set(b,y)})},xo=(c,g,y)=>{var Ge,lt,ct,Me,Te,Ue;let b=document.createElement("div"),N=(()=>{var Ee;let M=s.find(Ie=>Ie.renderLoadingIndicator);if(M!=null&&M.renderLoadingIndicator)return M.renderLoadingIndicator;if((Ee=r.loadingIndicator)!=null&&Ee.render)return r.loadingIndicator.render})(),F=(M,Ee)=>Ee==null?!1:typeof Ee=="string"?(M.textContent=Ee,!0):(M.appendChild(Ee),!0),q=new Set,H=new Set,Ce=s.some(M=>M.renderAskUserQuestion),ce=[],te=[],ye=r.enableComponentStreaming!==!1;if(g.forEach(M=>{var An,un,et,dt,Sn,gn,Co,Ao,So,Yo,Zo,Vt,Eo,oo;q.add(M.id);let Ee=Ce&&$r(M),Ie=!Ee&&M.role==="assistant"&&!M.variant&&ye&&Ii(M);if(!Ie&&Cr.has(M.id)){let bt=c.querySelector(`#wrapper-${M.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),Cr.delete(M.id)}let Ve=$r(M)?`:${(An=M.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(un=M.agentMetadata)!=null&&un.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",ve=Su(M,xs)+Ve,Pt=Ee||Ie?null:Tu(ur,M.id,ve);if(Pt){b.appendChild(Pt.cloneNode(!0)),$r(M)&&((et=M.toolCall)!=null&&et.id)&&((dt=M.agentMetadata)==null?void 0:dt.awaitingLocalTool)===!0&&!((Sn=M.agentMetadata)!=null&&Sn.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,Ae.composerOverlay));return}let at=null,Yt=s.find(bt=>!!(M.variant==="reasoning"&&bt.renderReasoning||M.variant==="tool"&&bt.renderToolCall||M.variant==="approval"&&bt.renderApproval||!M.variant&&bt.renderMessage)),pn=(gn=r.layout)==null?void 0:gn.messages;if($r(M)&&((Co=M.agentMetadata)==null?void 0:Co.askUserQuestionAnswered)===!0){Pr.delete(M.id);let bt=c.querySelector(`#wrapper-${M.id}`);bt==null||bt.removeAttribute("data-preserve-runtime");return}if($r(M)&&((So=(Ao=r.features)==null?void 0:Ao.askUserQuestion)==null?void 0:So.enabled)!==!1){let bt=s.find(In=>typeof In.renderAskUserQuestion=="function");if(bt&&It.current){let In=Pr.get(M.id),Dr=In!==ve,En=null;if(Dr){let{payload:Ut,complete:Dt}=jr(M),Kt=M.id,Rn=()=>{var Jn;return(Jn=It.current)==null?void 0:Jn.getMessages().find(rn=>rn.id===Kt)};En=bt.renderAskUserQuestion({message:M,payload:Ut,complete:Dt,resolve:Jn=>{var Sr;let rn=Rn();rn&&((Sr=It.current)==null||Sr.resolveAskUserQuestion(rn,Jn))},dismiss:()=>{var rn,Sr,Nr;let Jn=Rn();(rn=Jn==null?void 0:Jn.agentMetadata)!=null&&rn.awaitingLocalTool&&((Sr=It.current)==null||Sr.markAskUserQuestionResolved(Jn),(Nr=It.current)==null||Nr.resolveAskUserQuestion(Jn,"(dismissed)"))},config:r})}let Wn=In!=null;if(Dr&&En===null&&!Wn){((Yo=M.agentMetadata)==null?void 0:Yo.awaitingLocalTool)===!0&&!((Zo=M.agentMetadata)!=null&&Zo.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,Ae.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),b.appendChild(Bt),ce.push({messageId:M.id,fingerprint:ve,bubble:En});return}else{((Vt=M.agentMetadata)==null?void 0:Vt.awaitingLocalTool)===!0&&!((Eo=M.agentMetadata)!=null&&Eo.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,Ae.composerOverlay));return}}else if(Yt)if(M.variant==="reasoning"&&M.reasoning&&Yt.renderReasoning){if(!He)return;at=Yt.renderReasoning({message:M,defaultRenderer:()=>gl(M,r),config:r})}else if(M.variant==="tool"&&M.toolCall&&Yt.renderToolCall){if(!Oe)return;at=Yt.renderToolCall({message:M,defaultRenderer:()=>fl(M,r),config:r})}else if(M.variant==="approval"&&M.approval&&Yt.renderApproval){if(r.approval===!1)return;at=Yt.renderApproval({message:M,defaultRenderer:()=>Al(M,r),config:r})}else Yt.renderMessage&&(at=Yt.renderMessage({message:M,defaultRenderer:()=>{let bt=ds(M,y,pn,r.messageActions,V,{loadingIndicatorRenderer:N,widgetConfig:r});return M.role!=="user"&&Ml(bt,M,r,E),bt},config:r}));if(!at&&Ie){let bt=Wi(M);if(bt){let In=Cr.get(M.id),Dr=In!==ve,En=r.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Dr){let Bt=Pi(bt,{config:r,message:M,transform:y});if(Bt)if(En){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-${M.id}`,Ut.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=y({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Bt),Wn=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-${M.id}`,Ut.setAttribute("data-message-id",M.id),Ut.setAttribute("data-persona-component-directive","true"),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=y({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Bt),Wn=Ut}}if(Wn||In!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),En||Bt.classList.add("persona-w-full"),b.appendChild(Bt),te.push({messageId:M.id,fingerprint:ve,bubble:Wn});return}}}if(!at)if(M.variant==="reasoning"&&M.reasoning){if(!He)return;at=gl(M,r)}else if(M.variant==="tool"&&M.toolCall){if(!Oe)return;at=fl(M,r)}else if(M.variant==="approval"&&M.approval){if(r.approval===!1)return;at=Al(M,r)}else{let bt=(oo=r.layout)==null?void 0:oo.messages;bt!=null&&bt.renderUserMessage&&M.role==="user"?at=bt.renderUserMessage({message:M,config:r,streaming:!!M.streaming}):bt!=null&&bt.renderAssistantMessage&&M.role==="assistant"?at=bt.renderAssistantMessage({message:M,config:r,streaming:!!M.streaming}):at=ds(M,y,bt,r.messageActions,V,{loadingIndicatorRenderer:N,widgetConfig:r}),M.role!=="user"&&at&&Ml(at,M,r,E)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${M.id}`,Wt.setAttribute("data-wrapper-id",M.id),M.role==="user"&&Wt.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(at),Mu(ur,M.id,ve,Wt),b.appendChild(Wt)}),Ae.composerOverlay&&Ae.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let Ie=Ee.getAttribute("data-persona-ask-sheet-for");Ie&&!H.has(Ie)&&mo(Ae.composerOverlay,Ie)}),(lt=(Ge=r.features)==null?void 0:Ge.toolCallDisplay)!=null&&lt.grouped){let M=[],Ee=[];g.forEach(Ie=>{if(Ie.variant==="tool"&&Ie.toolCall&&Oe){Ee.push(Ie);return}Ee.length>1&&M.push(Ee),Ee=[]}),Ee.length>1&&M.push(Ee),M.forEach((Ie,Ve)=>{var un,et;let ve=Ie.map(dt=>Array.from(b.children).find(Sn=>Sn instanceof HTMLElement&&Sn.getAttribute("data-wrapper-id")===dt.id)).filter(dt=>!!dt);if(ve.length<2)return;let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-tool-group-${Ve}-${Ie[0].id}`,Pt.setAttribute("data-wrapper-id",`tool-group-${Ve}-${Ie[0].id}`);let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Yt=document.createElement("div");Yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let pn=`Called ${Ie.length} tools`,Wt=(et=(un=r.toolCall)==null?void 0:un.renderGroupedSummary)==null?void 0:et.call(un,{messages:Ie,toolCalls:Ie.map(dt=>dt.toolCall).filter(dt=>!!dt),defaultSummary:pn,config:r});F(Yt,Wt)||(Yt.textContent=pn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Yt,An),Pt.appendChild(at),ve[0].before(Pt),ve.forEach((dt,Sn)=>{let gn=document.createElement("div");gn.className="persona-tool-group-item persona-relative",gn.setAttribute("data-persona-tool-group-item","true"),Sn<ve.length-1&&gn.setAttribute("data-persona-tool-group-connector","true"),gn.appendChild(dt),An.appendChild(gn)})})}ku(ur,q);let Se=g.some(M=>M.role==="assistant"&&M.streaming),Be=g[g.length-1],nt=(Be==null?void 0:Be.role)==="assistant"&&!Be.streaming&&Be.variant!=="approval";if(Vn&&g.some(M=>M.role==="user")&&!Se&&!nt){let M={config:r,streaming:!0,location:"standalone",defaultRenderer:Oo},Ee=s.find(Ve=>Ve.renderLoadingIndicator),Ie=null;if(Ee!=null&&Ee.renderLoadingIndicator&&(Ie=Ee.renderLoadingIndicator(M)),Ie===null&&((ct=r.loadingIndicator)!=null&&ct.render)&&(Ie=r.loadingIndicator.render(M)),Ie===null&&(Ie=Oo()),Ie){let Ve=document.createElement("div"),ve=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;Ve.className=ve?["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(Ie);let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id="wrapper-typing-indicator",Pt.setAttribute("data-wrapper-id","typing-indicator"),Pt.appendChild(Ve),b.appendChild(Pt)}}if(!Vn&&g.length>0){let M=g[g.length-1],Ee={config:r,lastMessage:M,messageCount:g.length},Ie=s.find(ve=>ve.renderIdleIndicator),Ve=null;if(Ie!=null&&Ie.renderIdleIndicator&&(Ve=Ie.renderIdleIndicator(Ee)),Ve===null&&((Te=r.loadingIndicator)!=null&&Te.renderIdle)&&(Ve=r.loadingIndicator.renderIdle(Ee)),Ve){let ve=document.createElement("div"),Pt=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ve.className=Pt?["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(" "),ve.setAttribute("data-idle-indicator","true"),ve.appendChild(Ve);let at=document.createElement("div");at.className="persona-flex",at.id="wrapper-idle-indicator",at.setAttribute("data-wrapper-id","idle-indicator"),at.appendChild(ve),b.appendChild(at)}}if(ri(c,b),ce.length>0)for(let{messageId:M,fingerprint:Ee,bubble:Ie}of ce){let Ve=c.querySelector(`#wrapper-${M}`);Ve&&Ie!==null&&(Ve.replaceChildren(Ie),Ve.setAttribute("data-bubble-fp",Ee),Pr.set(M,Ee))}if(Pr.size>0)for(let M of Pr.keys())q.has(M)||Pr.delete(M);if(te.length>0)for(let{messageId:M,fingerprint:Ee,bubble:Ie}of te){let Ve=c.querySelector(`#wrapper-${M}`);Ve&&Ie!==null&&(Ve.replaceChildren(Ie),Ve.setAttribute("data-bubble-fp",Ee),Cr.set(M,Ee))}if(Cr.size>0)for(let M of Cr.keys())q.has(M)||Cr.delete(M)},Zr=null,wa=()=>{var y;if(Zr)return;let c=b=>{let L=b.composedPath();L.includes(le)||Ye&&L.includes(Ye)||Ht(!1,"user")};Zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},Ss=()=>{var g;if(!Zr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Zr,!0),Zr=null};ht.push(()=>Ss());let eo=null,Ca=()=>{var y;if(eo)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Ht(!1,"user"))};eo=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},Es=()=>{var g;if(!eo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",eo,!0),eo=null};ht.push(()=>Es());let to=!1,Ts=new Set,Aa=()=>{var g,y,b,L;let c=(b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((L=r.features)==null?void 0:L.streamAnimation)},Hr=()=>{var lt,ct,Me,Te;if(!_())return;let c=Ae.peekBanner,g=Ae.peekTextNode;if(!c||!g)return;if(D){c.classList.remove("persona-pill-peek--visible");return}let y=(lt=E==null?void 0:E.getMessages())!=null?lt:[],b;for(let Ue=y.length-1;Ue>=0;Ue--){let M=y[Ue];if(M.role==="assistant"&&M.content){b=M;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let L=b.content,N=!!b.streaming,F=Aa(),q=li(F),H=q.type!=="none"?Zs(q.type,F==null?void 0:F.plugins):null,Ce=((ct=H==null?void 0:H.isAnimating)==null?void 0:ct.call(H,b))===!0,ce=H!==null&&(N||Ce);ce&&H&&!Ts.has(H.name)&&(ol(H,e),Ts.add(H.name));let te=ce&&(H!=null&&H.containerClass)?H.containerClass:null,ye=(Me=g.dataset.personaPeekStreamClass)!=null?Me:null;ye&&ye!==te&&(g.classList.remove(ye),delete g.dataset.personaPeekStreamClass),te&&ye!==te&&(g.classList.add(te),g.dataset.personaPeekStreamClass=te),ce?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Se=ce?ci(L,q.buffer,H,b,N):L;if(ce&&q.placeholder==="skeleton"&&N&&(!Se||!Se.trim())){let Ue=document.createElement("div"),M=ta();M.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(M),ri(g,Ue)}else{let Ue=Math.max(0,Se.length-100),M=Se.length>100?Se.slice(-100):Se,Ee=Po(M);if(!ce||!H){let Ie=Se.length>100?`\u2026${M}`:M;g.textContent!==Ie&&(g.textContent=Ie)}else{let Ie=Ee;(H.wrap==="char"||H.wrap==="word")&&(Ie=ea(Ee,H.wrap,`peek-${b.id}`,{skipTags:H.skipTags,startIndex:Ue}));let Ve=document.createElement("div");if(Ve.innerHTML=Ie,H.useCaret&&M.length>0){let ve=di(),Pt=Ve.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=Pt[Pt.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(ve,at.nextSibling):Ve.appendChild(ve)}ri(g,Ve),(Te=H.onAfterRender)==null||Te.call(H,{container:g,bubble:c,messageId:b.id,message:b,speed:q.speed,duration:q.duration})}}let Ge=Vn||to;c.classList.toggle("persona-pill-peek--visible",Ge)};if(_()){let c=Ae.peekBanner;if(c){let b=L=>{L.preventDefault(),L.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",b),ht.push(()=>{c.removeEventListener("pointerdown",b)})}let g=()=>{to||(to=!0,Hr())},y=()=>{to&&(to=!1,Hr())};ie.addEventListener("pointerenter",g),ie.addEventListener("pointerleave",y),ht.push(()=>{ie.removeEventListener("pointerenter",g),ie.removeEventListener("pointerleave",y)}),Ye&&(Ye.addEventListener("pointerenter",g),Ye.addEventListener("pointerleave",y),ht.push(()=>{Ye.removeEventListener("pointerenter",g),Ye.removeEventListener("pointerleave",y)}))}let Sa=c=>{var ye,Se,Be,nt,Ge,lt,ct,Me;let g=(Se=(ye=r.launcher)==null?void 0:ye.composerBar)!=null?Se:{},y=(Be=g.expandedSize)!=null?Be:"anchored",b=(nt=g.bottomOffset)!=null?nt:"16px",L=g.collapsedMaxWidth,N=(Ge=g.expandedMaxWidth)!=null?Ge:"880px",F=(lt=g.expandedTopOffset)!=null?lt:"5vh",q=(ct=g.modalMaxWidth)!=null?ct:"880px",H=(Me=g.modalMaxHeight)!=null?Me:"min(90vh, 800px)",Ce="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",te=le.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Ye){let Te=Ye.style;Te.bottom=b,Te.width=L!=null?L:""}if(c&&y!=="fullscreen"){if(y==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=q,te.maxWidth=Ce,te.maxHeight=H,te.height=H;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${b} + ${ce})`,te.top=F,te.width=N,te.maxWidth=Ce}},no=()=>{var H,Ce,ce,te,ye,Se,Be,nt;if(!$())return;if(_()){let lt=(ce=((Ce=(H=r.launcher)==null?void 0:H.composerBar)!=null?Ce:{}).expandedSize)!=null?ce:"anchored",ct=D?"expanded":"collapsed";le.dataset.state=ct,le.dataset.expandedSize=lt,Ye&&(Ye.dataset.state=ct,Ye.dataset.expandedSize=lt),le.style.removeProperty("display"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Sa(D),pe.style.display=D?"flex":"none",dr(),D?(wa(),Ca()):(Ss(),Es()),Hr();return}let c=on(r),g=(te=e.ownerDocument.defaultView)!=null?te:window,y=(Se=(ye=r.launcher)==null?void 0:ye.mobileBreakpoint)!=null?Se:640,b=(nt=(Be=r.launcher)==null?void 0:Be.mobileFullscreen)!=null?nt:!0,L=g.innerWidth<=y,N=b&&L&&S,F=ir(r).reveal;D?(le.style.removeProperty("display"),le.style.display=c?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-95","persona-opacity-0"),ie.classList.add("persona-scale-100","persona-opacity-100"),Je?Je.element.style.display="none":Ze&&(Ze.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!N?(le.style.removeProperty("display"),le.style.display="flex",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.setProperty("display","none","important"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.display="",le.classList.add("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100"),ie.classList.add("persona-scale-95","persona-opacity-0")),Je?Je.element.style.display=c?"none":"":Ze&&(Ze.style.display=c?"none":""))},Ht=(c,g="user")=>{var N,F;if(!$()||D===c)return;let y=D;D=c,no();let b=(()=>{var Be,nt,Ge,lt,ct,Me,Te,Ue,M,Ee;let q=(nt=(Be=r.launcher)==null?void 0:Be.sidebarMode)!=null?nt:!1,H=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,Ce=(ct=(lt=r.launcher)==null?void 0:lt.mobileFullscreen)!=null?ct:!0,ce=(Te=(Me=r.launcher)==null?void 0:Me.mobileBreakpoint)!=null?Te:640,te=H.innerWidth<=ce,ye=on(r)&&Ce&&te,Se=_()&&((Ee=(M=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:M.expandedSize)!=null?Ee:"fullscreen")==="fullscreen";return q||Ce&&te&&S||ye||Se})();if(D&&b){if(!Gt){let q=e.getRootNode(),H=q instanceof ShadowRoot?q.host:e.closest(".persona-host");H&&(Gt=sl(H,(F=(N=r.launcher)==null?void 0:N.zIndex)!=null?F:yn))}Xt||(Xt=al(e.ownerDocument))}else D||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null);D&&(Qt(),Yr(!0));let L={open:D,source:g,timestamp:Date.now()};D&&!y?o.emit("widget:opened",L):!D&&y&&o.emit("widget:closed",L),o.emit("widget:state",{open:D,launcherEnabled:S,voiceActive:gt.active,streaming:E.isStreaming()})},Vo=c=>{Jt(c?"stop":"send"),J&&(J.disabled=c),pr.buttons.forEach(g=>{g.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Ko=()=>{gt.active||X&&X.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Ko(),200)});let Ms=()=>{var y,b,L,N,F,q,H,Ce,ce,te,ye;Bn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Yn.textContent=(N=(L=r.copy)==null?void 0:L.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",X.placeholder=(q=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?q:"How can I help...";let c=Q.querySelector("[data-persona-intro-card]");if(c){let Se=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=Se?"":"none",Se?(Q.classList.remove("persona-gap-3"),Q.classList.add("persona-gap-6")):(Q.classList.remove("persona-gap-6"),Q.classList.add("persona-gap-3"))}!((ce=(Ce=r.sendButton)==null?void 0:Ce.useIcon)!=null&&ce)&&!(E!=null&&E.isStreaming())&&(Fe.textContent=(ye=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?ye:"Send"),X.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',X.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Ar=null,Ea=()=>{Ar==null&&(Ar=setInterval(()=>{let c=je.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ar),Ar=null;return}let g=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Na(g-b))})},100))};if(E=new os(r,{onMessagesChanged(c){xo(je,c,We),Ea(),E&&(c.some(L=>L.role==="user")?pr.render([],E,X,c):pr.render(r.suggestionChips,E,X,c,r.suggestionChipsConfig)),Yr(!Vn),va(c);let g=[...c].reverse().find(b=>b.role==="user"),y=gt.lastUserMessageId;g&&g.id!==y&&(gt.lastUserMessageId=g.id,o.emit("user:message",g)),gt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),zo(c),Hr()},onStatusChanged(c){var b;let g=(b=r.statusIndicator)!=null?b:{};fe(cn,(L=>{var N,F,q,H;return L==="idle"?(N=g.idleText)!=null?N:hn.idle:L==="connecting"?(F=g.connectingText)!=null?F:hn.connecting:L==="connected"?(q=g.connectedText)!=null?q:hn.connected:L==="error"?(H=g.errorText)!=null?H:hn.error:hn[L]})(c),g,c)},onStreamingChanged(c){Vn=c,Vo(c),E&&xo(je,E.getMessages(),We),c||Yr(!0),Hr()},onVoiceStatusChanged(c){var g,y;if(((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":G(),Z();break;case"speaking":G(),ee();break;default:c==="idle"&&E.isBargeInActive()?(G(),k(),J==null||J.setAttribute("aria-label","End voice session")):(gt.active=!1,G(),or("system"),Pn());break}},onArtifactsState(c){_n=c,Un(),zo()}}),It.current=E,((_c=(Fc=r.voiceRecognition)==null?void 0:Fc.provider)==null?void 0:_c.type)==="runtype")try{E.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&E.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||r.onSSEEvent)&&E.setSSEEventCallback((c,g)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,g),ue==null||ue.processEvent(c,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,y,b;c&&(c.metadata&&(d=Pl(c.metadata),T.syncFromMetadata()),(g=c.messages)!=null&&g.length&&E.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&E.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ks=()=>{var g,y,b;!_()||D||!((b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Ht(!0,"auto")},Ls=c=>{var L;if(c.preventDefault(),E.isStreaming()){E.cancel(),ue==null||ue.reset(),he==null||he.update();return}let g=X.value.trim(),y=(L=tt==null?void 0:tt.hasAttachments())!=null?L:!1;if(!g&&!y)return;ks();let b;y&&(b=[],b.push(...tt.getContentParts()),g&&b.push(qs(g))),X.value="",X.style.height="auto",vo(),E.sendMessage(g,{contentParts:b}),y&&tt.clearAttachments()},Ta=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Jo={...oi},Go=!1,vo=()=>{Jo={...oi}},Ma=()=>E.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ka=c=>{if(!X)return;Go=!0,X.value=c,X.dispatchEvent(new Event("input",{bubbles:!0})),Go=!1;let g=X.value.length;X.setSelectionRange(g,g)},Ps=()=>{Go||vo()},Is=c=>{if(X){if(Ta()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=X.selectionStart===0&&X.selectionEnd===0,y=Au({direction:c.key==="ArrowUp"?"up":"down",history:Ma(),currentValue:X.value,atStart:g,state:Jo});if(Jo=y.state,y.handled){c.preventDefault(),y.value!==void 0&&ka(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(E.isStreaming()){c.preventDefault();return}vo(),c.preventDefault(),Fe.click()}}},Ws=c=>{c.key!=="Escape"||c.isComposing||E.isStreaming()&&c.composedPath().includes(pe)&&(E.cancel(),ue==null||ue.reset(),he==null||he.update(),vo(),c.preventDefault(),c.stopImmediatePropagation())},Rs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!tt)return;let g=Ih(c.clipboardData);g.length!==0&&(c.preventDefault(),await tt.handleFiles(g))},Cn=null,Kn=!1,Br=null,st=null,Hs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,wo=(c="user")=>{var N,F,q,H,Ce,ce,te;if(Kn||E.isStreaming())return;let g=Hs();if(!g)return;Cn=new g;let b=(F=((N=r.voiceRecognition)!=null?N:{}).pauseDuration)!=null?F:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let L=X.value;Cn.onresult=ye=>{let Se="",Be="";for(let Ge=0;Ge<ye.results.length;Ge++){let lt=ye.results[Ge],ct=lt[0].transcript;lt.isFinal?Se+=ct+" ":Be=ct}let nt=L+Se+Be;X.value=nt,Br&&clearTimeout(Br),(Se||Be)&&(Br=window.setTimeout(()=>{let Ge=X.value.trim();Ge&&Cn&&Kn&&(hr(),X.value="",X.style.height="auto",E.sendMessage(Ge,{viaVoice:!0}))},b))},Cn.onerror=ye=>{ye.error!=="no-speech"&&hr()},Cn.onend=()=>{if(Kn){let ye=X.value.trim();ye&&ye!==L.trim()&&(X.value="",X.style.height="auto",E.sendMessage(ye,{viaVoice:!0})),hr()}};try{if(Cn.start(),Kn=!0,gt.active=!0,c!=="system"&&(gt.manuallyDeactivated=!1),or(c),Pn(),J){let ye=(q=r.voiceRecognition)!=null?q:{};st={backgroundColor:J.style.backgroundColor,color:J.style.color,borderColor:J.style.borderColor,iconName:(H=ye.iconName)!=null?H:"mic",iconSize:parseFloat((te=(ce=ye.iconSize)!=null?ce:(Ce=r.sendButton)==null?void 0:Ce.size)!=null?te:"40")||24};let Se=ye.recordingBackgroundColor,Be=ye.recordingIconColor,nt=ye.recordingBorderColor;if(J.classList.add("persona-voice-recording"),J.style.backgroundColor=Se!=null?Se:"var(--persona-voice-recording-bg, #ef4444)",J.style.color=Be!=null?Be:"var(--persona-voice-recording-indicator, #ffffff)",Be){let Ge=J.querySelector("svg");Ge&&Ge.setAttribute("stroke",Be)}nt&&(J.style.borderColor=nt),J.setAttribute("aria-label","Stop voice recognition")}}catch{hr("system")}},hr=(c="user")=>{if(Kn){if(Kn=!1,Br&&(clearTimeout(Br),Br=null),Cn){try{Cn.stop()}catch{}Cn=null}if(gt.active=!1,or(c),Pn(),J){if(J.classList.remove("persona-voice-recording"),st){J.style.backgroundColor=st.backgroundColor,J.style.color=st.color,J.style.borderColor=st.borderColor;let g=J.querySelector("svg");g&&g.setAttribute("stroke",st.color||"currentColor"),st=null}J.setAttribute("aria-label","Start voice recognition")}}},Xo=(c,g)=>{var lt,ct,Me,Te,Ue,M,Ee,Ie;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((lt=c==null?void 0:c.provider)==null?void 0:lt.type)==="runtype";if(!(y||b))return null;let N=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 q=(ct=c==null?void 0:c.iconName)!=null?ct:"mic",H=(Me=g==null?void 0:g.size)!=null?Me:"40px",Ce=(Te=c==null?void 0:c.iconSize)!=null?Te:H,ce=parseFloat(Ce)||24,te=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:g==null?void 0:g.backgroundColor,ye=(M=c==null?void 0:c.iconColor)!=null?M:g==null?void 0:g.textColor;F.style.width=Ce,F.style.height=Ce,F.style.minWidth=Ce,F.style.minHeight=Ce,F.style.fontSize="18px",F.style.lineHeight="1",ye?F.style.color=ye:F.style.color="var(--persona-text, #111827)";let Be=be(q,ce,ye||"currentColor",1.5);Be?F.appendChild(Be):F.textContent="\u{1F3A4}",te?F.style.backgroundColor=te: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),N.appendChild(F);let nt=(Ee=c==null?void 0:c.tooltipText)!=null?Ee:"Start voice recognition";if(((Ie=c==null?void 0:c.showTooltip)!=null?Ie:!1)&&nt){let Ve=h("div","persona-send-button-tooltip");Ve.textContent=nt,N.appendChild(Ve)}return{micButton:F,micButtonWrapper:N}},qe=()=>{var g,y,b,L,N;if(!J||st)return;let c=(g=r.voiceRecognition)!=null?g:{};st={backgroundColor:J.style.backgroundColor,color:J.style.color,borderColor:J.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((N=(L=c.iconSize)!=null?L:(b=r.sendButton)==null?void 0:b.size)!=null?N:"40")||24}},A=(c,g)=>{var N,F,q,H,Ce;if(!J)return;let y=J.querySelector("svg");y&&y.remove();let b=(Ce=st==null?void 0:st.iconSize)!=null?Ce:parseFloat((H=(q=(N=r.voiceRecognition)==null?void 0:N.iconSize)!=null?q:(F=r.sendButton)==null?void 0:F.size)!=null?H:"40")||24,L=be(c,b,g,1.5);L&&J.appendChild(L)},j=()=>{J&&J.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},k=()=>{var L;if(!J)return;qe();let c=(L=r.voiceRecognition)!=null?L:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(j(),J.classList.add("persona-voice-recording"),J.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",J.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let N=J.querySelector("svg");N&&N.setAttribute("stroke",y)}b&&(J.style.borderColor=b),J.setAttribute("aria-label","Stop voice recognition")},Z=()=>{var q,H,Ce,ce,te,ye,Se,Be;if(!J)return;qe();let c=(q=r.voiceRecognition)!=null?q:{},g=E.getVoiceInterruptionMode(),y=(H=c.processingIconName)!=null?H:"loader",b=(ce=(Ce=c.processingIconColor)!=null?Ce:st==null?void 0:st.color)!=null?ce:"",L=(ye=(te=c.processingBackgroundColor)!=null?te:st==null?void 0:st.backgroundColor)!=null?ye:"",N=(Be=(Se=c.processingBorderColor)!=null?Se:st==null?void 0:st.borderColor)!=null?Be:"";j(),J.classList.add("persona-voice-processing"),J.style.backgroundColor=L,J.style.borderColor=N;let F=b||"currentColor";J.style.color=F,A(y,F),J.setAttribute("aria-label","Processing voice input"),g==="none"&&(J.style.cursor="default")},ee=()=>{var Ce,ce,te,ye,Se,Be,nt,Ge,lt,ct,Me,Te;if(!J)return;qe();let c=(Ce=r.voiceRecognition)!=null?Ce:{},g=E.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=(ce=c.speakingIconName)!=null?ce:y,L=(Be=c.speakingIconColor)!=null?Be:g==="barge-in"?(ye=(te=c.recordingIconColor)!=null?te:st==null?void 0:st.color)!=null?ye:"":(Se=st==null?void 0:st.color)!=null?Se:"",N=(lt=c.speakingBackgroundColor)!=null?lt:g==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(Ge=st==null?void 0:st.backgroundColor)!=null?Ge:"",F=(Te=c.speakingBorderColor)!=null?Te:g==="barge-in"?(ct=c.recordingBorderColor)!=null?ct:"":(Me=st==null?void 0:st.borderColor)!=null?Me:"";j(),J.classList.add("persona-voice-speaking"),J.style.backgroundColor=N,J.style.borderColor=F;let q=L||"currentColor";J.style.color=q,A(b,q);let H=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";J.setAttribute("aria-label",H),g==="none"&&(J.style.cursor="default"),g==="barge-in"&&J.classList.add("persona-voice-recording")},G=()=>{var c,g,y;J&&(j(),st&&(J.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",J.style.color=(g=st.color)!=null?g:"",J.style.borderColor=(y=st.borderColor)!=null?y:"",A(st.iconName,st.color||"currentColor"),st=null),J.style.cursor="",J.setAttribute("aria-label","Start voice recognition"))},ze=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let y=E.getVoiceStatus(),b=E.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){E.stopVoicePlayback();return}if(E.isBargeInActive()){E.stopVoicePlayback(),E.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),G()});return}E.toggleVoice().then(()=>{gt.active=E.isVoiceActive(),gt.manuallyDeactivated=!E.isVoiceActive(),Pn(),or("user"),E.isVoiceActive()?k():G()});return}if(Kn){let y=X.value.trim();gt.manuallyDeactivated=!0,Pn(),hr("user"),y&&(X.value="",X.style.height="auto",E.sendMessage(y))}else gt.manuallyDeactivated=!1,Pn(),wo("user")};Dn=ze,J&&(J.addEventListener("click",ze),ht.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(E.isVoiceActive()&&E.toggleVoice(),G()):hr("system"),J&&J.removeEventListener("click",ze)}));let Ne=o.on("assistant:complete",()=>{ws&&(gt.active||gt.manuallyDeactivated||ws==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!gt.active&&!gt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?E.toggleVoice().then(()=>{gt.active=E.isVoiceActive(),or("auto"),E.isVoiceActive()&&k()}):wo("auto"))},600))});ht.push(Ne);let it=o.on("action:resubmit",()=>{setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)});ht.push(it);let Ke=()=>{Ht(!D,"user")},Je=null,Ze=null;if(S&&!_()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>ra(r,Ke).element,onToggle:Ke});g&&(Ze=g)}Ze||(Je=ra(r,Ke))}Je?e.appendChild(Je.element):Ze&&e.appendChild(Ze),no(),pr.render(r.suggestionChips,E,X,void 0,r.suggestionChipsConfig),Ms(),Vo(E.isStreaming()),Yr(!0),ha(),I&&(!S||_()?setTimeout(()=>Ko(),0):D&&setTimeout(()=>Ko(),200));let Qt=()=>{var H,Ce,ce,te,ye,Se,Be,nt,Ge,lt,ct,Me,Te,Ue,M,Ee,Ie,Ve,ve,Pt,at,Yt;if(_()){xt(),no();return}let c=on(r),g=(Ce=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?Ce:!1,y=c||g||((te=(ce=r.launcher)==null?void 0:ce.fullHeight)!=null?te:!1),b=(ye=e.ownerDocument.defaultView)!=null?ye:window,L=(Be=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Be:!0,N=(Ge=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?Ge:640,F=b.innerWidth<=N,q=L&&F&&S;try{if(q){dr(),so(e,r);return}if(R&&(R=!1,dr(),so(e,r)),!S&&!c){ie.style.height="",ie.style.width="";return}if(!g&&!c){let pn=(ct=(lt=r==null?void 0:r.launcher)==null?void 0:lt.width)!=null?ct:r==null?void 0:r.launcherWidth,Wt=pn!=null?pn:Xn;ie.style.width=Wt,ie.style.maxWidth=Wt}if(wr(),!y){let pn=b.innerHeight,Wt=64,An=(Te=(Me=r.launcher)==null?void 0:Me.heightOffset)!=null?Te:0,un=Math.max(200,pn-Wt),et=Math.min(640,un),dt=Math.max(200,et-An);ie.style.height=`${dt}px`}}finally{if(xt(),no(),D&&S){let Wt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((Ee=(M=r.launcher)==null?void 0:M.mobileBreakpoint)!=null?Ee:640),An=(Ve=(Ie=r.launcher)==null?void 0:Ie.sidebarMode)!=null?Ve:!1,un=(Pt=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Pt:!0,et=on(r)&&un&&Wt,dt=An||un&&Wt&&S||et;if(dt&&!Xt){let Sn=e.getRootNode(),gn=Sn instanceof ShadowRoot?Sn.host:e.closest(".persona-host");gn&&!Gt&&(Gt=sl(gn,(Yt=(at=r.launcher)==null?void 0:at.zIndex)!=null?Yt:yn)),Xt=al(e.ownerDocument)}else dt||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null)}}};Qt();let Tt=($c=e.ownerDocument.defaultView)!=null?$c:window;if(Tt.addEventListener("resize",Qt),ht.push(()=>Tt.removeEventListener("resize",Qt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{xt()});c.observe($e),ht.push(()=>c.disconnect())}gr=Q.scrollTop;let Lt=Q.scrollHeight,sn=()=>{let c=Q.scrollTop,g=Q.scrollHeight,y=g<Lt;Lt=g;let{action:b,nextLastScrollTop:L}=ai({following:mr.isFollowing(),currentScrollTop:c,lastScrollTop:gr,nearBottom:Xs(Q,vs),userScrollThreshold:ga,isAutoScrolling:Ir||yo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gr=L,b==="resume"){Qr();return}b==="pause"&&As()};Q.addEventListener("scroll",sn,{passive:!0}),ht.push(()=>Q.removeEventListener("scroll",sn));let mn=c=>{let g=ii({following:mr.isFollowing(),deltaY:c.deltaY,nearBottom:Xs(Q,vs),resumeWhenNearBottom:!0});g==="pause"?As():g==="resume"&&Qr()};Q.addEventListener("wheel",mn,{passive:!0}),ht.push(()=>Q.removeEventListener("wheel",mn)),Mt.addEventListener("click",()=>{Q.scrollTop=Q.scrollHeight,gr=Q.scrollTop,Qr(),Yr(!0)}),ht.push(()=>Mt.remove()),ht.push(()=>{Cs()});let dn=()=>{B&&(zn&&(B.removeEventListener("click",zn),zn=null),$()?(B.style.display="",zn=()=>{Ht(!1,"user")},B.addEventListener("click",zn)):B.style.display="none")};dn(),(()=>{let{clearChatButton:c}=Ae;c&&c.addEventListener("click",()=>{E.clearMessages(),ur.clear(),Qr(),mo(Ae.composerOverlay);try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},T.syncFromMetadata(),K==null||K.clear(),ue==null||ue.reset(),he==null||he.update()})})(),Ot&&Ot.addEventListener("submit",Ls),X==null||X.addEventListener("keydown",Is),X==null||X.addEventListener("input",Ps),X==null||X.addEventListener("paste",Rs);let sr=(jc=e.ownerDocument)!=null?jc:document;sr.addEventListener("keydown",Ws,!0);let Jl="persona-attachment-drop-active",Bs=0,zi=()=>{Bs=0,pe.classList.remove(Jl)},Qo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Gl=c=>{!Bi(c.dataTransfer)||!Qo()||(Bs++,Bs===1&&pe.classList.add(Jl))},Xl=c=>{!Bi(c.dataTransfer)||!Qo()||(Bs--,Bs<=0&&zi())},Ql=c=>{!Bi(c.dataTransfer)||!Qo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Yl=c=>{var y;if(!Bi(c.dataTransfer)||!Qo())return;c.preventDefault(),c.stopPropagation(),zi();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&tt.handleFiles(g)},ro=!0;pe.addEventListener("dragenter",Gl,ro),pe.addEventListener("dragleave",Xl,ro),e.addEventListener("dragover",Ql,ro),e.addEventListener("drop",Yl,ro);let La=e.ownerDocument,Zl=c=>{Qo()&&c.preventDefault()},ec=c=>{Qo()&&c.preventDefault()};La.addEventListener("dragover",Zl),La.addEventListener("drop",ec),ht.push(()=>{Ot&&Ot.removeEventListener("submit",Ls),X==null||X.removeEventListener("keydown",Is),X==null||X.removeEventListener("input",Ps),X==null||X.removeEventListener("paste",Rs),sr.removeEventListener("keydown",Ws,!0)}),ht.push(()=>{pe.removeEventListener("dragenter",Gl,ro),pe.removeEventListener("dragleave",Xl,ro),e.removeEventListener("dragover",Ql,ro),e.removeEventListener("drop",Yl,ro),La.removeEventListener("dragover",Zl),La.removeEventListener("drop",ec),zi()}),ht.push(()=>{E.cancel()}),Je?ht.push(()=>{Je==null||Je.destroy()}):Ze&&ht.push(()=>{Ze==null||Ze.remove()});let nn={update(c){var rn,Sr,Nr,Pa,Ia,Wa,To,Ra,Ds,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Ep,Tp,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp;let g=r.toolCall,y=r.messageActions,b=(rn=r.layout)==null?void 0:rn.messages,L=r.colorScheme,N=r.loadingIndicator,F=r.iterationDisplay,q=(Sr=r.features)==null?void 0:Sr.showReasoning,H=(Nr=r.features)==null?void 0:Nr.showToolCalls,Ce=(Pa=r.features)==null?void 0:Pa.toolCallDisplay,ce=(Ia=r.features)==null?void 0:Ia.reasoningDisplay;r={...r,...c},dr(),so(e,r),Ti(e,r),Mi(e,r),Un(),r.colorScheme!==L&&Xr();let te=da.getForInstance(r.plugins);s.length=0,s.push(...te),S=(To=(Wa=r.launcher)==null?void 0:Wa.enabled)!=null?To:!0,W=(Ds=(Ra=r.launcher)==null?void 0:Ra.autoExpand)!=null?Ds:!1,He=(Xc=(Gc=r.features)==null?void 0:Gc.showReasoning)!=null?Xc:!0,Oe=(Yc=(Qc=r.features)==null?void 0:Qc.showToolCalls)!=null?Yc:!0,we=(ed=(Zc=r.features)==null?void 0:Zc.scrollToBottom)!=null?ed:{},zt(),Rr();let ye=de;if(de=(nd=(td=r.features)==null?void 0:td.showEventStreamToggle)!=null?nd:!1,de&&!ye){if(K||(re=new la(Pe),K=new ia(Le,re),ue=ue!=null?ue:new ca,re.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),E.setSSEEventCallback((Y,wt)=>{var Ft;(Ft=r.onSSEEvent)==null||Ft.call(r,Y,wt),ue==null||ue.processEvent(Y,wt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(wt)})})),!mt&&_e){let Y=(od=(rd=r.features)==null?void 0:rd.eventStream)==null?void 0:od.classNames,wt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");mt=h("button",wt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Ft=be("activity","18px","currentColor",1.5);Ft&&mt.appendChild(Ft);let pt=Ae.clearChatButtonWrapper,kt=Ae.closeButtonWrapper,an=pt||kt;an&&an.parentNode===_e?_e.insertBefore(mt,an):_e.appendChild(mt),mt.addEventListener("click",()=>{ge?Nn():xn()})}}else!de&&ye&&(Nn(),mt&&(mt.remove(),mt=null),K==null||K.clear(),re==null||re.destroy(),K=null,re=null,ue==null||ue.reset(),ue=null);if(((sd=r.launcher)==null?void 0:sd.enabled)===!1&&Je&&(Je.destroy(),Je=null),((ad=r.launcher)==null?void 0:ad.enabled)===!1&&Ze&&(Ze.remove(),Ze=null),((id=r.launcher)==null?void 0:id.enabled)!==!1&&!Je&&!Ze){let Y=s.find(wt=>wt.renderLauncher);if(Y!=null&&Y.renderLauncher){let wt=Y.renderLauncher({config:r,defaultRenderer:()=>ra(r,Ke).element,onToggle:Ke});wt&&(Ze=wt,e.appendChild(Ze))}Ze||(Je=ra(r,Ke),e.appendChild(Je.element))}Je&&Je.update(r),De&&((ld=r.launcher)==null?void 0:ld.title)!==void 0&&(De.textContent=r.launcher.title),Qe&&((cd=r.launcher)==null?void 0:cd.subtitle)!==void 0&&(Qe.textContent=r.launcher.subtitle);let Se=(dd=r.layout)==null?void 0:dd.header;if((Se==null?void 0:Se.layout)!==C&&_e){let Y=Se?ls(r,Se,{showClose:$(),onClose:()=>Ht(!1,"user")}):_r({config:r,showClose:$(),onClose:()=>Ht(!1,"user")});_e.replaceWith(Y.header),_e=Y.header,se=Y.iconHolder,De=Y.headerTitle,Qe=Y.headerSubtitle,B=Y.closeButton,C=Se==null?void 0:Se.layout}else if(Se&&(se&&(se.style.display=Se.showIcon===!1?"none":""),De&&(De.style.display=Se.showTitle===!1?"none":""),Qe&&(Qe.style.display=Se.showSubtitle===!1?"none":""),B&&(B.style.display=Se.showCloseButton===!1?"none":""),Ae.clearChatButtonWrapper)){let Y=Se.showClearChat;if(Y!==void 0){Ae.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:wt}=Ae;wt&&!wt.classList.contains("persona-absolute")&&(Y?wt.classList.remove("persona-ml-auto"):wt.classList.add("persona-ml-auto"))}}let nt=((pd=r.layout)==null?void 0:pd.showHeader)!==!1;_e&&(_e.style.display=nt?"":"none");let Ge=((ud=r.layout)==null?void 0:ud.showFooter)!==!1;$e&&($e.style.display=Ge?"":"none"),xt(),Rr(),S!==P?S?Ht(W,"auto"):(D=!0,no()):W!==O&&Ht(W,"auto"),O=W,P=S,Qt(),dn();let Me=JSON.stringify(c.toolCall)!==JSON.stringify(g),Te=JSON.stringify(r.messageActions)!==JSON.stringify(y),Ue=JSON.stringify((md=r.layout)==null?void 0:md.messages)!==JSON.stringify(b),M=((gd=r.loadingIndicator)==null?void 0:gd.render)!==(N==null?void 0:N.render)||((fd=r.loadingIndicator)==null?void 0:fd.renderIdle)!==(N==null?void 0:N.renderIdle)||((hd=r.loadingIndicator)==null?void 0:hd.showBubble)!==(N==null?void 0:N.showBubble),Ee=r.iterationDisplay!==F,Ie=((bd=(yd=r.features)==null?void 0:yd.showReasoning)!=null?bd:!0)!==(q!=null?q:!0)||((vd=(xd=r.features)==null?void 0:xd.showToolCalls)!=null?vd:!0)!==(H!=null?H:!0)||JSON.stringify((wd=r.features)==null?void 0:wd.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Cd=r.features)==null?void 0:Cd.reasoningDisplay)!==JSON.stringify(ce);(Me||Te||Ue||M||Ee||Ie)&&E&&(xs++,xo(je,E.getMessages(),We));let ve=(Ad=r.launcher)!=null?Ad:{},Pt=(Sd=ve.headerIconHidden)!=null?Sd:!1,at=(Td=(Ed=r.layout)==null?void 0:Ed.header)==null?void 0:Td.showIcon,Yt=Pt||at===!1,pn=ve.headerIconName,Wt=(Md=ve.headerIconSize)!=null?Md:"48px";if(se){let Y=pe.querySelector(".persona-border-b-persona-divider"),wt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(Yt)se.style.display="none",Y&&wt&&!Y.contains(wt)&&Y.insertBefore(wt,Y.firstChild);else{if(se.style.display="",se.style.height=Wt,se.style.width=Wt,Y&&wt&&(Y.contains(se)?se.nextSibling!==wt&&(se.remove(),Y.insertBefore(se,wt)):Y.insertBefore(se,wt)),pn){let pt=parseFloat(Wt)||24,kt=be(pn,pt*.6,"#ffffff",2);kt?se.replaceChildren(kt):se.textContent=(kd=ve.agentIconText)!=null?kd:"\u{1F4AC}"}else if(ve.iconUrl){let pt=se.querySelector("img");if(pt)pt.src=ve.iconUrl,pt.style.height=Wt,pt.style.width=Wt;else{let kt=document.createElement("img");kt.src=ve.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Wt,kt.style.width=Wt,se.replaceChildren(kt)}}else{let pt=se.querySelector("svg"),kt=se.querySelector("img");(pt||kt)&&se.replaceChildren(),se.textContent=(Ld=ve.agentIconText)!=null?Ld:"\u{1F4AC}"}let Ft=se.querySelector("img");Ft&&(Ft.style.height=Wt,Ft.style.width=Wt)}}let An=(Id=(Pd=r.layout)==null?void 0:Pd.header)==null?void 0:Id.showTitle,un=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showSubtitle;if(De&&(De.style.display=An===!1?"none":""),Qe&&(Qe.style.display=un===!1?"none":""),B){((Bd=(Hd=r.layout)==null?void 0:Hd.header)==null?void 0:Bd.showCloseButton)===!1?B.style.display="none":B.style.display="";let wt=(Dd=ve.closeButtonSize)!=null?Dd:"32px",Ft=(Nd=ve.closeButtonPlacement)!=null?Nd:"inline";B.style.height=wt,B.style.width=wt;let{closeButtonWrapper:pt}=Ae,kt=Ft==="top-right",an=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&kt!==an)if(pt.remove(),kt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(pt);else{let ut=(Fd=(Od=ve.clearChat)==null?void 0:Od.placement)!=null?Fd:"inline",ln=($d=(_d=ve.clearChat)==null?void 0:_d.enabled)!=null?$d:!0;pt.className=ln&&ut==="inline"?"":"persona-ml-auto";let Hn=pe.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(pt)}if(B.style.color=ve.closeButtonColor||Mn.actionIconColor,ve.closeButtonBackgroundColor?(B.style.backgroundColor=ve.closeButtonBackgroundColor,B.classList.remove("hover:persona-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ut=ve.closeButtonBorderWidth||"0px",ln=ve.closeButtonBorderColor||"transparent";B.style.border=`${ut} solid ${ln}`,B.classList.remove("persona-border-none")}else B.style.border="",B.classList.add("persona-border-none");ve.closeButtonBorderRadius?(B.style.borderRadius=ve.closeButtonBorderRadius,B.classList.remove("persona-rounded-full")):(B.style.borderRadius="",B.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(B.style.paddingLeft=ve.closeButtonPaddingX,B.style.paddingRight=ve.closeButtonPaddingX):(B.style.paddingLeft="",B.style.paddingRight=""),ve.closeButtonPaddingY?(B.style.paddingTop=ve.closeButtonPaddingY,B.style.paddingBottom=ve.closeButtonPaddingY):(B.style.paddingTop="",B.style.paddingBottom="");let fn=(jd=ve.closeButtonIconName)!=null?jd:"x",yr=(Ud=ve.closeButtonIconText)!=null?Ud:"\xD7";B.innerHTML="";let Tn=be(fn,"28px","currentColor",1);Tn?B.appendChild(Tn):B.textContent=yr;let Zt=(qd=ve.closeButtonTooltipText)!=null?qd:"Close chat",Gn=(zd=ve.closeButtonShowTooltip)!=null?zd:!0;if(B.setAttribute("aria-label",Zt),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!B)return;let Mo=B.ownerDocument,Ns=Mo.body;if(!Ns)return;ut=Er(Mo,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Os=Er(Mo,"div");Os.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Os);let ko=B.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(ao),ut.style.left=`${ko.left+ko.width/2}px`,ut.style.top=`${ko.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};pt.addEventListener("mouseenter",ln),pt.addEventListener("mouseleave",Hn),B.addEventListener("focus",ln),B.addEventListener("blur",Hn),pt._cleanupTooltip=()=>{Hn(),pt&&(pt.removeEventListener("mouseenter",ln),pt.removeEventListener("mouseleave",Hn)),B&&(B.removeEventListener("focus",ln),B.removeEventListener("blur",Hn))}}}let{clearChatButton:et,clearChatButtonWrapper:dt}=Ae;if(et){let Y=(Vd=ve.clearChat)!=null?Vd:{},wt=(Kd=Y.enabled)!=null?Kd:!0,Ft=(Gd=(Jd=r.layout)==null?void 0:Jd.header)==null?void 0:Gd.showClearChat,pt=Ft!==void 0?Ft:wt,kt=(Xd=Y.placement)!=null?Xd:"inline";if(dt){dt.style.display=pt?"":"none";let{closeButtonWrapper:an}=Ae;!_()&&an&&!an.classList.contains("persona-absolute")&&(pt?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let fn=kt==="top-right",yr=dt.classList.contains("persona-absolute");if(!_()&&fn!==yr&&pt){if(dt.remove(),fn)dt.className="persona-absolute persona-top-4 persona-z-50",dt.style.right="48px",pe.style.position="relative",pe.appendChild(dt);else{dt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",dt.style.right="";let Zt=pe.querySelector(".persona-border-b-persona-divider"),Gn=Ae.closeButtonWrapper;Zt&&Gn&&Gn.parentElement===Zt?Zt.insertBefore(dt,Gn):Zt&&Zt.appendChild(dt)}let Tn=Ae.closeButtonWrapper;Tn&&!Tn.classList.contains("persona-absolute")&&(fn?Tn.classList.add("persona-ml-auto"):Tn.classList.remove("persona-ml-auto"))}}if(pt){if(!_()){let ut=(Qd=Y.size)!=null?Qd:"32px";et.style.height=ut,et.style.width=ut}let an=(Yd=Y.iconName)!=null?Yd:"refresh-cw",fn=(Zd=Y.iconColor)!=null?Zd:"";et.style.color=fn||Mn.actionIconColor,et.innerHTML="";let yr=_()?"14px":"20px",Tn=be(an,yr,"currentColor",2);if(Tn&&et.appendChild(Tn),Y.backgroundColor?(et.style.backgroundColor=Y.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let ut=Y.borderWidth||"0px",ln=Y.borderColor||"transparent";et.style.border=`${ut} solid ${ln}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");Y.borderRadius?(et.style.borderRadius=Y.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),Y.paddingX?(et.style.paddingLeft=Y.paddingX,et.style.paddingRight=Y.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),Y.paddingY?(et.style.paddingTop=Y.paddingY,et.style.paddingBottom=Y.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let Zt=(ep=Y.tooltipText)!=null?ep:"Clear chat",Gn=(tp=Y.showTooltip)!=null?tp:!0;if(et.setAttribute("aria-label",Zt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!et)return;let Mo=et.ownerDocument,Ns=Mo.body;if(!Ns)return;ut=Er(Mo,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Os=Er(Mo,"div");Os.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Os);let ko=et.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(ao),ut.style.left=`${ko.left+ko.width/2}px`,ut.style.top=`${ko.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",ln),dt.addEventListener("mouseleave",Hn),et.addEventListener("focus",ln),et.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",ln),dt.removeEventListener("mouseleave",Hn)),et&&(et.removeEventListener("focus",ln),et.removeEventListener("blur",Hn))}}}}let Sn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],gn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[$o.message,$o.messageAndClick];T=ua({parsers:Sn,handlers:gn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),We=Am(r,T,oe),E.updateConfig(r),xo(je,E.getMessages(),We),pr.render(r.suggestionChips,E,X,void 0,r.suggestionChipsConfig),Ms(),Vo(E.isStreaming());let Co=((np=r.voiceRecognition)==null?void 0:np.enabled)===!0,Ao=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),So=((op=(rp=r.voiceRecognition)==null?void 0:rp.provider)==null?void 0:op.type)==="runtype";if(Co&&(Ao||So))if(!J||!ft){let Y=Xo(r.voiceRecognition,r.sendButton);Y&&(J=Y.micButton,ft=Y.micButtonWrapper,$t.insertBefore(ft,kn),J.addEventListener("click",ze),J.disabled=E.isStreaming())}else{let Y=(sp=r.voiceRecognition)!=null?sp:{},wt=(ap=r.sendButton)!=null?ap:{},Ft=(ip=Y.iconName)!=null?ip:"mic",pt=(lp=wt.size)!=null?lp:"40px",kt=(cp=Y.iconSize)!=null?cp:pt,an=parseFloat(kt)||24;J.style.width=kt,J.style.height=kt,J.style.minWidth=kt,J.style.minHeight=kt;let fn=(pp=(dp=Y.iconColor)!=null?dp:wt.textColor)!=null?pp:"currentColor";J.innerHTML="";let yr=be(Ft,an,fn,2);yr?J.appendChild(yr):J.textContent="\u{1F3A4}";let Tn=(up=Y.backgroundColor)!=null?up:wt.backgroundColor;Tn?J.style.backgroundColor=Tn:J.style.backgroundColor="",fn?J.style.color=fn:J.style.color="var(--persona-text, #111827)",Y.borderWidth?(J.style.borderWidth=Y.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),Y.borderColor?J.style.borderColor=Y.borderColor:J.style.borderColor="",Y.paddingX?(J.style.paddingLeft=Y.paddingX,J.style.paddingRight=Y.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),Y.paddingY?(J.style.paddingTop=Y.paddingY,J.style.paddingBottom=Y.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Zt=ft==null?void 0:ft.querySelector(".persona-send-button-tooltip"),Gn=(mp=Y.tooltipText)!=null?mp:"Start voice recognition";if(((gp=Y.showTooltip)!=null?gp:!1)&&Gn)if(Zt)Zt.textContent=Gn,Zt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Gn,ft==null||ft.insertBefore(ln,J)}else Zt&&(Zt.style.display="none");ft.style.display="",J.disabled=E.isStreaming()}else J&&ft&&(ft.style.display="none",((hp=(fp=r.voiceRecognition)==null?void 0:fp.provider)==null?void 0:hp.type)==="runtype"?E.isVoiceActive()&&E.toggleVoice():Kn&&hr());if(((yp=r.attachments)==null?void 0:yp.enabled)===!0)if(!qt||!rt){let Y=(bp=r.attachments)!=null?bp:{},Ft=(vp=((xp=r.sendButton)!=null?xp:{}).size)!=null?vp:"40px";xe||(xe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xe.style.display="none",Ot.insertBefore(xe,X)),ae||(ae=document.createElement("input"),ae.type="file",ae.accept=((wp=Y.allowedTypes)!=null?wp:Fr).join(","),ae.multiple=((Cp=Y.maxFiles)!=null?Cp:4)>1,ae.style.display="none",ae.setAttribute("aria-label","Attach files"),Ot.insertBefore(ae,X)),qt=h("div","persona-send-button-wrapper"),rt=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),rt.type="button",rt.setAttribute("aria-label",(Ap=Y.buttonTooltipText)!=null?Ap:"Attach file");let pt=(Sp=Y.buttonIconName)!=null?Sp:"paperclip",kt=Ft,an=parseFloat(kt)||40,fn=Math.round(an*.6);rt.style.width=kt,rt.style.height=kt,rt.style.minWidth=kt,rt.style.minHeight=kt,rt.style.fontSize="18px",rt.style.lineHeight="1",rt.style.backgroundColor="transparent",rt.style.color="var(--persona-primary, #111827)",rt.style.border="none",rt.style.borderRadius="6px",rt.style.transition="background-color 0.15s ease",rt.addEventListener("mouseenter",()=>{rt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),rt.addEventListener("mouseleave",()=>{rt.style.backgroundColor="transparent"});let yr=be(pt,fn,"currentColor",1.5);yr?rt.appendChild(yr):rt.textContent="\u{1F4CE}",rt.addEventListener("click",Gn=>{Gn.preventDefault(),ae==null||ae.click()}),qt.appendChild(rt);let Tn=(Ep=Y.buttonTooltipText)!=null?Ep:"Attach file",Zt=h("div","persona-send-button-tooltip");Zt.textContent=Tn,qt.appendChild(Zt),St.append(qt),!tt&&ae&&xe&&(tt=Do.fromConfig(Y),tt.setPreviewsContainer(xe),ae.addEventListener("change",async()=>{tt&&(ae!=null&&ae.files)&&(await tt.handleFileSelect(ae.files),ae.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(Sm(Y.dropOverlay))}else{qt.style.display="";let Y=(Tp=r.attachments)!=null?Tp:{};ae&&(ae.accept=((Mp=Y.allowedTypes)!=null?Mp:Fr).join(","),ae.multiple=((kp=Y.maxFiles)!=null?kp:4)>1),tt&&tt.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else qt&&(qt.style.display="none"),tt&&tt.clearAttachments(),(Lp=pe.querySelector(".persona-attachment-drop-overlay"))==null||Lp.remove();let Vt=(Pp=r.sendButton)!=null?Pp:{},Eo=(Ip=Vt.useIcon)!=null?Ip:!1,oo=(Wp=Vt.iconText)!=null?Wp:"\u2191",bt=Vt.iconName,In=(Rp=Vt.tooltipText)!=null?Rp:"Send message",Dr=(Hp=Vt.showTooltip)!=null?Hp:!1,En=(Bp=Vt.size)!=null?Bp:"40px",Wn=Vt.backgroundColor,Bt=Vt.textColor;if(Eo){if(Fe.style.width=En,Fe.style.height=En,Fe.style.minWidth=En,Fe.style.minHeight=En,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.innerHTML="",Bt?Fe.style.color=Bt:Fe.style.color="var(--persona-button-primary-fg, #ffffff)",bt){let Y=parseFloat(En)||24,wt=(Bt==null?void 0:Bt.trim())||"currentColor",Ft=be(bt,Y,wt,2);Ft?Fe.appendChild(Ft):Fe.textContent=oo}else Fe.textContent=oo;Fe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-primary")):(Fe.style.backgroundColor="",Fe.classList.add("persona-bg-persona-primary"))}else Fe.textContent=(Np=(Dp=r.copy)==null?void 0:Dp.sendButtonLabel)!=null?Np:"Send",Fe.style.width="",Fe.style.height="",Fe.style.minWidth="",Fe.style.minHeight="",Fe.style.fontSize="",Fe.style.lineHeight="",Fe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-accent")):Fe.classList.add("persona-bg-persona-accent"),Bt?Fe.style.color=Bt:Fe.classList.add("persona-text-white");Vt.borderWidth?(Fe.style.borderWidth=Vt.borderWidth,Fe.style.borderStyle="solid"):(Fe.style.borderWidth="",Fe.style.borderStyle=""),Vt.borderColor?Fe.style.borderColor=Vt.borderColor:Fe.style.borderColor="",Vt.paddingX?(Fe.style.paddingLeft=Vt.paddingX,Fe.style.paddingRight=Vt.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),Vt.paddingY?(Fe.style.paddingTop=Vt.paddingY,Fe.style.paddingBottom=Vt.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Ut=kn==null?void 0:kn.querySelector(".persona-send-button-tooltip");if(Dr&&In)if(Ut)Ut.textContent=In,Ut.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=In,kn==null||kn.insertBefore(Y,Fe)}else Ut&&(Ut.style.display="none");let Dt=(jp=(Op=r.layout)==null?void 0:Op.contentMaxWidth)!=null?jp:_()?($p=(_p=(Fp=r.launcher)==null?void 0:Fp.composerBar)==null?void 0:_p.contentMaxWidth)!=null?$p:"720px":void 0;Dt?(je.style.maxWidth=Dt,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%",Ot&&(Ot.style.maxWidth=Dt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),At&&(At.style.maxWidth=Dt,At.style.marginLeft="auto",At.style.marginRight="auto")):(je.style.maxWidth="",je.style.marginLeft="",je.style.marginRight="",je.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),At&&(At.style.maxWidth="",At.style.marginLeft="",At.style.marginRight=""));let Kt=(Up=r.statusIndicator)!=null?Up:{},Rn=(qp=Kt.visible)!=null?qp:!0;if(cn.style.display=Rn?"":"none",E){let Y=E.getStatus();fe(cn,(Ft=>{var pt,kt,an,fn;return Ft==="idle"?(pt=Kt.idleText)!=null?pt:hn.idle:Ft==="connecting"?(kt=Kt.connectingText)!=null?kt:hn.connecting:Ft==="connected"?(an=Kt.connectedText)!=null?an:hn.connected:Ft==="error"?(fn=Kt.errorText)!=null?fn:hn.error:hn[Ft]})(Y),Kt,Y)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Jn=Kt.align==="left"?"persona-text-left":Kt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Jn)},open(){$()&&Ht(!0,"api")},close(){$()&&Ht(!1,"api")},toggle(){$()&&Ht(!D,"api")},clearChat(){vn=!1,E.clearMessages(),ur.clear(),Qr();try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},T.syncFromMetadata(),K==null||K.clear(),ue==null||ue.reset(),he==null||he.update()},setMessage(c){return!X||E.isStreaming()?!1:(!D&&$()&&Ht(!0,"system"),X.value=c,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(E.isStreaming())return!1;let g=(c==null?void 0:c.trim())||X.value.trim();return g?(!D&&$()&&Ht(!0,"system"),X.value="",X.style.height="auto",E.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return E.isStreaming()?!1:((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(E.isVoiceActive()||(!D&&$()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),E.toggleVoice().then(()=>{gt.active=E.isVoiceActive(),or("user"),E.isVoiceActive()&&k()})),!0):Kn?!0:Hs()?(!D&&$()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),wo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?E.isVoiceActive()?(E.toggleVoice().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),G()}),!0):!1:Kn?(gt.manuallyDeactivated=!0,Pn(),hr("user"),!0):!1},injectMessage(c){return!D&&$()&&Ht(!0,"system"),E.injectMessage(c)},injectAssistantMessage(c){!D&&$()&&Ht(!0,"system");let g=E.injectAssistantMessage(c);return U&&(U=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)),g},injectUserMessage(c){return!D&&$()&&Ht(!0,"system"),E.injectUserMessage(c)},injectSystemMessage(c){return!D&&$()&&Ht(!0,"system"),E.injectSystemMessage(c)},injectMessageBatch(c){return!D&&$()&&Ht(!0,"system"),E.injectMessageBatch(c)},injectComponentDirective(c){return!D&&$()&&Ht(!0,"system"),E.injectComponentDirective(c)},injectTestMessage(c){!D&&$()&&Ht(!0,"system"),E.injectTestEvent(c)},async connectStream(c,g){return E.connectStream(c,g)},__pushEventStreamEvent(c){K&&(ue==null||ue.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!de||!K||xn()},hideEventStream(){ge&&Nn()},isEventStreamVisible(){return ge},showArtifacts(){cr(r)&&(vn=!1,Un(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(vn=!0,Un())},upsertArtifact(c){return cr(r)?(vn=!1,E.upsertArtifact(c)):null},selectArtifact(c){cr(r)&&E.selectArtifact(c)},clearArtifacts(){cr(r)&&E.clearArtifacts()},getArtifacts(){var c;return(c=E==null?void 0:E.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=E==null?void 0:E.getSelectedArtifactId())!=null?c:null},focusInput(){return S&&!D&&!_()||!X?!1:(X.focus(),!0)},async resolveApproval(c,g){let b=E.getMessages().find(L=>{var N;return L.variant==="approval"&&((N=L.approval)==null?void 0:N.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){E.resolveWebMcpApproval(b.id,g);return}return E.resolveApproval(b.approval,g)},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return $()&&D},isVoiceActive(){return gt.active},getState(){return{open:$()&&D,launcherEnabled:S,voiceActive:gt.active,streaming:E.isStreaming()}},showCSATFeedback(c){!D&&$()&&Ht(!0,"system");let g=je.querySelector(".persona-feedback-container");g&&g.remove();let y=Ri({onSubmit:async(b,L)=>{var N;E.isClientTokenMode()&&await E.submitCSATFeedback(b,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,b,L)},onDismiss:c==null?void 0:c.onDismiss,...c});je.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!D&&$()&&Ht(!0,"system");let g=je.querySelector(".persona-feedback-container");g&&g.remove();let y=Hi({onSubmit:async(b,L)=>{var N;E.isClientTokenMode()&&await E.submitNPSFeedback(b,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,b,L)},onDismiss:c==null?void 0:c.onDismiss,...c});je.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return E.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return E.submitNPSFeedback(c,g)},destroy(){Ar!=null&&(clearInterval(Ar),Ar=null),ht.forEach(c=>c()),le.remove(),Ye==null||Ye.remove(),Je==null||Je.destroy(),Ze==null||Ze.remove(),zn&&B.removeEventListener("click",zn)}};if((((Uc=n==null?void 0:n.debugTools)!=null?Uc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:nn,getMessages:nn.getMessages,getStatus:nn.getStatus,getMetadata:nn.getPersistentMetadata,updateMetadata:nn.updatePersistentMetadata,clearHistory:()=>nn.clearChat(),setVoiceActive:y=>y?nn.startVoiceRecognition():nn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ht.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",g),ht.push(()=>{window.removeEventListener("persona:focusInput",g)}),de){let q=Ce=>{let ce=Ce.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&nn.showEventStream()},H=Ce=>{let ce=Ce.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",H),ht.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",H)})}let y=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&nn.showArtifacts()},b=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&nn.hideArtifacts()},L=q=>{let H=q.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&nn.upsertArtifact(H.artifact)},N=q=>{let H=q.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&nn.selectArtifact(H.id)},F=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",F),ht.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",F)})}let ar=Wh(r.persistState);if(ar&&$()){let c=Rh(ar.storage),g=`${ar.keyPrefix}widget-open`,y=`${ar.keyPrefix}widget-voice`,b=`${ar.keyPrefix}widget-voice-mode`;if(c){let L=((qc=ar.persist)==null?void 0:qc.openState)&&c.getItem(g)==="true",N=((zc=ar.persist)==null?void 0:zc.voiceState)&&c.getItem(y)==="true",F=((Vc=ar.persist)==null?void 0:Vc.voiceState)&&c.getItem(b)==="true";if(L&&setTimeout(()=>{nn.open(),setTimeout(()=>{var q;if(N||F)nn.startVoiceRecognition();else if((q=ar.persist)!=null&&q.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(Kc=ar.persist)!=null&&Kc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(Jc=ar.persist)!=null&&Jc.voiceState&&(o.on("voice:state",q=>{c.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{c.setItem(b,q.viaVoice?"true":"false")})),ar.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(b)},H=()=>q();window.addEventListener("persona:clear-chat",H),ht.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return u&&$()&&setTimeout(()=>{nn.open()},0),Hr(),nn};var Hh=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Em=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Hl=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=""},Tm=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Hl(e)},Il=e=>{e.style.transition=""},Wl=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=""},Rl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ni=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Bh=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Dh=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Mm=(e,t,n,r,s,o,a)=>{var v,x,T,S,W,I;let i=ir(o),d=i.reveal==="push";Bh(e,t,n,r,d),Dh(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,p=(S=(T=o==null?void 0:o.launcher)==null?void 0:T.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"),Wl(t),Il(r),Tm(r),Rl(n),Ni(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((I=(W=o==null?void 0:o.launcher)==null?void 0:W.zIndex)!=null?I:yn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Tm(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Wl(t),Il(r),Rl(n),Ni(s,r);let O=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=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=O,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Il(r),Hl(r),Ni(s,r);let O=Hh(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),C=i.animate?"transform 180ms ease":"none",R=i.side==="right"?a?`translateX(-${O}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${O}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${P+O}px`,t.style.transition=C,t.style.transform=R,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.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="",Wl(t),Hl(r),Rl(n),Ni(s,r);let O=i.reveal==="emerge";O?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",R=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",r.style.position="relative",r.style.overflow=O||R?"hidden":"visible",r.style.transition=C,O&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Nh=(e,t)=>{let n=e.ownerDocument.createElement("div");return Em(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Em(n,r)},destroy(){n.remove()}}},Oh=(e,t)=>{var W,I,O,P;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),u=n.createElement("div"),p=(I=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)==null||I?(P=(O=t==null?void 0:t.launcher)==null?void 0:O.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,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),ir(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Mm(a,i,d,l,u,t,p)}),f.observe(a))},x=()=>{Mm(a,i,d,l,u,t,p),v()},T=a.ownerDocument.defaultView,S=()=>{x()};return T==null||T.addEventListener("resize",S),ir(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(C){let R=C.launcherEnabled?C.open:!0;p!==R&&(p=R,x())},updateConfig(C){var R,_;t=C,((_=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)!=null?_:!0)===!1&&(p=!0),x()},destroy(){T==null||T.removeEventListener("resize",S),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ma=(e,t)=>on(t)?Oh(e,t):Nh(e,t);var Bl={},Fh=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},_h=()=>{try{if(typeof Bl!="undefined"&&Bl.url)return new URL("../widget.css",Bl.url).href}catch{}return null},km=(e,t)=>{let n=_h(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Dl=e=>{var T;let t=Fh(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=ma(t,s),a,i=[],d=(S,W)=>{var C,R;let O=!((R=(C=W==null?void 0:W.launcher)==null?void 0:C.enabled)!=null?R:!0)||on(W),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),O&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let _=S.attachShadow({mode:"open"});_.appendChild(P),km(_,r)}else S.appendChild(P),km(S,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let S=d(o.host,s);a=Di(S,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};p(),(T=e.onReady)==null||T.call(e);let m=S=>{f(),o.destroy(),o=ma(t,S),s=S,p()},v={update(S){var R,_,$,D,U,z;let W={...s,...S,launcher:{...(R=s==null?void 0:s.launcher)!=null?R:{},...(_=S==null?void 0:S.launcher)!=null?_:{},dock:{...(D=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?D:{},...(z=(U=S==null?void 0:S.launcher)==null?void 0:U.dock)!=null?z:{}}}},I=on(s),O=on(W),P=lo(s),C=lo(W);if(I!==O||P!==C){m(W);return}s=W,o.updateConfig(s),a.update(S),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(S,W,I){if(W==="host")return o.host;if(W in S)return Reflect.get(S,W,I);let O=a[W];return typeof O=="function"?O.bind(a):O}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Rm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),$h=new Set(["button","a","input","select","textarea","details","summary"]),jh=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Nl=/\b(product|card|item|listing|result)\b/i,Fl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Uh=3e3,qh=100;function Hm(e){let t=typeof e.className=="string"?e.className:"";if(Nl.test(t)||e.id&&Nl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Nl.test(r.value))return!0}return!1}function Bm(e){var t;return Fl.test(((t=e.textContent)!=null?t:"").trim())}function Dm(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function zh(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Lm(e){let t=e.match(Fl);return t?t[0]:null}function Pm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Vh(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var Kh="commerce-card",Jh="result-card";function Im(e){return!Hm(e)||!Bm(e)||!Dm(e)&&!zh(e)?0:5200}function Wm(e){var r;return!Hm(e)||Bm(e)||!Dm(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 _l=[{id:Kh,scoreElement(e){return Im(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Fl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,u;if(Im(e)===0)return null;let{title:n,href:r}=Pm(e),s=(u=(l=Lm(((d=e.textContent)!=null?d:"").trim()))!=null?l:Lm(t.text))!=null?u:"",o=Vh(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
- `)}},{id:Jh,scoreElement(e){return Wm(e)},formatSummary(e,t){if(Wm(e)===0)return null;let{title:n,href:r}=Pm(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
- `)}}];function Gh(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Xh(e){var u,p,f,m,v,x,T,S,W,I,O,P,C;let t=(u=e.options)!=null?u:{},n=(f=(p=t.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(v=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(T=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?T:200,o=(W=(S=t.visibleOnly)!=null?S:e.visibleOnly)!=null?W:!0,a=(I=t.root)!=null?I:e.root,i=(O=t.mode)!=null?O:"structured",d=(P=t.maxCandidates)!=null?P:Math.max(500,n*10),l=(C=e.rules)!=null?C:_l;return i==="simple"&&e.rules&&e.rules.length>0?(Gh(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function Ol(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Qh=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Yh(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||$h.has(t)||n&&jh.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Nm(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Zh(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function $l(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Ol(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Qh){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${Ol(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>Ol(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function ey(e){return e==="static"?qh:Uh}function Om(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:$l(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Yh(e),attributes:Zh(e)}}function ty(e,t,n,r){let s=ey(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function ny(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function ry(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Rm.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Nm(l)){i=a.nextNode();continue}let p=Om(l,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(T=>T==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:v,formattingRule:x}=ty(l,p,e.rules,n);s.push({el:l,domIndex:o,enriched:p,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;ny(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,n);m&&(u=m)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function oy(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(Rm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Nm(d)){o=s.nextNode();continue}let u=Om(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),n.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Fm(e={}){var r;let t=Xh(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?oy(t,n):ry(t,n):[]}var Oi=100;function _m(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
107
+ `}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",Kt=g?"":"padding-top: 1.25em !important;",Rn=g?"":`z-index: ${(Ut=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?Ut:bn} !important;`;le.style.cssText+=Dt+Kt+Rn}M()};dr(),so(e,r),Ei(e,r),Mi(e,r);let ht=[];ht.push(()=>{document.removeEventListener("keydown",Kr)});let Gt=null,Xt=null;ht.push(()=>{Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null}),Fn&&ht.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),ht.push(()=>{wn==null||wn(),wn=null,Lr(),Rt&&(Rt.remove(),Rt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),de&&ht.push(()=>{me!==null&&(cancelAnimationFrame(me),me=null),he==null||he.destroy(),he=null,K==null||K.destroy(),K=null,re=null});let qn=null,Xr=()=>{qn&&(qn(),qn=null),r.colorScheme==="auto"&&(qn=ni(()=>{so(e,r)}))};Xr(),ht.push(()=>{qn&&(qn(),qn=null)});let rr=(Dc=r.features)==null?void 0:Dc.streamAnimation;if(rr!=null&&rr.type&&rr.type!=="none"){let c=Zs(rr.type,rr.plugins);c&&(ol(c,e),ht.push(()=>Du(e)))}let pr=sm(At),zn=null,T,Vn=!1,ur=Mu(),Pr=new Map,Cr=new Map,xs=0,mr=si(),gr=0,fr=null,Ir=!1,bo=!1,ga=4,vs=24,fa=80,qo=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ws=(Oc=(Nc=r.voiceRecognition)==null?void 0:Nc.autoResume)!=null?Oc:!1,or=c=>{o.emit("voice:state",{active:gt.active,source:c,timestamp:Date.now()})},Pn=()=>{m(c=>({...c,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},ha=()=>{var y,L;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Pl(d.voiceState),g=!!c.active,b=Number((L=c.timestamp)!=null?L:0);gt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<Wh&&setTimeout(()=>{var O,F;gt.active||(gt.manuallyDeactivated=!1,((F=(O=r.voiceRecognition)==null?void 0:O.provider)==null?void 0:F.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("restore"),T.isVoiceActive()&&k()}):wo("restore"))},1e3)},ba=()=>T?Sm(T.getMessages()).filter(c=>!c.__skipPersist):[];function zo(c){if(!(i!=null&&i.save))return;let b={messages:c?Sm(c):T?ba():[],metadata:d,artifacts:_n.artifacts,selectedArtifactId:_n.selectedId};try{let y=i.save(b);y instanceof Promise&&y.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Wr=null,ya=()=>le.querySelector("#persona-scroll-container")||Q,yo=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),Ir=!1},Cs=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),bo=!1,yo()},Rr=()=>{if(!yn()||ge){Mt.parentNode&&Mt.remove(),Mt.style.display="none";return}Mt.parentNode!==pe&&pe.appendChild(Mt),xt();let c=Gs(Q)>0;Mt.style.display=mr.isFollowing()||!c?"none":""},As=()=>{mr.pause()&&(Cs(),Rr())},Qr=()=>{mr.resume(),Rr()},Yr=(c=!1)=>{mr.isFollowing()&&(!c&&!Vn||(fr!==null&&(cancelAnimationFrame(fr),fr=null),bo=!0,fr=requestAnimationFrame(()=>{fr=null,bo=!1,mr.isFollowing()&&xa(ya(),c?220:140)})))},xa=(c,g=500)=>{let b=c.scrollTop,y=Gs(c),L=y-b;if(Math.abs(L)<1){gr=c.scrollTop;return}if(Math.abs(L)>=fa){yo(),Ir=!0,c.scrollTop=y,gr=c.scrollTop,Ir=!1;return}yo();let O=performance.now();Ir=!0;let F=B=>1-Math.pow(1-B,3),q=B=>{if(!mr.isFollowing()){yo();return}let Ce=Gs(c);Ce!==y&&(y=Ce,L=y-b);let ce=B-O,te=Math.min(ce/g,1),be=F(te),Se=b+L*be;c.scrollTop=Se,gr=c.scrollTop,te<1?Wr=requestAnimationFrame(q):(c.scrollTop=y,gr=c.scrollTop,Wr=null,Ir=!1)};Wr=requestAnimationFrame(q)},va=c=>{let g=new Map;c.forEach(b=>{let y=qo.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(y!=null&&y.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(y?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),qo.clear(),g.forEach((b,y)=>{qo.set(y,b)})},xo=(c,g,b)=>{var Ge,lt,ct,Me,Ee,Ue;let y=document.createElement("div"),O=(()=>{var Te;let M=s.find(Ie=>Ie.renderLoadingIndicator);if(M!=null&&M.renderLoadingIndicator)return M.renderLoadingIndicator;if((Te=r.loadingIndicator)!=null&&Te.render)return r.loadingIndicator.render})(),F=(M,Te)=>Te==null?!1:typeof Te=="string"?(M.textContent=Te,!0):(M.appendChild(Te),!0),q=new Set,B=new Set,Ce=s.some(M=>M.renderAskUserQuestion),ce=[],te=[],be=r.enableComponentStreaming!==!1;if(g.forEach(M=>{var An,un,et,dt,Sn,gn,Co,Ao,So,Yo,Zo,Vt,To,oo;q.add(M.id);let Te=Ce&&$r(M),Ie=!Te&&M.role==="assistant"&&!M.variant&&be&&Ii(M);if(!Ie&&Cr.has(M.id)){let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),Cr.delete(M.id)}let Ve=$r(M)?`:${(An=M.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(un=M.agentMetadata)!=null&&un.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",ve=Eu(M,xs)+Ve,Pt=Te||Ie?null:ku(ur,M.id,ve);if(Pt){y.appendChild(Pt.cloneNode(!0)),$r(M)&&((et=M.toolCall)!=null&&et.id)&&((dt=M.agentMetadata)==null?void 0:dt.awaitingLocalTool)===!0&&!((Sn=M.agentMetadata)!=null&&Sn.askUserQuestionAnswered)&&(B.add(M.toolCall.id),fs(M,r,Ae.composerOverlay));return}let at=null,Yt=s.find(yt=>!!(M.variant==="reasoning"&&yt.renderReasoning||M.variant==="tool"&&yt.renderToolCall||M.variant==="approval"&&yt.renderApproval||!M.variant&&yt.renderMessage)),pn=(gn=r.layout)==null?void 0:gn.messages;if($r(M)&&((Co=M.agentMetadata)==null?void 0:Co.askUserQuestionAnswered)===!0){Pr.delete(M.id);let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if($r(M)&&((So=(Ao=r.features)==null?void 0:Ao.askUserQuestion)==null?void 0:So.enabled)!==!1){let yt=s.find(In=>typeof In.renderAskUserQuestion=="function");if(yt&&It.current){let In=Pr.get(M.id),Dr=In!==ve,Tn=null;if(Dr){let{payload:Ut,complete:Dt}=jr(M),Kt=M.id,Rn=()=>{var Jn;return(Jn=It.current)==null?void 0:Jn.getMessages().find(rn=>rn.id===Kt)};Tn=yt.renderAskUserQuestion({message:M,payload:Ut,complete:Dt,resolve:Jn=>{var Sr;let rn=Rn();rn&&((Sr=It.current)==null||Sr.resolveAskUserQuestion(rn,Jn))},dismiss:()=>{var rn,Sr,Nr;let Jn=Rn();(rn=Jn==null?void 0:Jn.agentMetadata)!=null&&rn.awaitingLocalTool&&((Sr=It.current)==null||Sr.markAskUserQuestionResolved(Jn),(Nr=It.current)==null||Nr.resolveAskUserQuestion(Jn,"(dismissed)"))},config:r})}let Wn=In!=null;if(Dr&&Tn===null&&!Wn){((Yo=M.agentMetadata)==null?void 0:Yo.awaitingLocalTool)===!0&&!((Zo=M.agentMetadata)!=null&&Zo.askUserQuestionAnswered)&&(B.add(M.toolCall.id),fs(M,r,Ae.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),y.appendChild(Bt),ce.push({messageId:M.id,fingerprint:ve,bubble:Tn});return}else{((Vt=M.agentMetadata)==null?void 0:Vt.awaitingLocalTool)===!0&&!((To=M.agentMetadata)!=null&&To.askUserQuestionAnswered)&&(B.add(M.toolCall.id),fs(M,r,Ae.composerOverlay));return}}else if(Yt)if(M.variant==="reasoning"&&M.reasoning&&Yt.renderReasoning){if(!He)return;at=Yt.renderReasoning({message:M,defaultRenderer:()=>gl(M,r),config:r})}else if(M.variant==="tool"&&M.toolCall&&Yt.renderToolCall){if(!Oe)return;at=Yt.renderToolCall({message:M,defaultRenderer:()=>fl(M,r),config:r})}else if(M.variant==="approval"&&M.approval&&Yt.renderApproval){if(r.approval===!1)return;at=Yt.renderApproval({message:M,defaultRenderer:()=>Al(M,r),config:r})}else Yt.renderMessage&&(at=Yt.renderMessage({message:M,defaultRenderer:()=>{let yt=ds(M,b,pn,r.messageActions,V,{loadingIndicatorRenderer:O,widgetConfig:r});return M.role!=="user"&&Ml(yt,M,r,T),yt},config:r}));if(!at&&Ie){let yt=Wi(M);if(yt){let In=Cr.get(M.id),Dr=In!==ve,Tn=r.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Dr){let Bt=Pi(yt,{config:r,message:M,transform:b});if(Bt)if(Tn){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-${M.id}`,Ut.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=b({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Bt),Wn=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-${M.id}`,Ut.setAttribute("data-message-id",M.id),Ut.setAttribute("data-persona-component-directive","true"),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=b({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Bt),Wn=Ut}}if(Wn||In!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),Tn||Bt.classList.add("persona-w-full"),y.appendChild(Bt),te.push({messageId:M.id,fingerprint:ve,bubble:Wn});return}}}if(!at)if(M.variant==="reasoning"&&M.reasoning){if(!He)return;at=gl(M,r)}else if(M.variant==="tool"&&M.toolCall){if(!Oe)return;at=fl(M,r)}else if(M.variant==="approval"&&M.approval){if(r.approval===!1)return;at=Al(M,r)}else{let yt=(oo=r.layout)==null?void 0:oo.messages;yt!=null&&yt.renderUserMessage&&M.role==="user"?at=yt.renderUserMessage({message:M,config:r,streaming:!!M.streaming}):yt!=null&&yt.renderAssistantMessage&&M.role==="assistant"?at=yt.renderAssistantMessage({message:M,config:r,streaming:!!M.streaming}):at=ds(M,b,yt,r.messageActions,V,{loadingIndicatorRenderer:O,widgetConfig:r}),M.role!=="user"&&at&&Ml(at,M,r,T)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${M.id}`,Wt.setAttribute("data-wrapper-id",M.id),M.role==="user"&&Wt.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(at),Lu(ur,M.id,ve,Wt),y.appendChild(Wt)}),Ae.composerOverlay&&Ae.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Ie=Te.getAttribute("data-persona-ask-sheet-for");Ie&&!B.has(Ie)&&mo(Ae.composerOverlay,Ie)}),(lt=(Ge=r.features)==null?void 0:Ge.toolCallDisplay)!=null&&lt.grouped){let M=[],Te=[];g.forEach(Ie=>{if(Ie.variant==="tool"&&Ie.toolCall&&Oe){Te.push(Ie);return}Te.length>1&&M.push(Te),Te=[]}),Te.length>1&&M.push(Te),M.forEach((Ie,Ve)=>{var un,et;let ve=Ie.map(dt=>Array.from(y.children).find(Sn=>Sn instanceof HTMLElement&&Sn.getAttribute("data-wrapper-id")===dt.id)).filter(dt=>!!dt);if(ve.length<2)return;let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-tool-group-${Ve}-${Ie[0].id}`,Pt.setAttribute("data-wrapper-id",`tool-group-${Ve}-${Ie[0].id}`);let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Yt=document.createElement("div");Yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let pn=`Called ${Ie.length} tools`,Wt=(et=(un=r.toolCall)==null?void 0:un.renderGroupedSummary)==null?void 0:et.call(un,{messages:Ie,toolCalls:Ie.map(dt=>dt.toolCall).filter(dt=>!!dt),defaultSummary:pn,config:r});F(Yt,Wt)||(Yt.textContent=pn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Yt,An),Pt.appendChild(at),ve[0].before(Pt),ve.forEach((dt,Sn)=>{let gn=document.createElement("div");gn.className="persona-tool-group-item persona-relative",gn.setAttribute("data-persona-tool-group-item","true"),Sn<ve.length-1&&gn.setAttribute("data-persona-tool-group-connector","true"),gn.appendChild(dt),An.appendChild(gn)})})}Pu(ur,q);let Se=g.some(M=>M.role==="assistant"&&M.streaming),Be=g[g.length-1],nt=(Be==null?void 0:Be.role)==="assistant"&&!Be.streaming&&Be.variant!=="approval";if(Vn&&g.some(M=>M.role==="user")&&!Se&&!nt){let M={config:r,streaming:!0,location:"standalone",defaultRenderer:Oo},Te=s.find(Ve=>Ve.renderLoadingIndicator),Ie=null;if(Te!=null&&Te.renderLoadingIndicator&&(Ie=Te.renderLoadingIndicator(M)),Ie===null&&((ct=r.loadingIndicator)!=null&&ct.render)&&(Ie=r.loadingIndicator.render(M)),Ie===null&&(Ie=Oo()),Ie){let Ve=document.createElement("div"),ve=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;Ve.className=ve?["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(Ie);let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id="wrapper-typing-indicator",Pt.setAttribute("data-wrapper-id","typing-indicator"),Pt.appendChild(Ve),y.appendChild(Pt)}}if(!Vn&&g.length>0){let M=g[g.length-1],Te={config:r,lastMessage:M,messageCount:g.length},Ie=s.find(ve=>ve.renderIdleIndicator),Ve=null;if(Ie!=null&&Ie.renderIdleIndicator&&(Ve=Ie.renderIdleIndicator(Te)),Ve===null&&((Ee=r.loadingIndicator)!=null&&Ee.renderIdle)&&(Ve=r.loadingIndicator.renderIdle(Te)),Ve){let ve=document.createElement("div"),Pt=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ve.className=Pt?["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(" "),ve.setAttribute("data-idle-indicator","true"),ve.appendChild(Ve);let at=document.createElement("div");at.className="persona-flex",at.id="wrapper-idle-indicator",at.setAttribute("data-wrapper-id","idle-indicator"),at.appendChild(ve),y.appendChild(at)}}if(ri(c,y),ce.length>0)for(let{messageId:M,fingerprint:Te,bubble:Ie}of ce){let Ve=c.querySelector(`#wrapper-${M}`);Ve&&Ie!==null&&(Ve.replaceChildren(Ie),Ve.setAttribute("data-bubble-fp",Te),Pr.set(M,Te))}if(Pr.size>0)for(let M of Pr.keys())q.has(M)||Pr.delete(M);if(te.length>0)for(let{messageId:M,fingerprint:Te,bubble:Ie}of te){let Ve=c.querySelector(`#wrapper-${M}`);Ve&&Ie!==null&&(Ve.replaceChildren(Ie),Ve.setAttribute("data-bubble-fp",Te),Cr.set(M,Te))}if(Cr.size>0)for(let M of Cr.keys())q.has(M)||Cr.delete(M)},Zr=null,wa=()=>{var b;if(Zr)return;let c=y=>{let L=y.composedPath();L.includes(le)||Ye&&L.includes(Ye)||Ht(!1,"user")};Zr=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Ss=()=>{var g;if(!Zr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Zr,!0),Zr=null};ht.push(()=>Ss());let eo=null,Ca=()=>{var b;if(eo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ht(!1,"user"))};eo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Ts=()=>{var g;if(!eo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",eo,!0),eo=null};ht.push(()=>Ts());let to=!1,Es=new Set,Aa=()=>{var g,b,y,L;let c=(y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:y.streamAnimation;return c||((L=r.features)==null?void 0:L.streamAnimation)},Hr=()=>{var lt,ct,Me,Ee;if(!_())return;let c=Ae.peekBanner,g=Ae.peekTextNode;if(!c||!g)return;if(N){c.classList.remove("persona-pill-peek--visible");return}let b=(lt=T==null?void 0:T.getMessages())!=null?lt:[],y;for(let Ue=b.length-1;Ue>=0;Ue--){let M=b[Ue];if(M.role==="assistant"&&M.content){y=M;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let L=y.content,O=!!y.streaming,F=Aa(),q=li(F),B=q.type!=="none"?Zs(q.type,F==null?void 0:F.plugins):null,Ce=((ct=B==null?void 0:B.isAnimating)==null?void 0:ct.call(B,y))===!0,ce=B!==null&&(O||Ce);ce&&B&&!Es.has(B.name)&&(ol(B,e),Es.add(B.name));let te=ce&&(B!=null&&B.containerClass)?B.containerClass:null,be=(Me=g.dataset.personaPeekStreamClass)!=null?Me:null;be&&be!==te&&(g.classList.remove(be),delete g.dataset.personaPeekStreamClass),te&&be!==te&&(g.classList.add(te),g.dataset.personaPeekStreamClass=te),ce?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Se=ce?ci(L,q.buffer,B,y,O):L;if(ce&&q.placeholder==="skeleton"&&O&&(!Se||!Se.trim())){let Ue=document.createElement("div"),M=ta();M.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(M),ri(g,Ue)}else{let Ue=Math.max(0,Se.length-100),M=Se.length>100?Se.slice(-100):Se,Te=Po(M);if(!ce||!B){let Ie=Se.length>100?`\u2026${M}`:M;g.textContent!==Ie&&(g.textContent=Ie)}else{let Ie=Te;(B.wrap==="char"||B.wrap==="word")&&(Ie=ea(Te,B.wrap,`peek-${y.id}`,{skipTags:B.skipTags,startIndex:Ue}));let Ve=document.createElement("div");if(Ve.innerHTML=Ie,B.useCaret&&M.length>0){let ve=di(),Pt=Ve.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=Pt[Pt.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(ve,at.nextSibling):Ve.appendChild(ve)}ri(g,Ve),(Ee=B.onAfterRender)==null||Ee.call(B,{container:g,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Ge=Vn||to;c.classList.toggle("persona-pill-peek--visible",Ge)};if(_()){let c=Ae.peekBanner;if(c){let y=L=>{L.preventDefault(),L.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",y),ht.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{to||(to=!0,Hr())},b=()=>{to&&(to=!1,Hr())};ie.addEventListener("pointerenter",g),ie.addEventListener("pointerleave",b),ht.push(()=>{ie.removeEventListener("pointerenter",g),ie.removeEventListener("pointerleave",b)}),Ye&&(Ye.addEventListener("pointerenter",g),Ye.addEventListener("pointerleave",b),ht.push(()=>{Ye.removeEventListener("pointerenter",g),Ye.removeEventListener("pointerleave",b)}))}let Sa=c=>{var be,Se,Be,nt,Ge,lt,ct,Me;let g=(Se=(be=r.launcher)==null?void 0:be.composerBar)!=null?Se:{},b=(Be=g.expandedSize)!=null?Be:"anchored",y=(nt=g.bottomOffset)!=null?nt:"16px",L=g.collapsedMaxWidth,O=(Ge=g.expandedMaxWidth)!=null?Ge:"880px",F=(lt=g.expandedTopOffset)!=null?lt:"5vh",q=(ct=g.modalMaxWidth)!=null?ct:"880px",B=(Me=g.modalMaxHeight)!=null?Me:"min(90vh, 800px)",Ce="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",te=le.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Ye){let Ee=Ye.style;Ee.bottom=y,Ee.width=L!=null?L:""}if(c&&b!=="fullscreen"){if(b==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=q,te.maxWidth=Ce,te.maxHeight=B,te.height=B;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${y} + ${ce})`,te.top=F,te.width=O,te.maxWidth=Ce}},no=()=>{var B,Ce,ce,te,be,Se,Be,nt;if(!$())return;if(_()){let lt=(ce=((Ce=(B=r.launcher)==null?void 0:B.composerBar)!=null?Ce:{}).expandedSize)!=null?ce:"anchored",ct=N?"expanded":"collapsed";le.dataset.state=ct,le.dataset.expandedSize=lt,Ye&&(Ye.dataset.state=ct,Ye.dataset.expandedSize=lt),le.style.removeProperty("display"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Sa(N),pe.style.display=N?"flex":"none",dr(),N?(wa(),Ca()):(Ss(),Ts()),Hr();return}let c=on(r),g=(te=e.ownerDocument.defaultView)!=null?te:window,b=(Se=(be=r.launcher)==null?void 0:be.mobileBreakpoint)!=null?Se:640,y=(nt=(Be=r.launcher)==null?void 0:Be.mobileFullscreen)!=null?nt:!0,L=g.innerWidth<=b,O=y&&L&&S,F=ir(r).reveal;N?(le.style.removeProperty("display"),le.style.display=c?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-95","persona-opacity-0"),ie.classList.add("persona-scale-100","persona-opacity-100"),Je?Je.element.style.display="none":Ze&&(Ze.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!O?(le.style.removeProperty("display"),le.style.display="flex",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.setProperty("display","none","important"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.display="",le.classList.add("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100"),ie.classList.add("persona-scale-95","persona-opacity-0")),Je?Je.element.style.display=c?"none":"":Ze&&(Ze.style.display=c?"none":""))},Ht=(c,g="user")=>{var O,F;if(!$()||N===c)return;let b=N;N=c,no();let y=(()=>{var Be,nt,Ge,lt,ct,Me,Ee,Ue,M,Te;let q=(nt=(Be=r.launcher)==null?void 0:Be.sidebarMode)!=null?nt:!1,B=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,Ce=(ct=(lt=r.launcher)==null?void 0:lt.mobileFullscreen)!=null?ct:!0,ce=(Ee=(Me=r.launcher)==null?void 0:Me.mobileBreakpoint)!=null?Ee:640,te=B.innerWidth<=ce,be=on(r)&&Ce&&te,Se=_()&&((Te=(M=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:M.expandedSize)!=null?Te:"fullscreen")==="fullscreen";return q||Ce&&te&&S||be||Se})();if(N&&y){if(!Gt){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(Gt=sl(B,(F=(O=r.launcher)==null?void 0:O.zIndex)!=null?F:bn))}Xt||(Xt=al(e.ownerDocument))}else N||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null);N&&(Qt(),Yr(!0));let L={open:N,source:g,timestamp:Date.now()};N&&!b?o.emit("widget:opened",L):!N&&b&&o.emit("widget:closed",L),o.emit("widget:state",{open:N,launcherEnabled:S,voiceActive:gt.active,streaming:T.isStreaming()})},Vo=c=>{Jt(c?"stop":"send"),J&&(J.disabled=c),pr.buttons.forEach(g=>{g.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Ko=()=>{gt.active||X&&X.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Ko(),200)});let Ms=()=>{var b,y,L,O,F,q,B,Ce,ce,te,be;Bn.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",Yn.textContent=(O=(L=r.copy)==null?void 0:L.welcomeSubtitle)!=null?O:"Ask anything about your account or products.",X.placeholder=(q=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?q:"How can I help...";let c=Q.querySelector("[data-persona-intro-card]");if(c){let Se=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;c.style.display=Se?"":"none",Se?(Q.classList.remove("persona-gap-3"),Q.classList.add("persona-gap-6")):(Q.classList.remove("persona-gap-6"),Q.classList.add("persona-gap-3"))}!((ce=(Ce=r.sendButton)==null?void 0:Ce.useIcon)!=null&&ce)&&!(T!=null&&T.isStreaming())&&(Fe.textContent=(be=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?be:"Send"),X.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',X.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Ar=null,Ta=()=>{Ar==null&&(Ar=setInterval(()=>{let c=je.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ar),Ar=null;return}let g=Date.now();c.forEach(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=Na(g-y))})},100))};if(T=new os(r,{onMessagesChanged(c){xo(je,c,We),Ta(),T&&(c.some(L=>L.role==="user")?pr.render([],T,X,c):pr.render(r.suggestionChips,T,X,c,r.suggestionChipsConfig)),Yr(!Vn),va(c);let g=[...c].reverse().find(y=>y.role==="user"),b=gt.lastUserMessageId;g&&g.id!==b&&(gt.lastUserMessageId=g.id,o.emit("user:message",g)),gt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),zo(c),Hr()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};fe(cn,(L=>{var O,F,q,B;return L==="idle"?(O=g.idleText)!=null?O:hn.idle:L==="connecting"?(F=g.connectingText)!=null?F:hn.connecting:L==="connected"?(q=g.connectedText)!=null?q:hn.connected:L==="error"?(B=g.errorText)!=null?B:hn.error:hn[L]})(c),g,c)},onStreamingChanged(c){Vn=c,Vo(c),T&&xo(je,T.getMessages(),We),c||Yr(!0),Hr()},onVoiceStatusChanged(c){var g,b;if(((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":G(),Z();break;case"speaking":G(),ee();break;default:c==="idle"&&T.isBargeInActive()?(G(),k(),J==null||J.setAttribute("aria-label","End voice session")):(gt.active=!1,G(),or("system"),Pn());break}},onArtifactsState(c){_n=c,Un(),zo()}}),It.current=T,((_c=(Fc=r.voiceRecognition)==null?void 0:Fc.provider)==null?void 0:_c.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&T.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||r.onSSEEvent)&&T.setSSEEventCallback((c,g)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,g),ue==null||ue.processEvent(c,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,b,y;c&&(c.metadata&&(d=Pl(c.metadata),E.syncFromMetadata()),(g=c.messages)!=null&&g.length&&T.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&T.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ks=()=>{var g,b,y;!_()||N||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||Ht(!0,"auto")},Ls=c=>{var L;if(c.preventDefault(),T.isStreaming()){T.cancel(),ue==null||ue.reset(),he==null||he.update();return}let g=X.value.trim(),b=(L=tt==null?void 0:tt.hasAttachments())!=null?L:!1;if(!g&&!b)return;ks();let y;b&&(y=[],y.push(...tt.getContentParts()),g&&y.push(qs(g))),X.value="",X.style.height="auto",vo(),T.sendMessage(g,{contentParts:y}),b&&tt.clearAttachments()},Ea=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Jo={...oi},Go=!1,vo=()=>{Jo={...oi}},Ma=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ka=c=>{if(!X)return;Go=!0,X.value=c,X.dispatchEvent(new Event("input",{bubbles:!0})),Go=!1;let g=X.value.length;X.setSelectionRange(g,g)},Ps=()=>{Go||vo()},Is=c=>{if(X){if(Ea()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=X.selectionStart===0&&X.selectionEnd===0,b=Tu({direction:c.key==="ArrowUp"?"up":"down",history:Ma(),currentValue:X.value,atStart:g,state:Jo});if(Jo=b.state,b.handled){c.preventDefault(),b.value!==void 0&&ka(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}vo(),c.preventDefault(),Fe.click()}}},Ws=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(pe)&&(T.cancel(),ue==null||ue.reset(),he==null||he.update(),vo(),c.preventDefault(),c.stopImmediatePropagation())},Rs=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!tt)return;let g=Hh(c.clipboardData);g.length!==0&&(c.preventDefault(),await tt.handleFiles(g))},Cn=null,Kn=!1,Br=null,st=null,Hs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,wo=(c="user")=>{var O,F,q,B,Ce,ce,te;if(Kn||T.isStreaming())return;let g=Hs();if(!g)return;Cn=new g;let y=(F=((O=r.voiceRecognition)!=null?O:{}).pauseDuration)!=null?F:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let L=X.value;Cn.onresult=be=>{let Se="",Be="";for(let Ge=0;Ge<be.results.length;Ge++){let lt=be.results[Ge],ct=lt[0].transcript;lt.isFinal?Se+=ct+" ":Be=ct}let nt=L+Se+Be;X.value=nt,Br&&clearTimeout(Br),(Se||Be)&&(Br=window.setTimeout(()=>{let Ge=X.value.trim();Ge&&Cn&&Kn&&(hr(),X.value="",X.style.height="auto",T.sendMessage(Ge,{viaVoice:!0}))},y))},Cn.onerror=be=>{be.error!=="no-speech"&&hr()},Cn.onend=()=>{if(Kn){let be=X.value.trim();be&&be!==L.trim()&&(X.value="",X.style.height="auto",T.sendMessage(be,{viaVoice:!0})),hr()}};try{if(Cn.start(),Kn=!0,gt.active=!0,c!=="system"&&(gt.manuallyDeactivated=!1),or(c),Pn(),J){let be=(q=r.voiceRecognition)!=null?q:{};st={backgroundColor:J.style.backgroundColor,color:J.style.color,borderColor:J.style.borderColor,iconName:(B=be.iconName)!=null?B:"mic",iconSize:parseFloat((te=(ce=be.iconSize)!=null?ce:(Ce=r.sendButton)==null?void 0:Ce.size)!=null?te:"40")||24};let Se=be.recordingBackgroundColor,Be=be.recordingIconColor,nt=be.recordingBorderColor;if(J.classList.add("persona-voice-recording"),J.style.backgroundColor=Se!=null?Se:"var(--persona-voice-recording-bg, #ef4444)",J.style.color=Be!=null?Be:"var(--persona-voice-recording-indicator, #ffffff)",Be){let Ge=J.querySelector("svg");Ge&&Ge.setAttribute("stroke",Be)}nt&&(J.style.borderColor=nt),J.setAttribute("aria-label","Stop voice recognition")}}catch{hr("system")}},hr=(c="user")=>{if(Kn){if(Kn=!1,Br&&(clearTimeout(Br),Br=null),Cn){try{Cn.stop()}catch{}Cn=null}if(gt.active=!1,or(c),Pn(),J){if(J.classList.remove("persona-voice-recording"),st){J.style.backgroundColor=st.backgroundColor,J.style.color=st.color,J.style.borderColor=st.borderColor;let g=J.querySelector("svg");g&&g.setAttribute("stroke",st.color||"currentColor"),st=null}J.setAttribute("aria-label","Start voice recognition")}}},Xo=(c,g)=>{var lt,ct,Me,Ee,Ue,M,Te,Ie;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((lt=c==null?void 0:c.provider)==null?void 0:lt.type)==="runtype";if(!(b||y))return null;let O=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 q=(ct=c==null?void 0:c.iconName)!=null?ct:"mic",B=(Me=g==null?void 0:g.size)!=null?Me:"40px",Ce=(Ee=c==null?void 0:c.iconSize)!=null?Ee:B,ce=parseFloat(Ce)||24,te=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:g==null?void 0:g.backgroundColor,be=(M=c==null?void 0:c.iconColor)!=null?M:g==null?void 0:g.textColor;F.style.width=Ce,F.style.height=Ce,F.style.minWidth=Ce,F.style.minHeight=Ce,F.style.fontSize="18px",F.style.lineHeight="1",be?F.style.color=be:F.style.color="var(--persona-text, #111827)";let Be=ye(q,ce,be||"currentColor",1.5);Be?F.appendChild(Be):F.textContent="\u{1F3A4}",te?F.style.backgroundColor=te: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),O.appendChild(F);let nt=(Te=c==null?void 0:c.tooltipText)!=null?Te:"Start voice recognition";if(((Ie=c==null?void 0:c.showTooltip)!=null?Ie:!1)&&nt){let Ve=h("div","persona-send-button-tooltip");Ve.textContent=nt,O.appendChild(Ve)}return{micButton:F,micButtonWrapper:O}},qe=()=>{var g,b,y,L,O;if(!J||st)return;let c=(g=r.voiceRecognition)!=null?g:{};st={backgroundColor:J.style.backgroundColor,color:J.style.color,borderColor:J.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((O=(L=c.iconSize)!=null?L:(y=r.sendButton)==null?void 0:y.size)!=null?O:"40")||24}},A=(c,g)=>{var O,F,q,B,Ce;if(!J)return;let b=J.querySelector("svg");b&&b.remove();let y=(Ce=st==null?void 0:st.iconSize)!=null?Ce:parseFloat((B=(q=(O=r.voiceRecognition)==null?void 0:O.iconSize)!=null?q:(F=r.sendButton)==null?void 0:F.size)!=null?B:"40")||24,L=ye(c,y,g,1.5);L&&J.appendChild(L)},j=()=>{J&&J.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},k=()=>{var L;if(!J)return;qe();let c=(L=r.voiceRecognition)!=null?L:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,y=c.recordingBorderColor;if(j(),J.classList.add("persona-voice-recording"),J.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",J.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let O=J.querySelector("svg");O&&O.setAttribute("stroke",b)}y&&(J.style.borderColor=y),J.setAttribute("aria-label","Stop voice recognition")},Z=()=>{var q,B,Ce,ce,te,be,Se,Be;if(!J)return;qe();let c=(q=r.voiceRecognition)!=null?q:{},g=T.getVoiceInterruptionMode(),b=(B=c.processingIconName)!=null?B:"loader",y=(ce=(Ce=c.processingIconColor)!=null?Ce:st==null?void 0:st.color)!=null?ce:"",L=(be=(te=c.processingBackgroundColor)!=null?te:st==null?void 0:st.backgroundColor)!=null?be:"",O=(Be=(Se=c.processingBorderColor)!=null?Se:st==null?void 0:st.borderColor)!=null?Be:"";j(),J.classList.add("persona-voice-processing"),J.style.backgroundColor=L,J.style.borderColor=O;let F=y||"currentColor";J.style.color=F,A(b,F),J.setAttribute("aria-label","Processing voice input"),g==="none"&&(J.style.cursor="default")},ee=()=>{var Ce,ce,te,be,Se,Be,nt,Ge,lt,ct,Me,Ee;if(!J)return;qe();let c=(Ce=r.voiceRecognition)!=null?Ce:{},g=T.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ce=c.speakingIconName)!=null?ce:b,L=(Be=c.speakingIconColor)!=null?Be:g==="barge-in"?(be=(te=c.recordingIconColor)!=null?te:st==null?void 0:st.color)!=null?be:"":(Se=st==null?void 0:st.color)!=null?Se:"",O=(lt=c.speakingBackgroundColor)!=null?lt:g==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(Ge=st==null?void 0:st.backgroundColor)!=null?Ge:"",F=(Ee=c.speakingBorderColor)!=null?Ee:g==="barge-in"?(ct=c.recordingBorderColor)!=null?ct:"":(Me=st==null?void 0:st.borderColor)!=null?Me:"";j(),J.classList.add("persona-voice-speaking"),J.style.backgroundColor=O,J.style.borderColor=F;let q=L||"currentColor";J.style.color=q,A(y,q);let B=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";J.setAttribute("aria-label",B),g==="none"&&(J.style.cursor="default"),g==="barge-in"&&J.classList.add("persona-voice-recording")},G=()=>{var c,g,b;J&&(j(),st&&(J.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",J.style.color=(g=st.color)!=null?g:"",J.style.borderColor=(b=st.borderColor)!=null?b:"",A(st.iconName,st.color||"currentColor"),st=null),J.style.cursor="",J.setAttribute("aria-label","Start voice recognition"))},ze=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=T.getVoiceStatus(),y=T.getVoiceInterruptionMode();if(y==="none"&&(b==="processing"||b==="speaking"))return;if(y==="cancel"&&(b==="processing"||b==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),G()});return}T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),gt.manuallyDeactivated=!T.isVoiceActive(),Pn(),or("user"),T.isVoiceActive()?k():G()});return}if(Kn){let b=X.value.trim();gt.manuallyDeactivated=!0,Pn(),hr("user"),b&&(X.value="",X.style.height="auto",T.sendMessage(b))}else gt.manuallyDeactivated=!1,Pn(),wo("user")};Dn=ze,J&&(J.addEventListener("click",ze),ht.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),G()):hr("system"),J&&J.removeEventListener("click",ze)}));let Ne=o.on("assistant:complete",()=>{ws&&(gt.active||gt.manuallyDeactivated||ws==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!gt.active&&!gt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("auto"),T.isVoiceActive()&&k()}):wo("auto"))},600))});ht.push(Ne);let it=o.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});ht.push(it);let Ke=()=>{Ht(!N,"user")},Je=null,Ze=null;if(S&&!_()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>ra(r,Ke).element,onToggle:Ke});g&&(Ze=g)}Ze||(Je=ra(r,Ke))}Je?e.appendChild(Je.element):Ze&&e.appendChild(Ze),no(),pr.render(r.suggestionChips,T,X,void 0,r.suggestionChipsConfig),Ms(),Vo(T.isStreaming()),Yr(!0),ha(),I&&(!S||_()?setTimeout(()=>Ko(),0):N&&setTimeout(()=>Ko(),200));let Qt=()=>{var B,Ce,ce,te,be,Se,Be,nt,Ge,lt,ct,Me,Ee,Ue,M,Te,Ie,Ve,ve,Pt,at,Yt;if(_()){xt(),no();return}let c=on(r),g=(Ce=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?Ce:!1,b=c||g||((te=(ce=r.launcher)==null?void 0:ce.fullHeight)!=null?te:!1),y=(be=e.ownerDocument.defaultView)!=null?be:window,L=(Be=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Be:!0,O=(Ge=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?Ge:640,F=y.innerWidth<=O,q=L&&F&&S;try{if(q){dr(),so(e,r);return}if(H&&(H=!1,dr(),so(e,r)),!S&&!c){ie.style.height="",ie.style.width="";return}if(!g&&!c){let pn=(ct=(lt=r==null?void 0:r.launcher)==null?void 0:lt.width)!=null?ct:r==null?void 0:r.launcherWidth,Wt=pn!=null?pn:Xn;ie.style.width=Wt,ie.style.maxWidth=Wt}if(wr(),!b){let pn=y.innerHeight,Wt=64,An=(Ee=(Me=r.launcher)==null?void 0:Me.heightOffset)!=null?Ee:0,un=Math.max(200,pn-Wt),et=Math.min(640,un),dt=Math.max(200,et-An);ie.style.height=`${dt}px`}}finally{if(xt(),no(),N&&S){let Wt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((Te=(M=r.launcher)==null?void 0:M.mobileBreakpoint)!=null?Te:640),An=(Ve=(Ie=r.launcher)==null?void 0:Ie.sidebarMode)!=null?Ve:!1,un=(Pt=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Pt:!0,et=on(r)&&un&&Wt,dt=An||un&&Wt&&S||et;if(dt&&!Xt){let Sn=e.getRootNode(),gn=Sn instanceof ShadowRoot?Sn.host:e.closest(".persona-host");gn&&!Gt&&(Gt=sl(gn,(Yt=(at=r.launcher)==null?void 0:at.zIndex)!=null?Yt:bn)),Xt=al(e.ownerDocument)}else dt||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null)}}};Qt();let Et=($c=e.ownerDocument.defaultView)!=null?$c:window;if(Et.addEventListener("resize",Qt),ht.push(()=>Et.removeEventListener("resize",Qt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{xt()});c.observe($e),ht.push(()=>c.disconnect())}gr=Q.scrollTop;let Lt=Q.scrollHeight,sn=()=>{let c=Q.scrollTop,g=Q.scrollHeight,b=g<Lt;Lt=g;let{action:y,nextLastScrollTop:L}=ai({following:mr.isFollowing(),currentScrollTop:c,lastScrollTop:gr,nearBottom:Xs(Q,vs),userScrollThreshold:ga,isAutoScrolling:Ir||bo||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gr=L,y==="resume"){Qr();return}y==="pause"&&As()};Q.addEventListener("scroll",sn,{passive:!0}),ht.push(()=>Q.removeEventListener("scroll",sn));let mn=c=>{let g=ii({following:mr.isFollowing(),deltaY:c.deltaY,nearBottom:Xs(Q,vs),resumeWhenNearBottom:!0});g==="pause"?As():g==="resume"&&Qr()};Q.addEventListener("wheel",mn,{passive:!0}),ht.push(()=>Q.removeEventListener("wheel",mn)),Mt.addEventListener("click",()=>{Q.scrollTop=Q.scrollHeight,gr=Q.scrollTop,Qr(),Yr(!0)}),ht.push(()=>Mt.remove()),ht.push(()=>{Cs()});let dn=()=>{D&&(zn&&(D.removeEventListener("click",zn),zn=null),$()?(D.style.display="",zn=()=>{Ht(!1,"user")},D.addEventListener("click",zn)):D.style.display="none")};dn(),(()=>{let{clearChatButton:c}=Ae;c&&c.addEventListener("click",()=>{T.clearMessages(),ur.clear(),Qr(),mo(Ae.composerOverlay);try{localStorage.removeItem(ys),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ys}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ys)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},E.syncFromMetadata(),K==null||K.clear(),ue==null||ue.reset(),he==null||he.update()})})(),Ot&&Ot.addEventListener("submit",Ls),X==null||X.addEventListener("keydown",Is),X==null||X.addEventListener("input",Ps),X==null||X.addEventListener("paste",Rs);let sr=(jc=e.ownerDocument)!=null?jc:document;sr.addEventListener("keydown",Ws,!0);let Jl="persona-attachment-drop-active",Bs=0,zi=()=>{Bs=0,pe.classList.remove(Jl)},Qo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Gl=c=>{!Bi(c.dataTransfer)||!Qo()||(Bs++,Bs===1&&pe.classList.add(Jl))},Xl=c=>{!Bi(c.dataTransfer)||!Qo()||(Bs--,Bs<=0&&zi())},Ql=c=>{!Bi(c.dataTransfer)||!Qo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Yl=c=>{var b;if(!Bi(c.dataTransfer)||!Qo())return;c.preventDefault(),c.stopPropagation(),zi();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&tt.handleFiles(g)},ro=!0;pe.addEventListener("dragenter",Gl,ro),pe.addEventListener("dragleave",Xl,ro),e.addEventListener("dragover",Ql,ro),e.addEventListener("drop",Yl,ro);let La=e.ownerDocument,Zl=c=>{Qo()&&c.preventDefault()},ec=c=>{Qo()&&c.preventDefault()};La.addEventListener("dragover",Zl),La.addEventListener("drop",ec),ht.push(()=>{Ot&&Ot.removeEventListener("submit",Ls),X==null||X.removeEventListener("keydown",Is),X==null||X.removeEventListener("input",Ps),X==null||X.removeEventListener("paste",Rs),sr.removeEventListener("keydown",Ws,!0)}),ht.push(()=>{pe.removeEventListener("dragenter",Gl,ro),pe.removeEventListener("dragleave",Xl,ro),e.removeEventListener("dragover",Ql,ro),e.removeEventListener("drop",Yl,ro),La.removeEventListener("dragover",Zl),La.removeEventListener("drop",ec),zi()}),ht.push(()=>{T.cancel()}),Je?ht.push(()=>{Je==null||Je.destroy()}):Ze&&ht.push(()=>{Ze==null||Ze.remove()});let nn={update(c){var rn,Sr,Nr,Pa,Ia,Wa,Eo,Ra,Ds,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp;let g=r.toolCall,b=r.messageActions,y=(rn=r.layout)==null?void 0:rn.messages,L=r.colorScheme,O=r.loadingIndicator,F=r.iterationDisplay,q=(Sr=r.features)==null?void 0:Sr.showReasoning,B=(Nr=r.features)==null?void 0:Nr.showToolCalls,Ce=(Pa=r.features)==null?void 0:Pa.toolCallDisplay,ce=(Ia=r.features)==null?void 0:Ia.reasoningDisplay;r={...r,...c},dr(),so(e,r),Ei(e,r),Mi(e,r),Un(),r.colorScheme!==L&&Xr();let te=da.getForInstance(r.plugins);s.length=0,s.push(...te),S=(Eo=(Wa=r.launcher)==null?void 0:Wa.enabled)!=null?Eo:!0,R=(Ds=(Ra=r.launcher)==null?void 0:Ra.autoExpand)!=null?Ds:!1,He=(Xc=(Gc=r.features)==null?void 0:Gc.showReasoning)!=null?Xc:!0,Oe=(Yc=(Qc=r.features)==null?void 0:Qc.showToolCalls)!=null?Yc:!0,we=(ed=(Zc=r.features)==null?void 0:Zc.scrollToBottom)!=null?ed:{},zt(),Rr();let be=de;if(de=(nd=(td=r.features)==null?void 0:td.showEventStreamToggle)!=null?nd:!1,de&&!be){if(K||(re=new la(Pe),K=new ia(Le,re),ue=ue!=null?ue:new ca,re.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),T.setSSEEventCallback((Y,wt)=>{var Ft;(Ft=r.onSSEEvent)==null||Ft.call(r,Y,wt),ue==null||ue.processEvent(Y,wt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(wt)})})),!mt&&_e){let Y=(od=(rd=r.features)==null?void 0:rd.eventStream)==null?void 0:od.classNames,wt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");mt=h("button",wt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Ft=ye("activity","18px","currentColor",1.5);Ft&&mt.appendChild(Ft);let pt=Ae.clearChatButtonWrapper,kt=Ae.closeButtonWrapper,an=pt||kt;an&&an.parentNode===_e?_e.insertBefore(mt,an):_e.appendChild(mt),mt.addEventListener("click",()=>{ge?Nn():xn()})}}else!de&&be&&(Nn(),mt&&(mt.remove(),mt=null),K==null||K.clear(),re==null||re.destroy(),K=null,re=null,ue==null||ue.reset(),ue=null);if(((sd=r.launcher)==null?void 0:sd.enabled)===!1&&Je&&(Je.destroy(),Je=null),((ad=r.launcher)==null?void 0:ad.enabled)===!1&&Ze&&(Ze.remove(),Ze=null),((id=r.launcher)==null?void 0:id.enabled)!==!1&&!Je&&!Ze){let Y=s.find(wt=>wt.renderLauncher);if(Y!=null&&Y.renderLauncher){let wt=Y.renderLauncher({config:r,defaultRenderer:()=>ra(r,Ke).element,onToggle:Ke});wt&&(Ze=wt,e.appendChild(Ze))}Ze||(Je=ra(r,Ke),e.appendChild(Je.element))}Je&&Je.update(r),De&&((ld=r.launcher)==null?void 0:ld.title)!==void 0&&(De.textContent=r.launcher.title),Qe&&((cd=r.launcher)==null?void 0:cd.subtitle)!==void 0&&(Qe.textContent=r.launcher.subtitle);let Se=(dd=r.layout)==null?void 0:dd.header;if((Se==null?void 0:Se.layout)!==w&&_e){let Y=Se?ls(r,Se,{showClose:$(),onClose:()=>Ht(!1,"user")}):_r({config:r,showClose:$(),onClose:()=>Ht(!1,"user")});_e.replaceWith(Y.header),_e=Y.header,se=Y.iconHolder,De=Y.headerTitle,Qe=Y.headerSubtitle,D=Y.closeButton,w=Se==null?void 0:Se.layout}else if(Se&&(se&&(se.style.display=Se.showIcon===!1?"none":""),De&&(De.style.display=Se.showTitle===!1?"none":""),Qe&&(Qe.style.display=Se.showSubtitle===!1?"none":""),D&&(D.style.display=Se.showCloseButton===!1?"none":""),Ae.clearChatButtonWrapper)){let Y=Se.showClearChat;if(Y!==void 0){Ae.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:wt}=Ae;wt&&!wt.classList.contains("persona-absolute")&&(Y?wt.classList.remove("persona-ml-auto"):wt.classList.add("persona-ml-auto"))}}let nt=((pd=r.layout)==null?void 0:pd.showHeader)!==!1;_e&&(_e.style.display=nt?"":"none");let Ge=((ud=r.layout)==null?void 0:ud.showFooter)!==!1;$e&&($e.style.display=Ge?"":"none"),xt(),Rr(),S!==P?S?Ht(R,"auto"):(N=!0,no()):R!==W&&Ht(R,"auto"),W=R,P=S,Qt(),dn();let Me=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ee=JSON.stringify(r.messageActions)!==JSON.stringify(b),Ue=JSON.stringify((md=r.layout)==null?void 0:md.messages)!==JSON.stringify(y),M=((gd=r.loadingIndicator)==null?void 0:gd.render)!==(O==null?void 0:O.render)||((fd=r.loadingIndicator)==null?void 0:fd.renderIdle)!==(O==null?void 0:O.renderIdle)||((hd=r.loadingIndicator)==null?void 0:hd.showBubble)!==(O==null?void 0:O.showBubble),Te=r.iterationDisplay!==F,Ie=((yd=(bd=r.features)==null?void 0:bd.showReasoning)!=null?yd:!0)!==(q!=null?q:!0)||((vd=(xd=r.features)==null?void 0:xd.showToolCalls)!=null?vd:!0)!==(B!=null?B:!0)||JSON.stringify((wd=r.features)==null?void 0:wd.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Cd=r.features)==null?void 0:Cd.reasoningDisplay)!==JSON.stringify(ce);(Me||Ee||Ue||M||Te||Ie)&&T&&(xs++,xo(je,T.getMessages(),We));let ve=(Ad=r.launcher)!=null?Ad:{},Pt=(Sd=ve.headerIconHidden)!=null?Sd:!1,at=(Ed=(Td=r.layout)==null?void 0:Td.header)==null?void 0:Ed.showIcon,Yt=Pt||at===!1,pn=ve.headerIconName,Wt=(Md=ve.headerIconSize)!=null?Md:"48px";if(se){let Y=pe.querySelector(".persona-border-b-persona-divider"),wt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(Yt)se.style.display="none",Y&&wt&&!Y.contains(wt)&&Y.insertBefore(wt,Y.firstChild);else{if(se.style.display="",se.style.height=Wt,se.style.width=Wt,Y&&wt&&(Y.contains(se)?se.nextSibling!==wt&&(se.remove(),Y.insertBefore(se,wt)):Y.insertBefore(se,wt)),pn){let pt=parseFloat(Wt)||24,kt=ye(pn,pt*.6,"#ffffff",2);kt?se.replaceChildren(kt):se.textContent=(kd=ve.agentIconText)!=null?kd:"\u{1F4AC}"}else if(ve.iconUrl){let pt=se.querySelector("img");if(pt)pt.src=ve.iconUrl,pt.style.height=Wt,pt.style.width=Wt;else{let kt=document.createElement("img");kt.src=ve.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Wt,kt.style.width=Wt,se.replaceChildren(kt)}}else{let pt=se.querySelector("svg"),kt=se.querySelector("img");(pt||kt)&&se.replaceChildren(),se.textContent=(Ld=ve.agentIconText)!=null?Ld:"\u{1F4AC}"}let Ft=se.querySelector("img");Ft&&(Ft.style.height=Wt,Ft.style.width=Wt)}}let An=(Id=(Pd=r.layout)==null?void 0:Pd.header)==null?void 0:Id.showTitle,un=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showSubtitle;if(De&&(De.style.display=An===!1?"none":""),Qe&&(Qe.style.display=un===!1?"none":""),D){((Bd=(Hd=r.layout)==null?void 0:Hd.header)==null?void 0:Bd.showCloseButton)===!1?D.style.display="none":D.style.display="";let wt=(Dd=ve.closeButtonSize)!=null?Dd:"32px",Ft=(Nd=ve.closeButtonPlacement)!=null?Nd:"inline";D.style.height=wt,D.style.width=wt;let{closeButtonWrapper:pt}=Ae,kt=Ft==="top-right",an=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&kt!==an)if(pt.remove(),kt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(pt);else{let ut=(Fd=(Od=ve.clearChat)==null?void 0:Od.placement)!=null?Fd:"inline",ln=($d=(_d=ve.clearChat)==null?void 0:_d.enabled)!=null?$d:!0;pt.className=ln&&ut==="inline"?"":"persona-ml-auto";let Hn=pe.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(pt)}if(D.style.color=ve.closeButtonColor||Mn.actionIconColor,ve.closeButtonBackgroundColor?(D.style.backgroundColor=ve.closeButtonBackgroundColor,D.classList.remove("hover:persona-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ut=ve.closeButtonBorderWidth||"0px",ln=ve.closeButtonBorderColor||"transparent";D.style.border=`${ut} solid ${ln}`,D.classList.remove("persona-border-none")}else D.style.border="",D.classList.add("persona-border-none");ve.closeButtonBorderRadius?(D.style.borderRadius=ve.closeButtonBorderRadius,D.classList.remove("persona-rounded-full")):(D.style.borderRadius="",D.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(D.style.paddingLeft=ve.closeButtonPaddingX,D.style.paddingRight=ve.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ve.closeButtonPaddingY?(D.style.paddingTop=ve.closeButtonPaddingY,D.style.paddingBottom=ve.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let fn=(jd=ve.closeButtonIconName)!=null?jd:"x",br=(Ud=ve.closeButtonIconText)!=null?Ud:"\xD7";D.innerHTML="";let En=ye(fn,"28px","currentColor",1);En?D.appendChild(En):D.textContent=br;let Zt=(qd=ve.closeButtonTooltipText)!=null?qd:"Close chat",Gn=(zd=ve.closeButtonShowTooltip)!=null?zd:!0;if(D.setAttribute("aria-label",Zt),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!D)return;let Mo=D.ownerDocument,Ns=Mo.body;if(!Ns)return;ut=Tr(Mo,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Os=Tr(Mo,"div");Os.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Os);let ko=D.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(ao),ut.style.left=`${ko.left+ko.width/2}px`,ut.style.top=`${ko.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};pt.addEventListener("mouseenter",ln),pt.addEventListener("mouseleave",Hn),D.addEventListener("focus",ln),D.addEventListener("blur",Hn),pt._cleanupTooltip=()=>{Hn(),pt&&(pt.removeEventListener("mouseenter",ln),pt.removeEventListener("mouseleave",Hn)),D&&(D.removeEventListener("focus",ln),D.removeEventListener("blur",Hn))}}}let{clearChatButton:et,clearChatButtonWrapper:dt}=Ae;if(et){let Y=(Vd=ve.clearChat)!=null?Vd:{},wt=(Kd=Y.enabled)!=null?Kd:!0,Ft=(Gd=(Jd=r.layout)==null?void 0:Jd.header)==null?void 0:Gd.showClearChat,pt=Ft!==void 0?Ft:wt,kt=(Xd=Y.placement)!=null?Xd:"inline";if(dt){dt.style.display=pt?"":"none";let{closeButtonWrapper:an}=Ae;!_()&&an&&!an.classList.contains("persona-absolute")&&(pt?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let fn=kt==="top-right",br=dt.classList.contains("persona-absolute");if(!_()&&fn!==br&&pt){if(dt.remove(),fn)dt.className="persona-absolute persona-top-4 persona-z-50",dt.style.right="48px",pe.style.position="relative",pe.appendChild(dt);else{dt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",dt.style.right="";let Zt=pe.querySelector(".persona-border-b-persona-divider"),Gn=Ae.closeButtonWrapper;Zt&&Gn&&Gn.parentElement===Zt?Zt.insertBefore(dt,Gn):Zt&&Zt.appendChild(dt)}let En=Ae.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(fn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(pt){if(!_()){let ut=(Qd=Y.size)!=null?Qd:"32px";et.style.height=ut,et.style.width=ut}let an=(Yd=Y.iconName)!=null?Yd:"refresh-cw",fn=(Zd=Y.iconColor)!=null?Zd:"";et.style.color=fn||Mn.actionIconColor,et.innerHTML="";let br=_()?"14px":"20px",En=ye(an,br,"currentColor",2);if(En&&et.appendChild(En),Y.backgroundColor?(et.style.backgroundColor=Y.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let ut=Y.borderWidth||"0px",ln=Y.borderColor||"transparent";et.style.border=`${ut} solid ${ln}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");Y.borderRadius?(et.style.borderRadius=Y.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),Y.paddingX?(et.style.paddingLeft=Y.paddingX,et.style.paddingRight=Y.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),Y.paddingY?(et.style.paddingTop=Y.paddingY,et.style.paddingBottom=Y.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let Zt=(ep=Y.tooltipText)!=null?ep:"Clear chat",Gn=(tp=Y.showTooltip)!=null?tp:!0;if(et.setAttribute("aria-label",Zt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!et)return;let Mo=et.ownerDocument,Ns=Mo.body;if(!Ns)return;ut=Tr(Mo,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Os=Tr(Mo,"div");Os.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Os);let ko=et.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(ao),ut.style.left=`${ko.left+ko.width/2}px`,ut.style.top=`${ko.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",ln),dt.addEventListener("mouseleave",Hn),et.addEventListener("focus",ln),et.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",ln),dt.removeEventListener("mouseleave",Hn)),et&&(et.removeEventListener("focus",ln),et.removeEventListener("blur",Hn))}}}}let Sn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],gn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[$o.message,$o.messageAndClick];E=ua({parsers:Sn,handlers:gn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),We=Tm(r,E,oe),T.updateConfig(r),xo(je,T.getMessages(),We),pr.render(r.suggestionChips,T,X,void 0,r.suggestionChipsConfig),Ms(),Vo(T.isStreaming());let Co=((np=r.voiceRecognition)==null?void 0:np.enabled)===!0,Ao=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),So=((op=(rp=r.voiceRecognition)==null?void 0:rp.provider)==null?void 0:op.type)==="runtype";if(Co&&(Ao||So))if(!J||!ft){let Y=Xo(r.voiceRecognition,r.sendButton);Y&&(J=Y.micButton,ft=Y.micButtonWrapper,$t.insertBefore(ft,kn),J.addEventListener("click",ze),J.disabled=T.isStreaming())}else{let Y=(sp=r.voiceRecognition)!=null?sp:{},wt=(ap=r.sendButton)!=null?ap:{},Ft=(ip=Y.iconName)!=null?ip:"mic",pt=(lp=wt.size)!=null?lp:"40px",kt=(cp=Y.iconSize)!=null?cp:pt,an=parseFloat(kt)||24;J.style.width=kt,J.style.height=kt,J.style.minWidth=kt,J.style.minHeight=kt;let fn=(pp=(dp=Y.iconColor)!=null?dp:wt.textColor)!=null?pp:"currentColor";J.innerHTML="";let br=ye(Ft,an,fn,2);br?J.appendChild(br):J.textContent="\u{1F3A4}";let En=(up=Y.backgroundColor)!=null?up:wt.backgroundColor;En?J.style.backgroundColor=En:J.style.backgroundColor="",fn?J.style.color=fn:J.style.color="var(--persona-text, #111827)",Y.borderWidth?(J.style.borderWidth=Y.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),Y.borderColor?J.style.borderColor=Y.borderColor:J.style.borderColor="",Y.paddingX?(J.style.paddingLeft=Y.paddingX,J.style.paddingRight=Y.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),Y.paddingY?(J.style.paddingTop=Y.paddingY,J.style.paddingBottom=Y.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Zt=ft==null?void 0:ft.querySelector(".persona-send-button-tooltip"),Gn=(mp=Y.tooltipText)!=null?mp:"Start voice recognition";if(((gp=Y.showTooltip)!=null?gp:!1)&&Gn)if(Zt)Zt.textContent=Gn,Zt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Gn,ft==null||ft.insertBefore(ln,J)}else Zt&&(Zt.style.display="none");ft.style.display="",J.disabled=T.isStreaming()}else J&&ft&&(ft.style.display="none",((hp=(fp=r.voiceRecognition)==null?void 0:fp.provider)==null?void 0:hp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Kn&&hr());if(((bp=r.attachments)==null?void 0:bp.enabled)===!0)if(!qt||!rt){let Y=(yp=r.attachments)!=null?yp:{},Ft=(vp=((xp=r.sendButton)!=null?xp:{}).size)!=null?vp:"40px";xe||(xe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xe.style.display="none",Ot.insertBefore(xe,X)),ae||(ae=document.createElement("input"),ae.type="file",ae.accept=((wp=Y.allowedTypes)!=null?wp:Fr).join(","),ae.multiple=((Cp=Y.maxFiles)!=null?Cp:4)>1,ae.style.display="none",ae.setAttribute("aria-label","Attach files"),Ot.insertBefore(ae,X)),qt=h("div","persona-send-button-wrapper"),rt=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),rt.type="button",rt.setAttribute("aria-label",(Ap=Y.buttonTooltipText)!=null?Ap:"Attach file");let pt=(Sp=Y.buttonIconName)!=null?Sp:"paperclip",kt=Ft,an=parseFloat(kt)||40,fn=Math.round(an*.6);rt.style.width=kt,rt.style.height=kt,rt.style.minWidth=kt,rt.style.minHeight=kt,rt.style.fontSize="18px",rt.style.lineHeight="1",rt.style.backgroundColor="transparent",rt.style.color="var(--persona-primary, #111827)",rt.style.border="none",rt.style.borderRadius="6px",rt.style.transition="background-color 0.15s ease",rt.addEventListener("mouseenter",()=>{rt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),rt.addEventListener("mouseleave",()=>{rt.style.backgroundColor="transparent"});let br=ye(pt,fn,"currentColor",1.5);br?rt.appendChild(br):rt.textContent="\u{1F4CE}",rt.addEventListener("click",Gn=>{Gn.preventDefault(),ae==null||ae.click()}),qt.appendChild(rt);let En=(Tp=Y.buttonTooltipText)!=null?Tp:"Attach file",Zt=h("div","persona-send-button-tooltip");Zt.textContent=En,qt.appendChild(Zt),St.append(qt),!tt&&ae&&xe&&(tt=Do.fromConfig(Y),tt.setPreviewsContainer(xe),ae.addEventListener("change",async()=>{tt&&(ae!=null&&ae.files)&&(await tt.handleFileSelect(ae.files),ae.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(Em(Y.dropOverlay))}else{qt.style.display="";let Y=(Ep=r.attachments)!=null?Ep:{};ae&&(ae.accept=((Mp=Y.allowedTypes)!=null?Mp:Fr).join(","),ae.multiple=((kp=Y.maxFiles)!=null?kp:4)>1),tt&&tt.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else qt&&(qt.style.display="none"),tt&&tt.clearAttachments(),(Lp=pe.querySelector(".persona-attachment-drop-overlay"))==null||Lp.remove();let Vt=(Pp=r.sendButton)!=null?Pp:{},To=(Ip=Vt.useIcon)!=null?Ip:!1,oo=(Wp=Vt.iconText)!=null?Wp:"\u2191",yt=Vt.iconName,In=(Rp=Vt.tooltipText)!=null?Rp:"Send message",Dr=(Hp=Vt.showTooltip)!=null?Hp:!1,Tn=(Bp=Vt.size)!=null?Bp:"40px",Wn=Vt.backgroundColor,Bt=Vt.textColor;if(To){if(Fe.style.width=Tn,Fe.style.height=Tn,Fe.style.minWidth=Tn,Fe.style.minHeight=Tn,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.innerHTML="",Bt?Fe.style.color=Bt:Fe.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Y=parseFloat(Tn)||24,wt=(Bt==null?void 0:Bt.trim())||"currentColor",Ft=ye(yt,Y,wt,2);Ft?Fe.appendChild(Ft):Fe.textContent=oo}else Fe.textContent=oo;Fe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-primary")):(Fe.style.backgroundColor="",Fe.classList.add("persona-bg-persona-primary"))}else Fe.textContent=(Np=(Dp=r.copy)==null?void 0:Dp.sendButtonLabel)!=null?Np:"Send",Fe.style.width="",Fe.style.height="",Fe.style.minWidth="",Fe.style.minHeight="",Fe.style.fontSize="",Fe.style.lineHeight="",Fe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-accent")):Fe.classList.add("persona-bg-persona-accent"),Bt?Fe.style.color=Bt:Fe.classList.add("persona-text-white");Vt.borderWidth?(Fe.style.borderWidth=Vt.borderWidth,Fe.style.borderStyle="solid"):(Fe.style.borderWidth="",Fe.style.borderStyle=""),Vt.borderColor?Fe.style.borderColor=Vt.borderColor:Fe.style.borderColor="",Vt.paddingX?(Fe.style.paddingLeft=Vt.paddingX,Fe.style.paddingRight=Vt.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),Vt.paddingY?(Fe.style.paddingTop=Vt.paddingY,Fe.style.paddingBottom=Vt.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Ut=kn==null?void 0:kn.querySelector(".persona-send-button-tooltip");if(Dr&&In)if(Ut)Ut.textContent=In,Ut.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=In,kn==null||kn.insertBefore(Y,Fe)}else Ut&&(Ut.style.display="none");let Dt=(jp=(Op=r.layout)==null?void 0:Op.contentMaxWidth)!=null?jp:_()?($p=(_p=(Fp=r.launcher)==null?void 0:Fp.composerBar)==null?void 0:_p.contentMaxWidth)!=null?$p:"720px":void 0;Dt?(je.style.maxWidth=Dt,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%",Ot&&(Ot.style.maxWidth=Dt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),At&&(At.style.maxWidth=Dt,At.style.marginLeft="auto",At.style.marginRight="auto")):(je.style.maxWidth="",je.style.marginLeft="",je.style.marginRight="",je.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),At&&(At.style.maxWidth="",At.style.marginLeft="",At.style.marginRight=""));let Kt=(Up=r.statusIndicator)!=null?Up:{},Rn=(qp=Kt.visible)!=null?qp:!0;if(cn.style.display=Rn?"":"none",T){let Y=T.getStatus();fe(cn,(Ft=>{var pt,kt,an,fn;return Ft==="idle"?(pt=Kt.idleText)!=null?pt:hn.idle:Ft==="connecting"?(kt=Kt.connectingText)!=null?kt:hn.connecting:Ft==="connected"?(an=Kt.connectedText)!=null?an:hn.connected:Ft==="error"?(fn=Kt.errorText)!=null?fn:hn.error:hn[Ft]})(Y),Kt,Y)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Jn=Kt.align==="left"?"persona-text-left":Kt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Jn)},open(){$()&&Ht(!0,"api")},close(){$()&&Ht(!1,"api")},toggle(){$()&&Ht(!N,"api")},clearChat(){vn=!1,T.clearMessages(),ur.clear(),Qr();try{localStorage.removeItem(ys),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ys}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ys)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},E.syncFromMetadata(),K==null||K.clear(),ue==null||ue.reset(),he==null||he.update()},setMessage(c){return!X||T.isStreaming()?!1:(!N&&$()&&Ht(!0,"system"),X.value=c,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let g=(c==null?void 0:c.trim())||X.value.trim();return g?(!N&&$()&&Ht(!0,"system"),X.value="",X.style.height="auto",T.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return T.isStreaming()?!1:((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(T.isVoiceActive()||(!N&&$()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("user"),T.isVoiceActive()&&k()})),!0):Kn?!0:Hs()?(!N&&$()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),wo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),G()}),!0):!1:Kn?(gt.manuallyDeactivated=!0,Pn(),hr("user"),!0):!1},injectMessage(c){return!N&&$()&&Ht(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!N&&$()&&Ht(!0,"system");let g=T.injectAssistantMessage(c);return U&&(U=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),g},injectUserMessage(c){return!N&&$()&&Ht(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!N&&$()&&Ht(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!N&&$()&&Ht(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!N&&$()&&Ht(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!N&&$()&&Ht(!0,"system"),T.injectTestEvent(c)},async connectStream(c,g){return T.connectStream(c,g)},__pushEventStreamEvent(c){K&&(ue==null||ue.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!de||!K||xn()},hideEventStream(){ge&&Nn()},isEventStreamVisible(){return ge},showArtifacts(){cr(r)&&(vn=!1,Un(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(vn=!0,Un())},upsertArtifact(c){return cr(r)?(vn=!1,T.upsertArtifact(c)):null},selectArtifact(c){cr(r)&&T.selectArtifact(c)},clearArtifacts(){cr(r)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return S&&!N&&!_()||!X?!1:(X.focus(),!0)},async resolveApproval(c,g){let y=T.getMessages().find(L=>{var O;return L.variant==="approval"&&((O=L.approval)==null?void 0:O.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){T.resolveWebMcpApproval(y.id,g);return}return T.resolveApproval(y.approval,g)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return $()&&N},isVoiceActive(){return gt.active},getState(){return{open:$()&&N,launcherEnabled:S,voiceActive:gt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!N&&$()&&Ht(!0,"system");let g=je.querySelector(".persona-feedback-container");g&&g.remove();let b=Ri({onSubmit:async(y,L)=>{var O;T.isClientTokenMode()&&await T.submitCSATFeedback(y,L),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});je.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!N&&$()&&Ht(!0,"system");let g=je.querySelector(".persona-feedback-container");g&&g.remove();let b=Hi({onSubmit:async(y,L)=>{var O;T.isClientTokenMode()&&await T.submitNPSFeedback(y,L),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});je.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return T.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return T.submitNPSFeedback(c,g)},destroy(){Ar!=null&&(clearInterval(Ar),Ar=null),ht.forEach(c=>c()),le.remove(),Ye==null||Ye.remove(),Je==null||Je.destroy(),Ze==null||Ze.remove(),zn&&D.removeEventListener("click",zn)}};if((((Uc=t==null?void 0:t.debugTools)!=null?Uc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:nn,getMessages:nn.getMessages,getStatus:nn.getStatus,getMetadata:nn.getPersistentMetadata,updateMetadata:nn.updatePersistentMetadata,clearHistory:()=>nn.clearChat(),setVoiceActive:b=>b?nn.startVoiceRecognition():nn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ht.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",g),ht.push(()=>{window.removeEventListener("persona:focusInput",g)}),de){let q=Ce=>{let ce=Ce.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&nn.showEventStream()},B=Ce=>{let ce=Ce.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),ht.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let b=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&nn.showArtifacts()},y=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&nn.hideArtifacts()},L=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||B!=null&&B.artifact&&nn.upsertArtifact(B.artifact)},O=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||typeof(B==null?void 0:B.id)=="string"&&nn.selectArtifact(B.id)},F=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",O),window.addEventListener("persona:clearArtifacts",F),ht.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",O),window.removeEventListener("persona:clearArtifacts",F)})}let ar=Bh(r.persistState);if(ar&&$()){let c=Dh(ar.storage),g=`${ar.keyPrefix}widget-open`,b=`${ar.keyPrefix}widget-voice`,y=`${ar.keyPrefix}widget-voice-mode`;if(c){let L=((qc=ar.persist)==null?void 0:qc.openState)&&c.getItem(g)==="true",O=((zc=ar.persist)==null?void 0:zc.voiceState)&&c.getItem(b)==="true",F=((Vc=ar.persist)==null?void 0:Vc.voiceState)&&c.getItem(y)==="true";if(L&&setTimeout(()=>{nn.open(),setTimeout(()=>{var q;if(O||F)nn.startVoiceRecognition();else if((q=ar.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(Kc=ar.persist)!=null&&Kc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(Jc=ar.persist)!=null&&Jc.voiceState&&(o.on("voice:state",q=>{c.setItem(b,q.active?"true":"false")}),o.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),ar.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},B=()=>q();window.addEventListener("persona:clear-chat",B),ht.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return u&&$()&&setTimeout(()=>{nn.open()},0),Hr(),nn};var Nh=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},Mm=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Hl=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=""},km=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Hl(e)},Il=e=>{e.style.transition=""},Wl=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=""},Rl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ni=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Oh=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Fh=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Lm=(e,n,t,r,s,o,a)=>{var x,v,E,S,R,I;let i=ir(o),d=i.reveal==="push";Oh(e,n,t,r,d),Fh(e,n,t,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(v=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,p=(S=(E=o==null?void 0:o.launcher)==null?void 0:E.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"),Wl(n),Il(r),km(r),Rl(t),Ni(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((I=(R=o==null?void 0:o.launcher)==null?void 0:R.zIndex)!=null?I:bn),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"),km(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Wl(n),Il(r),Rl(t),Ni(s,r);let W=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=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=W,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Il(r),Hl(r),Ni(s,r);let W=Nh(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",H=i.side==="right"?a?`translateX(-${W}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${W}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+W}px`,n.style.transition=w,n.style.transform=H,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="",Wl(n),Hl(r),Rl(t),Ni(s,r);let W=i.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",H=!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=W||H?"hidden":"visible",r.style.transition=w,W&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},_h=(e,n)=>{let t=e.ownerDocument.createElement("div");return Mm(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Mm(t,r)},destroy(){t.remove()}}},$h=(e,n)=>{var R,I,W,P;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(I=(R=n==null?void 0:n.launcher)==null?void 0:R.enabled)==null||I?(P=(W=n==null?void 0:n.launcher)==null?void 0:W.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,m=()=>{f==null||f.disconnect(),f=null},x=()=>{m(),ir(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Lm(a,i,d,l,u,n,p)}),f.observe(a))},v=()=>{Lm(a,i,d,l,u,n,p),x()},E=a.ownerDocument.defaultView,S=()=>{v()};return E==null||E.addEventListener("resize",S),ir(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:u,shell:a,syncWidgetState(w){let H=w.launcherEnabled?w.open:!0;p!==H&&(p=H,v())},updateConfig(w){var H,_;n=w,((_=(H=n==null?void 0:n.launcher)==null?void 0:H.enabled)!=null?_:!0)===!1&&(p=!0),v()},destroy(){E==null||E.removeEventListener("resize",S),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ma=(e,n)=>on(n)?$h(e,n):_h(e,n);var Bl={},jh=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},Uh=()=>{try{if(typeof Bl!="undefined"&&Bl.url)return new URL("../widget.css",Bl.url).href}catch{}return null},Pm=(e,n)=>{let t=Uh(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},Dl=e=>{var E;let n=jh(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=ma(n,s),a,i=[],d=(S,R)=>{var w,H;let W=!((H=(w=R==null?void 0:R.launcher)==null?void 0:w.enabled)!=null?H:!0)||on(R),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),W&&(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),Pm(_,r)}else S.appendChild(P),Pm(S,r);return n.id&&P.setAttribute("data-persona-instance",n.id),P},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let S=d(o.host,s);a=Di(S,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=S=>{f(),o.destroy(),o=ma(n,S),s=S,p()},x={update(S){var H,_,$,N,U,z;let R={...s,...S,launcher:{...(H=s==null?void 0:s.launcher)!=null?H:{},...(_=S==null?void 0:S.launcher)!=null?_:{},dock:{...(N=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?N:{},...(z=(U=S==null?void 0:S.launcher)==null?void 0:U.dock)!=null?z:{}}}},I=on(s),W=on(R),P=lo(s),w=lo(R);if(I!==W||P!==w){m(R);return}s=R,o.updateConfig(s),a.update(S),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(x,{get(S,R,I){if(R==="host")return o.host;if(R in S)return Reflect.get(S,R,I);let W=a[R];return typeof W=="function"?W.bind(a):W}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Bm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),qh=new Set(["button","a","input","select","textarea","details","summary"]),zh=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Nl=/\b(product|card|item|listing|result)\b/i,Fl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vh=3e3,Kh=100;function Dm(e){let n=typeof e.className=="string"?e.className:"";if(Nl.test(n)||e.id&&Nl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Nl.test(r.value))return!0}return!1}function Nm(e){var n;return Fl.test(((n=e.textContent)!=null?n:"").trim())}function Om(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Jh(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Im(e){let n=e.match(Fl);return n?n[0]:null}function Wm(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Gh(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var Xh="commerce-card",Qh="result-card";function Rm(e){return!Dm(e)||!Nm(e)||!Om(e)&&!Jh(e)?0:5200}function Hm(e){var r;return!Dm(e)||Nm(e)||!Om(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var _l=[{id:Xh,scoreElement(e){return Rm(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||Fl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(Rm(e)===0)return null;let{title:t,href:r}=Wm(e),s=(u=(l=Im(((d=e.textContent)!=null?d:"").trim()))!=null?l:Im(n.text))!=null?u:"",o=Gh(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
+ `)}},{id:Qh,scoreElement(e){return Hm(e)},formatSummary(e,n){if(Hm(e)===0)return null;let{title:t,href:r}=Wm(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
109
+ `)}}];function Yh(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Zh(e){var u,p,f,m,x,v,E,S,R,I,W,P,w;let n=(u=e.options)!=null?u:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(x=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",s=(E=(v=n.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,o=(R=(S=n.visibleOnly)!=null?S:e.visibleOnly)!=null?R:!0,a=(I=n.root)!=null?I:e.root,i=(W=n.mode)!=null?W:"structured",d=(P=n.maxCandidates)!=null?P:Math.max(500,t*10),l=(w=e.rules)!=null?w:_l;return i==="simple"&&e.rules&&e.rules.length>0?(Yh(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function Ol(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var eb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function tb(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"||qh.has(n)||t&&zh.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Fm(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 nb(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(n[u.name]=u.value)}return n}function $l(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${Ol(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of eb){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${Ol(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>Ol(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function rb(e){return e==="static"?Kh:Vh}function _m(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:$l(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:tb(e),attributes:nb(e)}}function ob(e,n,t,r){let s=rb(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function sb(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 ab(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Bm.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Fm(l)){i=a.nextNode();continue}let p=_m(l,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(E=>E==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:x,formattingRule:v}=ob(l,p,e.rules,t);s.push({el:l,domIndex:o,enriched:p,score:x,formattingRule:v}),o+=1}i=a.nextNode()}s.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;sb(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,t);m&&(u=m)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function ib(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(Bm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Fm(d)){o=s.nextNode();continue}let u=_m(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function $m(e={}){var r;let n=Zh(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?ib(n,t):ab(n,t):[]}var Oi=100;function jm(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
110
110
  ${a.map(i=>`- ${i.split(`
111
111
  `).join(`
112
112
  `)}`).join(`
113
- `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Oi)}" (clickable)`);r.push(`Interactive elements:
113
+ `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Oi)}" (clickable)`);r.push(`Interactive elements:
114
114
  ${a.join(`
115
115
  `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Oi)}" (navigable)`);r.push(`Navigation links:
116
116
  ${a.join(`
@@ -120,7 +120,7 @@ ${a.join(`
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
123
- `)}var $m={name:"@runtypelabs/persona",version:"3.23.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var jo=$m.version;function qr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function ay(e){if(e)return{getHeaders:qr(e.getHeaders),onFeedback:qr(e.onFeedback),onCopy:qr(e.onCopy),requestMiddleware:qr(e.requestMiddleware),actionHandlers:qr(e.actionHandlers),actionParsers:qr(e.actionParsers),postprocessMessage:qr(e.postprocessMessage),contextProviders:qr(e.contextProviders),streamParser:qr(e.streamParser)}}var jm=`({ text, message }: any) => {
123
+ `)}var Um={name:"@runtypelabs/persona",version:"3.24.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var jo=Um.version;function qr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function cb(e){if(e)return{getHeaders:qr(e.getHeaders),onFeedback:qr(e.onFeedback),onCopy:qr(e.onCopy),requestMiddleware:qr(e.requestMiddleware),actionHandlers:qr(e.actionHandlers),actionParsers:qr(e.actionParsers),postprocessMessage:qr(e.postprocessMessage),contextProviders:qr(e.contextProviders),streamParser:qr(e.streamParser)}}var qm=`({ text, message }: any) => {
124
124
  const jsonSource = (message as any).rawContent || text || message.content;
125
125
  if (!jsonSource || typeof jsonSource !== 'string') return null;
126
126
  let cleanJson = jsonSource
@@ -133,7 +133,7 @@ ${a.join(`
133
133
  if (parsed.action) return { type: parsed.action, payload: parsed };
134
134
  } catch (e) { return null; }
135
135
  return null;
136
- }`,Um=`function(ctx) {
136
+ }`,zm=`function(ctx) {
137
137
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
138
138
  if (!jsonSource || typeof jsonSource !== 'string') return null;
139
139
  var cleanJson = jsonSource
@@ -146,7 +146,7 @@ ${a.join(`
146
146
  if (parsed.action) return { type: parsed.action, payload: parsed };
147
147
  } catch (e) { return null; }
148
148
  return null;
149
- }`,qm=`(action: any, context: any) => {
149
+ }`,Vm=`(action: any, context: any) => {
150
150
  if (action.type !== 'nav_then_click') return;
151
151
  const payload = action.payload || action.raw || {};
152
152
  const url = payload?.page;
@@ -163,7 +163,7 @@ ${a.join(`
163
163
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
164
164
  window.location.href = targetUrl;
165
165
  return { handled: true, displayText: text };
166
- }`,zm=`function(action, context) {
166
+ }`,Km=`function(action, context) {
167
167
  if (action.type !== 'nav_then_click') return;
168
168
  var payload = action.payload || action.raw || {};
169
169
  var url = payload.page;
@@ -180,26 +180,26 @@ ${a.join(`
180
180
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
181
181
  window.location.href = targetUrl;
182
182
  return { handled: true, displayText: text };
183
- }`,iy=`(parsed: any) => {
183
+ }`,db=`(parsed: any) => {
184
184
  if (!parsed || typeof parsed !== 'object') return null;
185
185
  if (parsed.action === 'nav_then_click') return 'Navigating...';
186
186
  if (parsed.action === 'message') return parsed.text || '';
187
187
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
188
188
  return parsed.text || null;
189
- }`,ly=`function(parsed) {
189
+ }`,pb=`function(parsed) {
190
190
  if (!parsed || typeof parsed !== 'object') return null;
191
191
  if (parsed.action === 'nav_then_click') return 'Navigating...';
192
192
  if (parsed.action === 'message') return parsed.text || '';
193
193
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
194
194
  return parsed.text || null;
195
- }`;function cy(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Fi(e){var t,n;return(n=(t=e.parserType)!=null?t:cy(e.streamParser))!=null?n:"plain"}function _i(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function $i(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function ji(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Ui(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function jl(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Vm(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),Vm(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function fo(e,t,n,r){n&&(e.push(`${r}${t}: {`),Vm(e,n,`${r} `),e.push(`${r}},`))}function Km(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:ay(n.hooks)}:void 0;return t==="esm"?dy(r,s):t==="script-installer"?my(r,s):t==="script-advanced"?fy(r,s):t==="react-component"?py(r,s):t==="react-advanced"?uy(r,s):gy(r,s)}function dy(e,t){let n=t==null?void 0:t.hooks,r=Fi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(o,"theme",e.theme," "),e.launcher&&fo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(..._i(e," ")),o.push(...$i(e," ",n)),o.push(...ji(e," ")),o.push(...Ui(e," ")),o.push(...jl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
196
- `)}function py(e,t){let n=t==null?void 0:t.hooks,r=Fi(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(o,"theme",e.theme," "),e.launcher&&fo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(..._i(e," ")),o.push(...$i(e," ",n)),o.push(...ji(e," ")),o.push(...Ui(e," ")),o.push(...jl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
197
- `)}function uy(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(r,"theme",e.theme," "),e.launcher&&fo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(..._i(e," ")),r.push(...$i(e," ",n)),r.push(...ji(e," ")),r.push(...Ui(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${iy}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${jm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${jm}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${qm}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${qm}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
198
- `)}function Jm(e){var s;let t=Fi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function my(e,t){let n=Jm(e),r=t!=null&&t.windowKey?{config:n,windowKey:t.windowKey}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist/install.global.js" data-config='${s}'></script>`}function gy(e,t){let n=t==null?void 0:t.hooks,r=Fi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(o,"theme",e.theme," "),e.launcher&&fo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(..._i(e," ")),o.push(...$i(e," ",n)),o.push(...ji(e," ")),o.push(...Ui(e," ")),o.push(...jl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
199
- `)}function fy(e,t){let n=t==null?void 0:t.hooks,r=Jm(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
195
+ }`;function ub(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function Fi(e){var n,t;return(t=(n=e.parserType)!=null?n:ub(e.streamParser))!=null?t:"plain"}function _i(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function $i(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function ji(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function Ui(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${n} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${n} ${d}: ${l},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function jl(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function Jm(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),Jm(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function fo(e,n,t,r){t&&(e.push(`${r}${n}: {`),Jm(e,t,`${r} `),e.push(`${r}},`))}function Gm(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:cb(t.hooks)}:void 0;return n==="esm"?mb(r,s):n==="script-installer"?hb(r,s):n==="script-advanced"?yb(r,s):n==="react-component"?gb(r,s):n==="react-advanced"?fb(r,s):bb(r,s)}function mb(e,n){let t=n==null?void 0:n.hooks,r=Fi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(o,"theme",e.theme," "),e.launcher&&fo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(..._i(e," ")),o.push(...$i(e," ",t)),o.push(...ji(e," ")),o.push(...Ui(e," ")),o.push(...jl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
196
+ `)}function gb(e,n){let t=n==null?void 0:n.hooks,r=Fi(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(o,"theme",e.theme," "),e.launcher&&fo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(..._i(e," ")),o.push(...$i(e," ",t)),o.push(...ji(e," ")),o.push(...Ui(e," ")),o.push(...jl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
197
+ `)}function fb(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(r,"theme",e.theme," "),e.launcher&&fo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(..._i(e," ")),r.push(...$i(e," ",t)),r.push(...ji(e," ")),r.push(...Ui(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${db}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${qm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${qm}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Vm}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Vm}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
198
+ `)}function Xm(e){var s;let n=Fi(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function hb(e,n){let t=Xm(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist/install.global.js" data-config='${s}'></script>`}function bb(e,n){let t=n==null?void 0:n.hooks,r=Fi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fo(o,"theme",e.theme," "),e.launcher&&fo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(..._i(e," ")),o.push(...$i(e," ",t)),o.push(...ji(e," ")),o.push(...Ui(e," ")),o.push(...jl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
199
+ `)}function yb(e,n){let t=n==null?void 0:n.hooks,r=Xm(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
200
200
  `).map((a,i)=>i===0?a:" "+a).join(`
201
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${ly});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Um}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Um}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${zm}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${zm}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
202
- `)}var Gm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Xm=.1,Qm=.15,Ym=1.5,Ul=24,Zm=40,hy=`
201
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${jo}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${pb});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${zm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${zm}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Km}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Km}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
202
+ `)}var Qm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ym=.1,Zm=.15,eg=1.5,Ul=24,tg=40,xb=`
203
203
  /* \u2500\u2500 Root \u2500\u2500 */
204
204
  .persona-dc-root {
205
205
  display: flex;
@@ -440,5 +440,5 @@ ${a.join(`
440
440
  min-height: 300px;
441
441
  }
442
442
  }
443
- `;function yy(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=hy,document.head.appendChild(e)}function by(e,t){let n=e.clientWidth-Ul*2-Zm,r=e.clientHeight-Ul*2-Zm;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function xy(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function eg(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");yy();let u=Math.max(0,Math.min(r,n.length-1)),p=s,f=o,m=null,v=1,x=!1,T=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),W=h("div","persona-dc-toolbar-lead"),I=h("div","persona-dc-toolbar-trail"),O=_t({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>me(-1)}),P=h("div");P.style.position="relative";let C=h("button","persona-dc-title-btn");C.type="button",C.setAttribute("aria-expanded","false"),C.setAttribute("aria-haspopup","listbox");let R=h("span","persona-dc-title-text"),_=h("span","persona-dc-title-chevron"),$=be("chevron-down",12,"currentColor",2);$&&_.appendChild($),C.append(R,_);let D=h("div","persona-dc-dropdown");D.setAttribute("role","listbox"),D.style.display="none";let U=!1;function z(){D.innerHTML="";for(let fe=0;fe<n.length;fe++){let le=n[fe],ie=h("button","persona-dc-dropdown-item");ie.type="button",ie.setAttribute("role","option"),ie.setAttribute("aria-current",fe===u?"true":"false");let Ye=h("span");if(Ye.textContent=le.title,ie.appendChild(Ye),le.description){let Ae=h("span","persona-dc-dropdown-desc");Ae.textContent=le.description,ie.appendChild(Ae)}ie.addEventListener("click",()=>{We(),Xe(fe)}),D.appendChild(ie)}}function oe(){U=!U,D.style.display=U?"":"none",C.setAttribute("aria-expanded",U?"true":"false"),U&&z()}function We(){U&&(U=!1,D.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",fe=>{fe.stopPropagation(),oe()});let He=()=>We();document.addEventListener("click",He),P.append(C,D);let Oe=_t({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>me(1)}),de=h("span","persona-dc-counter");W.append(O,P,Oe,de);let we=null;i&&(we=sa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:fe=>{p=fe,K.dataset.device=p,m=null,V()}}),I.appendChild(we.element));let ke=null;if(a){let fe=h("div","persona-dc-zoom-controls"),le=_t({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ae=m!=null?m:v;m=Math.max(Qm,Ae-Xm),V()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{m=1,V()});let ie=_t({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ae=m!=null?m:v;m=Math.min(Ym,Ae+Xm),V()}}),Ye=_t({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,V()}});fe.append(le,ke,ie,Ye),I.appendChild(fe)}if(d){let fe=h("div","persona-dc-separator");I.appendChild(fe);let le=sa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ie=>{f=ie,K.dataset.colorScheme=f,he()}});I.appendChild(le.element)}let Pe=h("div","persona-dc-separator");I.appendChild(Pe);let re=_t({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});I.appendChild(re),S.append(W,I);let Le=h("div","persona-dc-stage"),K=h("div","persona-dc-iframe-wrapper");K.dataset.device=p,K.dataset.colorScheme=f;let ue=h("iframe","persona-dc-iframe");ue.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ue.setAttribute("loading","lazy"),ue.title=n[u].title,K.appendChild(ue),Le.appendChild(K),T.append(S,Le),e.appendChild(T);function he(){var fe;try{let le=(fe=ue.contentDocument)==null?void 0:fe.body;if(!le)return;f==="dark"?le.classList.add("theme-dark"):le.classList.remove("theme-dark")}catch{}}ue.addEventListener("load",()=>he());function ge(){let fe=n[u];R.textContent=fe.title,de.textContent=`${u+1} / ${n.length}`,ue.title=fe.title}function me(fe){let le=((u+fe)%n.length+n.length)%n.length;Xe(le)}function Xe(fe){fe<0||fe>=n.length||(u=fe,ue.src=n[u].url,ge(),l==null||l(u,n[u]))}function V(){var ie;if(x)return;let fe=(ie=Gm[p])!=null?ie:Gm.desktop;v=by(Le,fe);let le=Math.max(Qm,Math.min(Ym,m!=null?m:v));xy(K,ue,fe,le,p),ke&&(ke.textContent=`${Math.round(le*100)}%`)}let ne=new ResizeObserver(()=>V());ne.observe(Le),ge(),ue.src=n[u].url,requestAnimationFrame(()=>V());function Re(){x||(x=!0,ne.disconnect(),document.removeEventListener("click",He),T.remove())}return{element:T,goTo:Xe,next:()=>me(1),prev:()=>me(-1),getIndex:()=>u,setDevice(fe){p=fe,K.dataset.device=fe,we==null||we.setSelected(fe),m=null,V()},setColorScheme(fe){f=fe,K.dataset.colorScheme=fe},setZoom(fe){m=fe,V()},destroy:Re}}function tg(){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 ng(){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 rg(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Tr(e.colors.primary,.95),100:Tr(e.colors.primary,.9),200:Tr(e.colors.primary,.8),300:Tr(e.colors.primary,.7),400:Tr(e.colors.primary,.6),500:e.colors.primary,600:Tr(e.colors.primary,.8),700:Tr(e.colors.primary,.7),800:Tr(e.colors.primary,.6),900:Tr(e.colors.primary,.5),950:Tr(e.colors.primary,.45)}}),{...t,palette:n}}}}function og(){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 sg(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Tr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function ag(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var vy={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"}}},ig={components:{panel:{borderRadius:"0",shadow:"none"}}},ql={id:"shop",label:"Shopping Assistant",config:{theme:vy,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Xn},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?"]}},zl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:ig}},Vl={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:ig}},Kl={shop:ql,minimal:zl,fullscreen:Vl};function lg(e){return Kl[e]}var wy=Dl;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,WEBMCP_TOOL_PREFIX,WebMcpBridge,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,isWebMcpToolName,listRegisteredStreamAnimations,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
443
+ `;function vb(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=xb,document.head.appendChild(e)}function wb(e,n){let t=e.clientWidth-Ul*2-tg,r=e.clientHeight-Ul*2-tg;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function Cb(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function ng(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");vb();let u=Math.max(0,Math.min(r,t.length-1)),p=s,f=o,m=null,x=1,v=!1,E=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),R=h("div","persona-dc-toolbar-lead"),I=h("div","persona-dc-toolbar-trail"),W=_t({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>me(-1)}),P=h("div");P.style.position="relative";let w=h("button","persona-dc-title-btn");w.type="button",w.setAttribute("aria-expanded","false"),w.setAttribute("aria-haspopup","listbox");let H=h("span","persona-dc-title-text"),_=h("span","persona-dc-title-chevron"),$=ye("chevron-down",12,"currentColor",2);$&&_.appendChild($),w.append(H,_);let N=h("div","persona-dc-dropdown");N.setAttribute("role","listbox"),N.style.display="none";let U=!1;function z(){N.innerHTML="";for(let fe=0;fe<t.length;fe++){let le=t[fe],ie=h("button","persona-dc-dropdown-item");ie.type="button",ie.setAttribute("role","option"),ie.setAttribute("aria-current",fe===u?"true":"false");let Ye=h("span");if(Ye.textContent=le.title,ie.appendChild(Ye),le.description){let Ae=h("span","persona-dc-dropdown-desc");Ae.textContent=le.description,ie.appendChild(Ae)}ie.addEventListener("click",()=>{We(),Xe(fe)}),N.appendChild(ie)}}function oe(){U=!U,N.style.display=U?"":"none",w.setAttribute("aria-expanded",U?"true":"false"),U&&z()}function We(){U&&(U=!1,N.style.display="none",w.setAttribute("aria-expanded","false"))}w.addEventListener("click",fe=>{fe.stopPropagation(),oe()});let He=()=>We();document.addEventListener("click",He),P.append(w,N);let Oe=_t({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>me(1)}),de=h("span","persona-dc-counter");R.append(W,P,Oe,de);let we=null;i&&(we=sa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:fe=>{p=fe,K.dataset.device=p,m=null,V()}}),I.appendChild(we.element));let ke=null;if(a){let fe=h("div","persona-dc-zoom-controls"),le=_t({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ae=m!=null?m:x;m=Math.max(Zm,Ae-Ym),V()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{m=1,V()});let ie=_t({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ae=m!=null?m:x;m=Math.min(eg,Ae+Ym),V()}}),Ye=_t({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,V()}});fe.append(le,ke,ie,Ye),I.appendChild(fe)}if(d){let fe=h("div","persona-dc-separator");I.appendChild(fe);let le=sa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ie=>{f=ie,K.dataset.colorScheme=f,he()}});I.appendChild(le.element)}let Pe=h("div","persona-dc-separator");I.appendChild(Pe);let re=_t({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});I.appendChild(re),S.append(R,I);let Le=h("div","persona-dc-stage"),K=h("div","persona-dc-iframe-wrapper");K.dataset.device=p,K.dataset.colorScheme=f;let ue=h("iframe","persona-dc-iframe");ue.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ue.setAttribute("loading","lazy"),ue.title=t[u].title,K.appendChild(ue),Le.appendChild(K),E.append(S,Le),e.appendChild(E);function he(){var fe;try{let le=(fe=ue.contentDocument)==null?void 0:fe.body;if(!le)return;f==="dark"?le.classList.add("theme-dark"):le.classList.remove("theme-dark")}catch{}}ue.addEventListener("load",()=>he());function ge(){let fe=t[u];H.textContent=fe.title,de.textContent=`${u+1} / ${t.length}`,ue.title=fe.title}function me(fe){let le=((u+fe)%t.length+t.length)%t.length;Xe(le)}function Xe(fe){fe<0||fe>=t.length||(u=fe,ue.src=t[u].url,ge(),l==null||l(u,t[u]))}function V(){var ie;if(v)return;let fe=(ie=Qm[p])!=null?ie:Qm.desktop;x=wb(Le,fe);let le=Math.max(Zm,Math.min(eg,m!=null?m:x));Cb(K,ue,fe,le,p),ke&&(ke.textContent=`${Math.round(le*100)}%`)}let ne=new ResizeObserver(()=>V());ne.observe(Le),ge(),ue.src=t[u].url,requestAnimationFrame(()=>V());function Re(){v||(v=!0,ne.disconnect(),document.removeEventListener("click",He),E.remove())}return{element:E,goTo:Xe,next:()=>me(1),prev:()=>me(-1),getIndex:()=>u,setDevice(fe){p=fe,K.dataset.device=fe,we==null||we.setSelected(fe),m=null,V()},setColorScheme(fe){f=fe,K.dataset.colorScheme=fe},setZoom(fe){m=fe,V()},destroy:Re}}function rg(){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 og(){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 sg(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:Er(e.colors.primary,.95),100:Er(e.colors.primary,.9),200:Er(e.colors.primary,.8),300:Er(e.colors.primary,.7),400:Er(e.colors.primary,.6),500:e.colors.primary,600:Er(e.colors.primary,.8),700:Er(e.colors.primary,.7),800:Er(e.colors.primary,.6),900:Er(e.colors.primary,.5),950:Er(e.colors.primary,.45)}}),{...n,palette:t}}}}function ag(){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 ig(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Er(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function lg(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Ab={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"}}},cg={components:{panel:{borderRadius:"0",shadow:"none"}}},ql={id:"shop",label:"Shopping Assistant",config:{theme:Ab,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Xn},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?"]}},zl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:cg}},Vl={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:cg}},Kl={shop:ql,minimal:zl,fullscreen:Vl};function dg(e){return Kl[e]}var Sb=Dl;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,WEBMCP_TOOL_PREFIX,WebMcpBridge,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,isWebMcpToolName,listRegisteredStreamAnimations,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
444
444
  //# sourceMappingURL=index.cjs.map