@runtypelabs/persona 3.29.1 → 3.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +55 -0
  2. package/dist/codegen.cjs +6 -6
  3. package/dist/codegen.js +4 -4
  4. package/dist/index.cjs +47 -47
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +112 -7
  7. package/dist/index.d.ts +112 -7
  8. package/dist/index.global.js +59 -59
  9. package/dist/index.global.js.map +1 -1
  10. package/dist/index.js +47 -47
  11. package/dist/index.js.map +1 -1
  12. package/dist/launcher.global.js +2 -2
  13. package/dist/launcher.global.js.map +1 -1
  14. package/dist/plugin-kit.cjs +1 -0
  15. package/dist/plugin-kit.d.cts +98 -0
  16. package/dist/plugin-kit.d.ts +98 -0
  17. package/dist/plugin-kit.js +1 -0
  18. package/dist/smart-dom-reader.d.cts +107 -4
  19. package/dist/smart-dom-reader.d.ts +107 -4
  20. package/dist/theme-editor.cjs +38 -38
  21. package/dist/theme-editor.d.cts +111 -6
  22. package/dist/theme-editor.d.ts +111 -6
  23. package/dist/theme-editor.js +38 -38
  24. package/dist/theme-reference.cjs +1 -1
  25. package/dist/theme-reference.d.cts +2 -0
  26. package/dist/theme-reference.d.ts +2 -0
  27. package/dist/theme-reference.js +1 -1
  28. package/package.json +8 -2
  29. package/src/components/approval-bubble.test.ts +268 -0
  30. package/src/components/approval-bubble.ts +170 -20
  31. package/src/components/launcher.ts +6 -3
  32. package/src/components/tool-bubble.test.ts +39 -0
  33. package/src/components/tool-bubble.ts +4 -0
  34. package/src/index-core.ts +1 -0
  35. package/src/plugin-kit.test.ts +230 -0
  36. package/src/plugin-kit.ts +294 -0
  37. package/src/plugins/types.ts +49 -2
  38. package/src/session.test.ts +99 -0
  39. package/src/session.ts +14 -3
  40. package/src/theme-editor/preview-utils.test.ts +10 -0
  41. package/src/theme-editor/preview-utils.ts +29 -1
  42. package/src/theme-editor/sections.test.ts +17 -0
  43. package/src/theme-editor/sections.ts +31 -0
  44. package/src/theme-reference.ts +1 -1
  45. package/src/types/theme.ts +2 -0
  46. package/src/types.ts +59 -2
  47. package/src/ui.approval-plugin.test.ts +204 -0
  48. package/src/ui.ts +149 -16
  49. package/src/utils/theme.test.ts +6 -2
  50. package/src/utils/theme.ts +0 -8
  51. package/src/utils/tokens.ts +6 -1
  52. package/src/webmcp-bridge.test.ts +66 -0
  53. package/src/webmcp-bridge.ts +49 -0
package/dist/index.cjs CHANGED
@@ -1,18 +1,18 @@
1
- "use strict";var hg=Object.create;var Na=Object.defineProperty;var yg=Object.getOwnPropertyDescriptor;var bg=Object.getOwnPropertyNames;var xg=Object.getPrototypeOf,vg=Object.prototype.hasOwnProperty;var Cg=(e,t)=>{for(var n in t)Na(e,n,{get:t[n],enumerable:!0})},Kp=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of bg(t))!vg.call(e,s)&&s!==n&&Na(e,s,{get:()=>t[s],enumerable:!(r=yg(t,s))||r.enumerable});return e};var Jp=(e,t,n)=>(n=e!=null?hg(xg(e)):{},Kp(t||!e||!e.__esModule?Na(n,"default",{value:e,enumerable:!0}):n,e)),wg=e=>Kp(Na({},"__esModule",{value:!0}),e);var Ly={};Cg(Ly,{ASK_USER_QUESTION_TOOL_NAME:()=>vl,AgentWidgetClient:()=>Ho,AgentWidgetSession:()=>ss,AttachmentManager:()=>Fo,DEFAULT_COMPONENTS:()=>nl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ti,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Xn,DEFAULT_PALETTE:()=>el,DEFAULT_SEMANTIC:()=>tl,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>Jl,PRESET_FULLSCREEN:()=>Kl,PRESET_MINIMAL:()=>Vl,PRESET_SHOP:()=>zl,THEME_ZONES:()=>Tu,VERSION:()=>qo,WEBMCP_TOOL_PREFIX:()=>_s,WebMcpBridge:()=>ns,accessibilityPlugin:()=>Jm,animationsPlugin:()=>Gm,applyThemeVariables:()=>io,attachHeaderToContainer:()=>Oo,brandPlugin:()=>Xm,buildComposer:()=>ds,buildDefaultHeader:()=>dl,buildHeader:()=>$r,buildHeaderWithLayout:()=>cs,buildMinimalHeader:()=>pl,collectEnrichedPageContext:()=>zm,componentRegistry:()=>Ur,createActionManager:()=>ma,createAgentExperience:()=>Oi,createAskUserQuestionBubble:()=>im,createBestAvailableVoiceProvider:()=>Za,createBubbleWithLayout:()=>Vu,createCSATFeedback:()=>Di,createComboButton:()=>yi,createComponentMiddleware:()=>Tm,createComponentStreamParser:()=>Wi,createDefaultSanitizer:()=>Xi,createDemoCarousel:()=>fg,createDirectivePostprocessor:()=>Zp,createDropdownMenu:()=>uo,createFlexibleJsonStreamParser:()=>au,createIconButton:()=>jt,createImagePart:()=>mu,createJsonStreamParser:()=>za,createLabelButton:()=>sa,createLocalStorageAdapter:()=>Ii,createMarkdownProcessor:()=>$s,createMarkdownProcessorFromConfig:()=>Io,createMessageActions:()=>hl,createNPSFeedback:()=>Ni,createPlainTextParser:()=>Ua,createPlugin:()=>Zm,createRegexJsonParser:()=>qa,createStandardBubble:()=>ps,createTextPart:()=>qs,createTheme:()=>is,createThemeObserver:()=>si,createToggleGroup:()=>aa,createTypingIndicator:()=>$o,createVoiceProvider:()=>No,createWidgetHostLayout:()=>ga,createXmlParser:()=>Va,default:()=>ng,defaultActionHandlers:()=>Uo,defaultJsonActionParser:()=>ua,defaultParseRules:()=>Ul,detectColorScheme:()=>Gs,directivePostprocessor:()=>eu,ensureAskUserQuestionSheet:()=>hs,escapeHtml:()=>Wo,extractComponentDirectiveFromMessage:()=>Bi,fileToImagePart:()=>gu,formatEnrichedContext:()=>Vm,generateAssistantMessageId:()=>Bo,generateCodeSnippet:()=>lg,generateMessageId:()=>lu,generateStableSelector:()=>ql,generateUserMessageId:()=>os,getActiveTheme:()=>ls,getColorScheme:()=>ol,getDisplayText:()=>du,getHeaderLayout:()=>ul,getImageParts:()=>uu,getPreset:()=>tg,hasComponentDirective:()=>Hi,hasImages:()=>pu,headerLayouts:()=>bi,highContrastPlugin:()=>Ym,initAgentWidget:()=>Ol,isAskUserQuestionMessage:()=>_r,isComponentDirectiveType:()=>Sm,isDockedMountMode:()=>rn,isVoiceSupported:()=>Vs,isWebMcpToolName:()=>ao,listRegisteredStreamAnimations:()=>Fu,markdownPostprocessor:()=>Gi,mergeWithDefaults:()=>ni,normalizeContent:()=>cu,parseAskUserQuestionPayload:()=>jr,pluginRegistry:()=>pa,reducedMotionPlugin:()=>Qm,registerStreamAnimationPlugin:()=>Du,removeAskUserQuestionSheet:()=>fo,renderComponentDirective:()=>Ri,renderLoadingIndicatorWithFallback:()=>fl,renderLucideIcon:()=>be,resolveDockConfig:()=>ir,resolveSanitizer:()=>ts,resolveTokens:()=>ri,stripWebMcpPrefix:()=>Qi,themeToCssVariables:()=>oi,unregisterStreamAnimationPlugin:()=>Nu,validateImageFile:()=>fu,validateTheme:()=>rl});module.exports=wg(Ly);var Xp=require("marked"),Ag=e=>{if(e)return e},$s=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new Xp.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=Ag(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},Io=e=>e?$s({markedOptions:e.options,renderer:e.renderer}):$s(),Sg=$s(),Gi=e=>Sg(e),Wo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Qp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Gp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Yp=(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=Gp(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=Gp(t.length);return t.push({token:o,type:s}),o}),n},Zp=e=>{let t=Io(e);return n=>{let r=[],s=Yp(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Qp(i)}"></div>`;o=o.replace(d,p)}),o}},eu=e=>{let t=[],n=Yp(e,t),r=Gi(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="${Qp(o)}"></div>`;r=r.replace(a,d)}),r};var tu=Jp(require("dompurify"),1),Tg={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"]},Eg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Xi=()=>{let e=(0,tu.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:")&&!Eg.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Tg)},ts=e=>e===!1?null:typeof e=="function"?e:Xi();var _s="webmcp:",Fa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function ru(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Mg(t.join(""))}`}function nu(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Mg(e){let t=nu(e,0).toString(36),n=nu(e,2654435761).toString(36);return`${t}.${n}`}var ns=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 Fa.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=Lg(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 u=typeof document!="undefined"&&!!document.modelContext;return br(u?"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=Qi(t),a;try{a=await s.getTools()}catch(u){let v=u instanceof Error?u.message:String(u);return br(`Failed to read WebMCP registry: ${v}`)}let i=a.find(u=>u.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,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),g=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",g,{once:!0}));try{let u=await s.executeTool(i,Rg(n),{signal:l.signal});return Pg(u)}catch(u){if(p)return br(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let v=u instanceof Error?u.message:String(u);return br(v)}finally{clearTimeout(m),r&&r.removeEventListener("abort",g)}}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){Fa.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,Fa.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:Ig;try{return await n(t)}catch(s){return Fa.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=>kg(t,r))}},Qi=e=>e.startsWith(_s)?e.slice(_s.length):e,ao=e=>e.startsWith(_s),kg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Lg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Pg=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:Hg(t)}]}},br=e=>({isError:!0,content:[{type:"text",text:e}]}),Ig=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Wg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var Tg=Object.create;var Na=Object.defineProperty;var Eg=Object.getOwnPropertyDescriptor;var Mg=Object.getOwnPropertyNames;var kg=Object.getPrototypeOf,Lg=Object.prototype.hasOwnProperty;var Pg=(e,t)=>{for(var n in t)Na(e,n,{get:t[n],enumerable:!0})},Qp=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Mg(t))!Lg.call(e,s)&&s!==n&&Na(e,s,{get:()=>t[s],enumerable:!(r=Eg(t,s))||r.enumerable});return e};var Yp=(e,t,n)=>(n=e!=null?Tg(kg(e)):{},Qp(t||!e||!e.__esModule?Na(n,"default",{value:e,enumerable:!0}):n,e)),Ig=e=>Qp(Na({},"__esModule",{value:!0}),e);var Fb={};Pg(Fb,{ASK_USER_QUESTION_TOOL_NAME:()=>Sl,AgentWidgetClient:()=>Oo,AgentWidgetSession:()=>ds,AttachmentManager:()=>jo,DEFAULT_COMPONENTS:()=>al,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ni,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Yn,DEFAULT_PALETTE:()=>ol,DEFAULT_SEMANTIC:()=>sl,DEFAULT_WIDGET_CONFIG:()=>$t,PRESETS:()=>Ql,PRESET_FULLSCREEN:()=>Xl,PRESET_MINIMAL:()=>Gl,PRESET_SHOP:()=>Jl,THEME_ZONES:()=>Pu,VERSION:()=>Jo,WEBMCP_TOOL_PREFIX:()=>_r,WebMcpBridge:()=>is,accessibilityPlugin:()=>rg,animationsPlugin:()=>og,applyThemeVariables:()=>uo,attachHeaderToContainer:()=>Uo,brandPlugin:()=>sg,buildComposer:()=>fs,buildDefaultHeader:()=>gl,buildHeader:()=>qr,buildHeaderWithLayout:()=>gs,buildMinimalHeader:()=>fl,collectEnrichedPageContext:()=>eg,componentRegistry:()=>Kr,createActionManager:()=>ba,createAgentExperience:()=>ji,createAskUserQuestionBubble:()=>um,createBestAvailableVoiceProvider:()=>ei,createBubbleWithLayout:()=>Qu,createCSATFeedback:()=>Fi,createComboButton:()=>yi,createComponentMiddleware:()=>Hm,createComponentStreamParser:()=>Bi,createDefaultSanitizer:()=>Zi,createDemoCarousel:()=>Sg,createDirectivePostprocessor:()=>ru,createDropdownMenu:()=>ho,createFlexibleJsonStreamParser:()=>pu,createIconButton:()=>Vt,createImagePart:()=>yu,createJsonStreamParser:()=>Va,createLabelButton:()=>ca,createLocalStorageAdapter:()=>Hi,createMarkdownProcessor:()=>zs,createMarkdownProcessorFromConfig:()=>Bo,createMessageActions:()=>vl,createNPSFeedback:()=>$i,createPlainTextParser:()=>qa,createPlugin:()=>lg,createRegexJsonParser:()=>za,createStandardBubble:()=>hs,createTextPart:()=>Js,createTheme:()=>us,createThemeObserver:()=>ai,createToggleGroup:()=>da,createTypingIndicator:()=>qo,createVoiceProvider:()=>_o,createWidgetHostLayout:()=>ya,createXmlParser:()=>Ka,default:()=>pg,defaultActionHandlers:()=>Ko,defaultJsonActionParser:()=>ha,defaultParseRules:()=>Vl,detectColorScheme:()=>Zs,directivePostprocessor:()=>ou,ensureAskUserQuestionSheet:()=>ws,escapeHtml:()=>Do,extractComponentDirectiveFromMessage:()=>Oi,fileToImagePart:()=>xu,formatEnrichedContext:()=>tg,generateAssistantMessageId:()=>Fo,generateCodeSnippet:()=>bg,generateMessageId:()=>mu,generateStableSelector:()=>Kl,generateUserMessageId:()=>cs,getActiveTheme:()=>ms,getColorScheme:()=>ll,getDisplayText:()=>fu,getHeaderLayout:()=>hl,getImageParts:()=>bu,getPreset:()=>dg,hasComponentDirective:()=>Ni,hasImages:()=>hu,headerLayouts:()=>xi,highContrastPlugin:()=>ig,initAgentWidget:()=>jl,isAskUserQuestionMessage:()=>zr,isComponentDirectiveType:()=>Rm,isDockedMountMode:()=>ln,isVoiceSupported:()=>Xs,isWebMcpToolName:()=>po,listRegisteredStreamAnimations:()=>Uu,markdownPostprocessor:()=>Yi,mergeWithDefaults:()=>ri,normalizeContent:()=>gu,parseAskUserQuestionPayload:()=>Vr,pluginRegistry:()=>fa,reducedMotionPlugin:()=>ag,registerStreamAnimationPlugin:()=>_u,removeAskUserQuestionSheet:()=>xo,renderComponentDirective:()=>Di,renderLoadingIndicatorWithFallback:()=>xl,renderLucideIcon:()=>we,resolveDockConfig:()=>mr,resolveSanitizer:()=>as,resolveTokens:()=>oi,stripWebMcpPrefix:()=>Fa,themeToCssVariables:()=>si,unregisterStreamAnimationPlugin:()=>ju,validateImageFile:()=>vu,validateTheme:()=>il});module.exports=Ig(Fb);var eu=require("marked"),Wg=e=>{if(e)return e},zs=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new eu.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=Wg(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},Bo=e=>e?zs({markedOptions:e.options,renderer:e.renderer}):zs(),Rg=zs(),Yi=e=>Rg(e),Do=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),tu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Zp=e=>`%%FORM_PLACEHOLDER_${e}%%`,nu=(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=Zp(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=Zp(t.length);return t.push({token:o,type:s}),o}),n},ru=e=>{let t=Bo(e);return n=>{let r=[],s=nu(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${tu(i)}"></div>`;o=o.replace(d,p)}),o}},ou=e=>{let t=[],n=nu(e,t),r=Yi(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="${tu(o)}"></div>`;r=r.replace(a,d)}),r};var su=Yp(require("dompurify"),1),Hg={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"]},Bg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Zi=()=>{let e=(0,su.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:")&&!Bg.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Hg)},as=e=>e===!1?null:typeof e=="function"?e:Zi();var _r="webmcp:",el=new Map,au=e=>{var t;el.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&el.set(n.name,r)}},tl=e=>el.get(Fa(e)),Oa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function lu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Dg(t.join(""))}`}function iu(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Dg(e){let t=iu(e,0).toString(36),n=iu(e,2654435761).toString(36);return`${t}.${n}`}var is=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 Oa.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}au(n);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=Og(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return Sr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let v=typeof document!="undefined"&&!!document.modelContext;return Sr(v?"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=Fa(t),a;try{a=await s.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return Sr(`Failed to read WebMCP registry: ${x}`)}au(a);let i=a.find(v=>v.name===o);if(!i)return Sr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return Sr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return Sr("Aborted by cancel()");let d=tl(o),l={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Sr("User declined the tool call.");if(r!=null&&r.aborted)return Sr("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),m=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await s.executeTool(i,jg(n),{signal:p.signal});return Fg(v)}catch(v){if(u)return Sr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return Sr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return Sr(x)}finally{clearTimeout(f),r&&r.removeEventListener("abort",m)}}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){Oa.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,Oa.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:$g;try{return await n(t)}catch(s){return Oa.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=>Ng(t,r))}},Fa=e=>e.startsWith(_r)?e.slice(_r.length):e,po=e=>e.startsWith(_r),Ng=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Og=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Fg=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:Ug(t)}]}},Sr=e=>({isError:!0,content:[{type:"text",text:e}]}),$g=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=_g(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
4
  ${t}`:"")+(e.description?`
5
5
 
6
- ${e.description}`:"");return window.confirm(n)},Wg=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)}},Rg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Hg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Fr=require("partial-json"),Oa=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),rs=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)}},Bg=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`},ou=e=>e.status==="complete"?Bg(e):e.status==="pending"?"Waiting":"",Dg=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 su=e=>e.status==="complete"?Dg(e):"Using tool...",$a=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 $a(t)},_a=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 $a(t)},Yi=(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)},ja=(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})},Ng=()=>{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(n)},_g=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)}},jg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ug=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var jr=require("partial-json"),$a=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ls=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)}},qg=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`},cu=e=>e.status==="complete"?qg(e):e.status==="pending"?"Waiting":"",zg=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 du=e=>e.status==="complete"?zg(e):"Using tool...",_a=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ks=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return _a(t)},ja=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 _a(t)},nl=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Ks(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ua=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Vs(r,n.slice(o,a.index),[]),a[1]!==void 0?Vs(r,a[1],["bold"]):a[2]!==void 0?Vs(r,a[2],["italic"]):a[3]!==void 0&&Vs(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Vs(r,n.slice(o),[]),r},Vs=(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})},Vg=()=>{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,`
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()=>{}}},Ro=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ua=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},qa=()=>{var t;let e=Ng();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)}},za=()=>{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,Fr.parse)(n,Fr.STR|Fr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Oa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Oa(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},au=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Oa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Oa(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,Fr.parse)(o,Fr.STR|Fr.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Va=()=>{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 Ka=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 Fg="https://api.runtype.com/v1/dispatch",Ja="https://api.runtype.com";function Og(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 Zi=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 $g(e){switch(e){case"json":return za;case"regex-json":return qa;case"xml":return Va;default:return Ua}}var iu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function _g(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=iu(n);if(!iu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Ro(e);return Ro(t)!==null&&a===null?t:e}var Ho=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Fg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:$g(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 ns(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$/,""))||Ja}/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,this.resetClientToolsFingerprint(),(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,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ja}/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.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let I=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:I}),I}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(Zi).map(I=>{var R,S,W;return{id:I.id,role:I.role,content:(W=(S=(R=I.contentParts)!=null?R:I.llmContent)!=null?S:I.rawContent)!=null?W:I.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,u=!!(g&&g.length>0),v=u?ru(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,w=u&&x&&this.lastSentClientToolsFingerprint===v,E=!1,B=null,L;for(let I=0;;I++){let S={...m,...u&&(E||!w)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),L.status===409&&I===0&&u){let W=await L.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}B=W!=null?W:{error:"Chat request failed"}}break}if(!L.ok){let I=B!=null?B:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(L.status===429){let S=new Error(I.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let R=new Error(I.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!L.body){let I=new Error("No response body received");throw n({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.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$/,""))||Ja}/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,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ja}/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:(p=r==null?void 0:r.streamResponse)!=null?p:!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(Zi).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(Zi).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=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},l=p=>r.current?r.current:d(p);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 p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}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 cn,Bn,Yn,ze;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=O=>{let Se=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Ne=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Fe=O.tools?O.tools.map(Ue=>({...Ue,chunks:Ue.chunks?[...Ue.chunks]:void 0})):void 0;return{...O,reasoning:Se,toolCall:Ne,tools:Fe}},m=O=>{if(O.role!=="assistant"||O.variant)return!0;let Se=Array.isArray(O.contentParts)&&O.contentParts.length>0,Ne=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||Se||Ne||!!O.stopReason},g=O=>{m(O)&&n({type:"message",message:p(O)})},u=null,v=null,x={current:null},w={current:null},E=!1,B=new Map,L=new Map,I=new Map,R=new Map,S={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},$=(O,Se,Ne="")=>`${O}::${Se}::${Ne}`,N=(O,Se)=>`${O}::${Se}::`,H=(O,Se,Ne,Fe)=>{let Ue=$(O,Se,Ne),pt=I.get(Ue);if(pt)return pt;let ot=Ne?`-${Ne}`:"",St={id:`nested-${O}-${Se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ne?{partId:Ne}:{},agentMetadata:{executionId:Fe,parentToolId:O,parentStepId:Se}};return I.set(Ue,St),g(St),St},j=O=>{if(O==null)return null;try{return String(O)}catch{return null}},V=O=>{var Se,Ne,Fe,Ue,pt;return j((pt=(Ue=(Fe=(Ne=(Se=O.stepId)!=null?Se:O.step_id)!=null?Ne:O.step)!=null?Fe:O.parentId)!=null?Ue:O.flowStepId)!=null?pt:O.flow_step_id)},se=O=>{var Se,Ne,Fe,Ue,pt,ot,St;return j((St=(ot=(pt=(Ue=(Fe=(Ne=(Se=O.callId)!=null?Se:O.call_id)!=null?Ne:O.requestId)!=null?Fe:O.request_id)!=null?Ue:O.toolCallId)!=null?pt:O.tool_call_id)!=null?ot:O.stepId)!=null?St:O.step_id)},He=r,qe=!1,Oe=()=>{if(u)return u;let O;return!qe&&He?(O=He,qe=!0):He&&w.current?O=`${He}_${w.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(u),u},fe=(O,Se)=>{S.lastId=Se,O&&S.byStep.set(O,Se)},xe=(O,Se)=>{var pt;let Ne=(pt=O.reasoningId)!=null?pt:O.id,Fe=V(O);if(Ne){let ot=String(Ne);return fe(Fe,ot),ot}if(Fe){let ot=S.byStep.get(Fe);if(ot)return S.lastId=ot,ot}if(S.lastId&&!Se)return S.lastId;if(!Se)return null;let Ue=`reason-${l()}`;return fe(Fe,Ue),Ue},Pe=O=>{let Se=B.get(O);if(Se)return Se;let Ne={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return B.set(O,Ne),g(Ne),Ne},De=(O,Se)=>{W.lastId=Se,O&&W.byCall.set(O,Se)},te=new Set,Ie=new Map,K=new Set,ce=new Map,Ce=O=>{if(!O)return!1;let Se=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return Se==="emit_artifact_markdown"||Se==="emit_artifact_component"},he=(O,Se)=>{var pt;let Ne=(pt=O.toolId)!=null?pt:O.id,Fe=se(O);if(Ne){let ot=String(Ne);return De(Fe,ot),ot}if(Fe){let ot=W.byCall.get(Fe);if(ot)return W.lastId=ot,ot}if(W.lastId&&!Se)return W.lastId;if(!Se)return null;let Ue=`tool-${l()}`;return De(Fe,Ue),Ue},we=O=>{let Se=L.get(O);if(Se)return Se;let Ne={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return L.set(O,Ne),g(Ne),Ne},Ke=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let Se=Number(O);if(!Number.isNaN(Se)&&Number.isFinite(Se))return Se;let Ne=Date.parse(O);if(!Number.isNaN(Ne))return Ne}return Date.now()},Q=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},ne=new Map,ae=new Map,me=new Map,le=new Map,oe=null,Ye=(O,Se,Ne)=>{var St;let Fe=me.get(O);Fe||(Fe=[],me.set(O,Fe));let Ue=0,pt=Fe.length;for(;Ue<pt;){let Ut=Ue+pt>>>1;Fe[Ut].seq<Se?Ue=Ut+1:pt=Ut}((St=Fe[Ue])==null?void 0:St.seq)===Se?Fe[Ue]={seq:Se,text:Ne}:Fe.splice(Ue,0,{seq:Se,text:Ne});let ot="";for(let Ut=0;Ut<Fe.length;Ut++)ot+=Fe[Ut].text;return ot},We=(O,Se)=>{let Ne=Q(Se),Fe=ae.get(O.id),Ue=_g(Fe,Ne);O.rawContent=Ue;let pt=ne.get(O.id),ot=Ze=>{var re;let Ft=(re=O.content)!=null?re:"";Ze.trim()!==""&&(Ft.trim().length===0||Ze.startsWith(Ft)||Ze.trimStart().startsWith(Ft.trim()))&&(O.content=Ze)},St=()=>{var Ze;if(pt){let Ft=(Ze=pt.close)==null?void 0:Ze.call(pt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(O.id),ae.delete(O.id),O.streaming=!1,g(O)};if(!pt){ot(Ne),St();return}let Ut=Ro(Ue);if(Ut!==null&&Ut.trim()!==""){ot(Ut),St();return}let z=Ze=>{var ge;let Ft=typeof Ze=="string"?Ze:(ge=Ze==null?void 0:Ze.text)!=null?ge:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let re=pt.getExtractedText();return re!==null&&re.trim()!==""?re:Ne},_t;try{_t=pt.processChunk(Ue)}catch{ot(Ne),St();return}if(_t instanceof Promise){_t.then(Ze=>{ot(z(Ze)),St()}).catch(()=>{ot(Ne),St()});return}ot(z(_t)),St()},de=[],G=!1,je,Mt=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,je()}))},pe=new Ka((O,Se)=>{de.push({payloadType:O,payload:Se}),Mt()}),ie=null,kn=new Map,$t=(cn=this.config.iterationDisplay)!=null?cn:"separate";for(je=()=>{var O,Se,Ne,Fe,Ue,pt,ot,St,Ut,z,_t,Ze,Ft,re,ge,Ct,qt,en,yn,Tt,wt,ht,bt,Vt,nt,Dn,Zn,bn,Nn,mt,vr,Fn,bo,Ln,zo,zr,Mr,xt,On,$n,xn,Pt,er,tr,_n,Vr,kr,Kr,jn,Rt,vn,nr,Jr,Lr,Gr,Cr,Un,dr,ft,Gt,Xt,qn,Xr,rr,pr,zn,T,Vn,ur,Pr,wr,vs,mr,gr,fr,Ir,xo,ha,Cs,ya,Vo,gt,ws,or,Pn,ba,xa,Ko,Wr,va,vo,As,Rr,Ss,Qr,Yr,Ca,wa,Ki,Co,Zr,Aa,Ts,eo,Sa,Es,to,Ms,Ta,Hr,Ea,no,Ht,Jo,Go,ks,Ar,Ma,Ls,Ps,ka,Xo,Qo,wo,La,Pa,Is,Ws,Rs,Hs,Cn,Kn,Br,st,Bs,Ao,hr,Ia;for(let ro=0;ro<de.length;ro++){let Je=de[ro].payloadType,A=de[ro].payload;if(Je==="reason_start"){let U=(O=xe(A,!0))!=null?O:`reason-${l()}`,P=Pe(U);P.reasoning=(Se=P.reasoning)!=null?Se:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(Fe=P.reasoning.startedAt)!=null?Fe:Ke((Ne=A.startedAt)!=null?Ne:A.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",g(P)}else if(Je==="reason_delta"||Je==="reason_chunk"){let U=(pt=(Ue=xe(A,!1))!=null?Ue:xe(A,!0))!=null?pt:`reason-${l()}`,P=Pe(U);P.reasoning=(ot=P.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(Ut=P.reasoning.startedAt)!=null?Ut:Ke((St=A.startedAt)!=null?St:A.timestamp);let Y=(Ze=(_t=(z=A.reasoningText)!=null?z:A.text)!=null?_t:A.delta)!=null?Ze:"";if(Y&&A.hidden!==!0){let ee=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ee!==void 0){let J=Ye(U,ee,String(Y));P.reasoning.chunks=[J]}else P.reasoning.chunks.push(String(Y))}if(P.reasoning.status=A.done?"complete":"streaming",A.done){P.reasoning.completedAt=Ke((Ft=A.completedAt)!=null?Ft:A.timestamp);let ee=(re=P.reasoning.startedAt)!=null?re:Date.now();P.reasoning.durationMs=Math.max(0,((ge=P.reasoning.completedAt)!=null?ge:Date.now())-ee)}P.streaming=P.reasoning.status!=="complete",g(P)}else if(Je==="reason_complete"){let U=(qt=(Ct=xe(A,!1))!=null?Ct:xe(A,!0))!=null?qt:`reason-${l()}`,P=B.get(U);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=Ke((en=A.completedAt)!=null?en:A.timestamp);let ee=(yn=P.reasoning.startedAt)!=null?yn:Date.now();P.reasoning.durationMs=Math.max(0,((Tt=P.reasoning.completedAt)!=null?Tt:Date.now())-ee),P.streaming=!1,g(P)}let Y=V(A);Y&&S.byStep.delete(Y)}else if(Je==="tool_start"){let U=(wt=he(A,!0))!=null?wt:`tool-${l()}`,P=(ht=A.toolName)!=null?ht:A.name;if(Ce(P)){te.add(U);continue}let Y=we(U),ee=(bt=Y.toolCall)!=null?bt:{id:U,status:"pending"};ee.name=P!=null?P:ee.name,ee.status="running",A.args!==void 0?ee.args=A.args:A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=(nt=ee.startedAt)!=null?nt:Ke((Vt=A.startedAt)!=null?Vt:A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,Y.toolCall=ee,Y.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(Y.agentMetadata={executionId:(Dn=J==null?void 0:J.executionId)!=null?Dn:A.executionId,iteration:(Zn=J==null?void 0:J.iteration)!=null?Zn:A.iteration}),g(Y)}else if(Je==="tool_chunk"||Je==="tool_delta"){let U=(Nn=(bn=he(A,!1))!=null?bn:he(A,!0))!=null?Nn:`tool-${l()}`;if(te.has(U))continue;let P=we(U),Y=(mt=P.toolCall)!=null?mt:{id:U,status:"running"};Y.startedAt=(Fn=Y.startedAt)!=null?Fn:Ke((vr=A.startedAt)!=null?vr:A.timestamp);let ee=(zo=(Ln=(bo=A.text)!=null?bo:A.delta)!=null?Ln:A.message)!=null?zo:"";ee&&(Y.chunks=(zr=Y.chunks)!=null?zr:[],Y.chunks.push(String(ee))),Y.status="running",P.toolCall=Y,P.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(P.agentMetadata=(On=P.agentMetadata)!=null?On:{executionId:(Mr=J==null?void 0:J.executionId)!=null?Mr:A.executionId,iteration:(xt=J==null?void 0:J.iteration)!=null?xt:A.iteration}),g(P)}else if(Je==="tool_complete"){let U=(xn=($n=he(A,!1))!=null?$n:he(A,!0))!=null?xn:`tool-${l()}`;if(te.has(U)){te.delete(U);continue}let P=we(U),Y=(Pt=P.toolCall)!=null?Pt:{id:U,status:"running"};Y.status="complete",A.result!==void 0&&(Y.result=A.result),typeof A.duration=="number"&&(Y.duration=A.duration),Y.completedAt=Ke((er=A.completedAt)!=null?er:A.timestamp);let ee=(tr=A.duration)!=null?tr:A.executionTime;if(typeof ee=="number")Y.durationMs=ee;else{let _e=(_n=Y.startedAt)!=null?_n:Date.now();Y.durationMs=Math.max(0,((Vr=Y.completedAt)!=null?Vr:Date.now())-_e)}P.toolCall=Y,P.streaming=!1;let J=A.agentContext;(J||A.executionId)&&(P.agentMetadata=(jn=P.agentMetadata)!=null?jn:{executionId:(kr=J==null?void 0:J.executionId)!=null?kr:A.executionId,iteration:(Kr=J==null?void 0:J.iteration)!=null?Kr:A.iteration}),g(P);let Re=se(A);Re&&W.byCall.delete(Re)}else if(Je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,P=(Rt=U!=null?U:A.toolId)!=null?Rt:`local-${l()}`,Y=we(P),ee=A.toolName,J=ao(ee),Re=(vn=Y.toolCall)!=null?vn:{id:P,status:"pending"};Re.name=ee,Re.args=A.parameters,Re.status=J?"running":"complete",Re.chunks=(nr=Re.chunks)!=null?nr:[],Re.startedAt=(Lr=Re.startedAt)!=null?Lr:Ke((Jr=A.startedAt)!=null?Jr:A.timestamp),J?(Re.completedAt=void 0,Re.duration=void 0,Re.durationMs=void 0):Re.completedAt=(Gr=Re.completedAt)!=null?Gr:Re.startedAt,Y.toolCall=Re,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(Un=A.executionId)!=null?Un:(Cr=Y.agentMetadata)==null?void 0:Cr.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(Y)}else if(Je==="text_start"){if((dr=A.toolContext)!=null&&dr.toolId)continue;let U=A.partId;if(U!==void 0&&w.current!==null&&U!==w.current){let P=u;P&&(P.streaming=!1,g(P),oe=P,u=null,E=!0)}U!==void 0&&(w.current=U)}else if(Je==="text_end"){if((ft=A.toolContext)!=null&&ft.toolId)continue;let U=u;U&&(U.streaming=!1,g(U),oe=U,u=null,E=!0)}else if(Je==="step_chunk"||Je==="step_delta"){let U=A.stepType,P=A.executionType;if(U==="tool"||P==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let _e=String((Xt=(Gt=A.id)!=null?Gt:Y.stepId)!=null?Xt:`step-${l()}`),tt=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Me=`${Y.toolId}::${_e}`,Xe=R.get(Me);if(tt!==""&&Xe!==void 0&&Xe!==""&&Xe!==tt){let At=I.get($(Y.toolId,_e,Xe));At&&At.streaming!==!1&&(At.streaming=!1,g(At))}tt!==""&&R.set(Me,tt);let It=H(Y.toolId,_e,tt,Y.executionId),on=(pr=(rr=(Xr=(qn=A.text)!=null?qn:A.delta)!=null?Xr:A.content)!=null?rr:A.chunk)!=null?pr:"";on&&(It.content+=String(on),It.streaming=!0,g(It)),A.isComplete&&(It.streaming=!1,g(It));continue}let ee=A.partId;if(ee!==void 0&&w.current!==null&&ee!==w.current){let _e=u;_e&&(_e.streaming=!1,g(_e),oe=_e,u=null,E=!0)}ee!==void 0&&(w.current=ee);let J=ee!==void 0&&(zn=le.get(ee))!=null?zn:Oe();ee!==void 0&&(J.partId||(J.partId=ee),le.set(ee,J));let Re=(Pr=(ur=(Vn=(T=A.text)!=null?T:A.delta)!=null?Vn:A.content)!=null?ur:A.chunk)!=null?Pr:"";if(Re){let _e=typeof A.seq=="number"?A.seq:void 0,tt=ee!=null?ee:J.id,Me=_e!==void 0?Ye(tt,_e,String(Re)):((wr=ae.get(J.id))!=null?wr:"")+Re;J.rawContent=Me,ne.has(J.id)||ne.set(J.id,this.createStreamParser());let Xe=ne.get(J.id),It=Me.trim().startsWith("{")||Me.trim().startsWith("[");if(It&&ae.set(J.id,Me),Xe.__isPlainTextParser===!0){J.content=_e!==void 0?Me:J.content+Re,ae.delete(J.id),ne.delete(J.id),J.rawContent=void 0,g(J);continue}let At=Xe.processChunk(Me);if(At instanceof Promise)At.then(kt=>{var un;let sn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(sn!==null&&sn.trim()!=="")J.content=sn,g(J);else if(!It&&!Me.trim().startsWith("<")){let wn=u,Qt=wn&&wn.id===J.id?wn:J;Qt.id===J.id&&(Qt.content=_e!==void 0?Me:Qt.content+Re,ae.delete(Qt.id),ne.delete(Qt.id),Qt.rawContent=void 0,g(Qt))}}).catch(()=>{J.content=_e!==void 0?Me:J.content+Re,ae.delete(J.id),ne.delete(J.id),J.rawContent=void 0,g(J)});else{let kt=typeof At=="string"?At:(vs=At==null?void 0:At.text)!=null?vs:null;kt!==null&&kt.trim()!==""?(J.content=kt,g(J)):!It&&!Me.trim().startsWith("<")&&(J.content=_e!==void 0?Me:J.content+Re,ae.delete(J.id),ne.delete(J.id),J.rawContent=void 0,g(J))}}if(A.isComplete){let _e=(gr=(mr=A.result)==null?void 0:mr.response)!=null?gr:J.content;if(_e){let tt=ae.get(J.id),Me=tt!=null?tt:Q(_e);J.rawContent=Me;let Xe=ne.get(J.id),It=null,on=!1;if(Xe&&(It=Xe.getExtractedText(),It===null&&(It=Ro(Me)),It===null)){let At=Xe.processChunk(Me);At instanceof Promise?(on=!0,At.then(kt=>{var un;let sn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(sn!==null){let wn=u;wn&&wn.id===J.id&&(wn.content=sn,wn.streaming=!1,ne.delete(wn.id),ae.delete(wn.id),g(wn))}})):It=typeof At=="string"?At:(fr=At==null?void 0:At.text)!=null?fr:null}if(!on){It!==null&&It.trim()!==""?J.content=It:ae.has(J.id)||(J.content=Q(_e));let At=ne.get(J.id);if(At){let kt=(Ir=At.close)==null?void 0:Ir.call(At);kt instanceof Promise&&kt.catch(()=>{}),ne.delete(J.id)}ae.delete(J.id),J.streaming=!1,g(J)}}}}else if(Je==="step_complete"){let U=A.stepType,P=A.executionType;if(U==="tool"||P==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let _e=String((ha=(xo=A.id)!=null?xo:Y.stepId)!=null?ha:"");if(_e){let tt=N(Y.toolId,_e);for(let[Me,Xe]of I)Me.startsWith(tt)&&Xe.streaming!==!1&&(Xe.streaming=!1,g(Xe));R.delete(`${Y.toolId}::${_e}`)}continue}let ee=A.stopReason;if(E){if(u!==null){let Me=u;ee&&(Me.stopReason=ee),ne.delete(Me.id),ae.delete(Me.id),Me.streaming!==!1&&(Me.streaming=!1,g(Me))}let _e=(Cs=A.result)==null?void 0:Cs.response,tt=oe;tt&&(ee&&(tt.stopReason=ee),_e!=null?We(tt,_e):(ne.delete(tt.id),ae.delete(tt.id))),oe=null;continue}let J=(ya=A.result)==null?void 0:ya.response,Re=Oe();if(ee&&(Re.stopReason=ee),J!=null){let _e=ne.get(Re.id),tt=!1,Me=!1;if(_e){let Xe=_e.getExtractedText(),It=ae.get(Re.id),on=It!=null?It:Q(J);if(Re.rawContent=on,Xe!==null&&Xe.trim()!=="")Re.content=Xe,tt=!0;else{let At=Ro(on);if(At!==null)Re.content=At,tt=!0;else{let kt=_e.processChunk(on);if(kt instanceof Promise)Me=!0,kt.then(sn=>{var wn;let un=typeof sn=="string"?sn:(wn=sn==null?void 0:sn.text)!=null?wn:null;if(un!==null&&un.trim()!==""){let Qt=u;Qt&&Qt.id===Re.id&&(Qt.content=un,Qt.streaming=!1,ne.delete(Qt.id),ae.delete(Qt.id),g(Qt))}else{let Qt=_e.getExtractedText(),sr=u;sr&&sr.id===Re.id&&(Qt!==null&&Qt.trim()!==""?sr.content=Qt:ae.has(sr.id)||(sr.content=Q(J)),sr.streaming=!1,ne.delete(sr.id),ae.delete(sr.id),g(sr))}});else{let sn=typeof kt=="string"?kt:(Vo=kt==null?void 0:kt.text)!=null?Vo:null;if(sn!==null&&sn.trim()!=="")Re.content=sn,tt=!0;else{let un=_e.getExtractedText();un!==null&&un.trim()!==""&&(Re.content=un,tt=!0)}}}}}if(!Me){if(!Re.rawContent){let Xe=ae.get(Re.id);Re.rawContent=Xe!=null?Xe:Q(J)}if(!tt&&!ae.has(Re.id)&&(Re.content=Q(J)),_e){let Xe=(gt=_e.close)==null?void 0:gt.call(_e);Xe instanceof Promise&&Xe.catch(()=>{})}ne.delete(Re.id),ae.delete(Re.id),Re.streaming=!1,g(Re)}}else ne.delete(Re.id),ae.delete(Re.id),Re.streaming=!1,g(Re)}else if(Je==="flow_complete"){let U=(ws=A.result)==null?void 0:ws.response;if(E){if(u!==null){let P=u;ne.delete(P.id),ae.delete(P.id),P.streaming!==!1&&(P.streaming=!1,g(P))}}else if(U!=null){let P=Oe(),Y=ae.get(P.id),ee=Y!=null?Y:Q(U);P.rawContent=ee;let J=Q(U),Re=ne.get(P.id);if(Re){let Me=Ro(ee);if(Me!==null)J=Me;else{let Xe=Re.processChunk(ee);Xe instanceof Promise&&Xe.then(on=>{var kt;let At=typeof on=="string"?on:(kt=on==null?void 0:on.text)!=null?kt:null;At!==null&&(P.content=At,P.streaming=!1,g(P))});let It=Re.getExtractedText();It!==null&&(J=It)}}ne.delete(P.id),ae.delete(P.id);let _e=J!==P.content,tt=P.streaming!==!1;_e&&(P.content=J),P.streaming=!1,(_e||tt)&&g(P)}else if(u!==null){let P=u;ne.delete(P.id),ae.delete(P.id),P.streaming!==!1&&(P.streaming=!1,g(P))}n({type:"status",status:"idle"})}else if(Je==="agent_start")ie={executionId:A.executionId,agentId:(or=A.agentId)!=null?or:"virtual",agentName:(Pn=A.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(ba=A.maxTurns)!=null?ba:1,startedAt:Ke(A.startedAt)};else if(Je==="agent_iteration_start"){if(ie&&(ie.currentIteration=A.iteration),$t==="separate"&&A.iteration>1){let U=u;U&&(U.streaming=!1,g(U),kn.set(A.iteration-1,U),u=null)}}else if(Je==="agent_turn_start")v=null;else if(Je==="agent_turn_delta"){if(A.contentType==="text"){let U=Oe();U.content+=(xa=A.delta)!=null?xa:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ie==null?void 0:ie.agentName},v=U,g(U)}else if(A.contentType==="thinking"){let U=(Ko=A.turnId)!=null?Ko:`agent-think-${A.iteration}`,P=Pe(U);P.reasoning=(Wr=P.reasoning)!=null?Wr:{id:U,status:"streaming",chunks:[]},P.reasoning.chunks.push((va=A.delta)!=null?va:""),P.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(P)}else if(A.contentType==="tool_input"){let U=(vo=A.toolCallId)!=null?vo:W.lastId;if(U){let P=L.get(U);P!=null&&P.toolCall&&(P.toolCall.chunks=(As=P.toolCall.chunks)!=null?As:[],P.toolCall.chunks.push((Rr=A.delta)!=null?Rr:""),g(P))}}}else if(Je==="agent_turn_complete"){let U=A.turnId;if(U){let ee=B.get(U);if(ee!=null&&ee.reasoning){ee.reasoning.status="complete",ee.reasoning.completedAt=Ke(A.completedAt);let J=(Ss=ee.reasoning.startedAt)!=null?Ss:Date.now();ee.reasoning.durationMs=Math.max(0,((Qr=ee.reasoning.completedAt)!=null?Qr:Date.now())-J),ee.streaming=!1,g(ee)}}let P=A.stopReason,Y=u!=null?u:v;if(P&&Y!==null){let ee=A.turnId;(!ee||((Yr=Y.agentMetadata)==null?void 0:Yr.turnId)===ee)&&(Y.stopReason=P,g(Y))}}else if(Je==="agent_tool_start"){u&&(u.streaming=!1,g(u),u=null);let U=(Ca=A.toolCallId)!=null?Ca:`agent-tool-${l()}`;De(se(A),U);let P=we(U),Y=(wa=P.toolCall)!=null?wa:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(Co=(Ki=A.toolName)!=null?Ki:A.name)!=null?Co:Y.name,Y.status="running",A.parameters!==void 0&&(Y.args=A.parameters),Y.startedAt=Ke((Zr=A.startedAt)!=null?Zr:A.timestamp),P.toolCall=Y,P.streaming=!0,P.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(P)}else if(Je==="agent_tool_delta"){let U=(Aa=A.toolCallId)!=null?Aa:W.lastId;if(U){let P=(Ts=L.get(U))!=null?Ts:we(U);P.toolCall&&(P.toolCall.chunks=(eo=P.toolCall.chunks)!=null?eo:[],P.toolCall.chunks.push((Sa=A.delta)!=null?Sa:""),P.toolCall.status="running",P.streaming=!0,g(P))}}else if(Je==="agent_tool_complete"){let U=(Es=A.toolCallId)!=null?Es:W.lastId;if(U){let P=(to=L.get(U))!=null?to:we(U);if(P.toolCall){P.toolCall.status="complete",A.result!==void 0&&(P.toolCall.result=A.result),typeof A.executionTime=="number"&&(P.toolCall.durationMs=A.executionTime),P.toolCall.completedAt=Ke((Ms=A.completedAt)!=null?Ms:A.timestamp),P.streaming=!1,g(P);let Y=se(A);Y&&W.byCall.delete(Y)}}}else if(Je==="agent_media"){let U=Array.isArray(A.media)?A.media:[],P=[];for(let Y of U){if(!Y||typeof Y!="object")continue;let ee=Y,J=typeof ee.type=="string"?ee.type:void 0,Re=typeof ee.mediaType=="string"?ee.mediaType.toLowerCase():"",_e=null,tt="";if(J==="media"){let Me=typeof ee.data=="string"?ee.data:void 0;if(!Me)continue;tt=Re.length>0?Re:"application/octet-stream",_e=`data:${tt};base64,${Me}`}else if(J==="image-url"){let Me=typeof ee.url=="string"?ee.url:void 0;if(!Me)continue;tt=Re,_e=Me}else if(J==="file-url"){let Me=typeof ee.url=="string"?ee.url:void 0;if(!Me)continue;tt=Re,_e=Me}else continue;if(_e)if(J==="image-url"||tt.startsWith("image/"))P.push({type:"image",image:_e,...tt?{mimeType:tt}:{}});else if(tt.startsWith("audio/"))P.push({type:"audio",audio:_e,mimeType:tt});else if(tt.startsWith("video/"))P.push({type:"video",video:_e,mimeType:tt});else{let Me=tt||"application/octet-stream";P.push({type:"file",data:_e,mimeType:Me,filename:Og(Me)})}}if(P.length>0){let Y=l(),ee=A.toolCallId,Re={id:`agent-media-${typeof ee=="string"&&ee.length>0?`${ee}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(Re);let _e=u;_e&&(_e.streaming=!1,g(_e)),u=null,x.current=null}}else if(Je!=="agent_iteration_complete"){if(Je==="agent_reflection"||Je==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,P={id:U,role:"assistant",content:(Ta=A.reflection)!=null?Ta:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Hr=A.reflection)!=null?Hr:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(P)}else if(Je==="agent_complete"){ie&&(ie.status=A.success?"complete":"error",ie.completedAt=Ke(A.completedAt),ie.stopReason=A.stopReason);let U=u;U&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}else if(Je==="agent_error"){let U=typeof A.error=="string"?A.error:(no=(Ea=A.error)==null?void 0:Ea.message)!=null?no:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Je!=="agent_ping"){if(Je==="agent_approval_start"){let U=(Ht=A.approvalId)!=null?Ht:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Jo=ie==null?void 0:ie.agentId)!=null?Jo:"virtual",executionId:(ks=(Go=A.executionId)!=null?Go:ie==null?void 0:ie.executionId)!=null?ks:"",toolName:(Ar=A.toolName)!=null?Ar:"",toolType:A.toolType,description:(Ls=A.description)!=null?Ls:`Execute ${(Ma=A.toolName)!=null?Ma:"tool"}`,parameters:A.parameters}};g(P)}else if(Je==="step_await"&&A.awaitReason==="approval_required"){let U=(Ps=A.approvalId)!=null?Ps:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ka=ie==null?void 0:ie.agentId)!=null?ka:"virtual",executionId:(Qo=(Xo=A.executionId)!=null?Xo:ie==null?void 0:ie.executionId)!=null?Qo:"",toolName:(wo=A.toolName)!=null?wo:"",toolType:A.toolType,description:(Pa=A.description)!=null?Pa:`Execute ${(La=A.toolName)!=null?La:"tool"}`,parameters:A.parameters}};g(P)}else if(Je==="agent_approval_complete"){let U=A.approvalId;if(U){let Y={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(Is=A.decision)!=null?Is:"approved",agentId:(Ws=ie==null?void 0:ie.agentId)!=null?Ws:"virtual",executionId:(Hs=(Rs=A.executionId)!=null?Rs:ie==null?void 0:ie.executionId)!=null?Hs:"",toolName:(Cn=A.toolName)!=null?Cn:"",description:(Kn=A.description)!=null?Kn:"",resolvedAt:Date.now()}};g(Y)}}else if(Je==="artifact_start"||Je==="artifact_delta"||Je==="artifact_update"||Je==="artifact_complete"){if(Je==="artifact_start"){let U=A.artifactType,P=String(A.id),Y=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:P,artifactType:U,title:Y,component:typeof A.component=="string"?A.component:void 0}),ce.set(P,{markdown:"",title:Y}),!K.has(P)){K.add(P);let ee={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:Y,artifactType:U,status:"streaming"}})};Ie.set(P,ee),g(ee)}}else if(Je==="artifact_delta"){let U=String(A.id),P=typeof A.delta=="string"?A.delta:String((Br=A.delta)!=null?Br:"");n({type:"artifact_delta",id:U,artDelta:P});let Y=ce.get(U);Y&&(Y.markdown+=P)}else if(Je==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(Je==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let P=Ie.get(U);if(P){P.streaming=!1;try{let Y=JSON.parse((st=P.rawContent)!=null?st:"{}");if(Y.props){Y.props.status="complete";let ee=ce.get(U);ee!=null&&ee.markdown&&(Y.props.markdown=ee.markdown)}P.rawContent=JSON.stringify(Y)}catch{}ce.delete(U),g(P),Ie.delete(U)}}}else if(Je==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let P=String((Bs=U.id)!=null?Bs:`msg-${l()}`),Y=U.role,J={id:P,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(g(J),J.rawContent)try{let Re=JSON.parse(J.rawContent),_e=(Ao=Re==null?void 0:Re.props)==null?void 0:Ao.artifactId;typeof _e=="string"&&K.add(_e)}catch{}u=null,x.current=null,ne.delete(P),ae.delete(P)}else if(Je==="error"||Je==="step_error"||Je==="dispatch_error"||Je==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(Je==="dispatch_error"){let P=(hr=A.message)!=null?hr:A.error;P!=null&&P!==""&&(U=new Error(String(P)))}else if(Je==="step_error"||Je==="flow_error"){let P=A.error;typeof P=="string"&&P!==""?U=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(U=new Error(String((Ia=P.message)!=null?Ia:P)))}else Je==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let P=u;P&&P.streaming&&(P.streaming=!1,g(P)),n({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:O,value:Se}=await s.read();if(O)break;a+=o.decode(Se,{stream:!0});let Ne=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<=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()=>{}}},No=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},qa=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},za=()=>{var t;let e=Vg();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)}},Va=()=>{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,jr.parse)(n,jr.STR|jr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?$a(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=$a(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},pu=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?$a(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,jr.parse)(o,jr.STR|jr.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Ka=()=>{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 Ja=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 Kg="https://api.runtype.com/v1/dispatch",Ga="https://api.runtype.com";function Jg(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 rl=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 Gg(e){switch(e){case"json":return Va;case"regex-json":return za;case"xml":return Ka;default:return qa}}var uu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Xg(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=uu(n);if(!uu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=No(e);return No(t)!==null&&a===null?t:e}var Oo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Kg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Gg(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 is(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$/,""))||Ga}/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,this.resetClientToolsFingerprint(),(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,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/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.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(rl).map(P=>{var W,S,I;return{id:P.id,role:P.role,content:(I=(S=(W=P.contentParts)!=null?W:P.llmContent)!=null?S:P.rawContent)!=null?I:P.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),v=m?lu(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,w=m&&x&&this.lastSentClientToolsFingerprint===v,T=!1,B=null,k;for(let P=0;;P++){let S={...u,...m&&(T||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),k.status===409&&P===0&&m){let I=await k.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}B=I!=null?I:{error:"Chat request failed"}}break}if(!k.ok){let P=B!=null?B:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(k.status===429){let S=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let W=new Error(P.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!k.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.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$/,""))||Ga}/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,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ga}/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:(p=r==null?void 0:r.streamResponse)!=null?p:!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(rl).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(rl).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=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=u,s(u),u},l=p=>r.current?r.current:d(p);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 p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}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 gn,Bn,er,Ue;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=F=>{let Ee=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,De=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ne=F.tools?F.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...F,reasoning:Ee,toolCall:De,tools:Ne}},u=F=>{if(F.role!=="assistant"||F.variant)return!0;let Ee=Array.isArray(F.contentParts)&&F.contentParts.length>0,De=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||Ee||De||!!F.stopReason},f=F=>{u(F)&&n({type:"message",message:p(F)})},m=null,v=null,x={current:null},w={current:null},T=!1,B=new Map,k=new Map,P=new Map,W=new Map,S={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},$=(F,Ee,De="")=>`${F}::${Ee}::${De}`,D=(F,Ee)=>`${F}::${Ee}::`,R=(F,Ee,De,Ne)=>{let _e=$(F,Ee,De),mt=P.get(_e);if(mt)return mt;let at=De?`-${De}`:"",It={id:`nested-${F}-${Ee}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ne,parentToolId:F,parentStepId:Ee}};return P.set(_e,It),f(It),It},q=F=>{if(F==null)return null;try{return String(F)}catch{return null}},K=F=>{var Ee,De,Ne,_e,mt;return q((mt=(_e=(Ne=(De=(Ee=F.stepId)!=null?Ee:F.step_id)!=null?De:F.step)!=null?Ne:F.parentId)!=null?_e:F.flowStepId)!=null?mt:F.flow_step_id)},se=F=>{var Ee,De,Ne,_e,mt,at,It;return q((It=(at=(mt=(_e=(Ne=(De=(Ee=F.callId)!=null?Ee:F.call_id)!=null?De:F.requestId)!=null?Ne:F.request_id)!=null?_e:F.toolCallId)!=null?mt:F.tool_call_id)!=null?at:F.stepId)!=null?It:F.step_id)},Re=r,Ge=!1,Ce=()=>{if(m)return m;let F;return!Ge&&Re?(F=Re,Ge=!0):Re&&w.current?F=`${Re}_${w.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},He=(F,Ee)=>{S.lastId=Ee,F&&S.byStep.set(F,Ee)},be=(F,Ee)=>{var mt;let De=(mt=F.reasoningId)!=null?mt:F.id,Ne=K(F);if(De){let at=String(De);return He(Ne,at),at}if(Ne){let at=S.byStep.get(Ne);if(at)return S.lastId=at,at}if(S.lastId&&!Ee)return S.lastId;if(!Ee)return null;let _e=`reason-${l()}`;return He(Ne,_e),_e},Be=F=>{let Ee=B.get(F);if(Ee)return Ee;let De={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return B.set(F,De),f(De),De},Pe=(F,Ee)=>{I.lastId=Ee,F&&I.byCall.set(F,Ee)},J=new Set,ue=new Map,V=new Set,de=new Map,le=F=>{if(!F)return!1;let Ee=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ee==="emit_artifact_markdown"||Ee==="emit_artifact_component"},ae=(F,Ee)=>{var mt;let De=(mt=F.toolId)!=null?mt:F.id,Ne=se(F);if(De){let at=String(De);return Pe(Ne,at),at}if(Ne){let at=I.byCall.get(Ne);if(at)return I.lastId=at,at}if(I.lastId&&!Ee)return I.lastId;if(!Ee)return null;let _e=`tool-${l()}`;return Pe(Ne,_e),_e},Se=F=>{let Ee=k.get(F);if(Ee)return Ee;let De={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return k.set(F,De),f(De),De},ze=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let Ee=Number(F);if(!Number.isNaN(Ee)&&Number.isFinite(Ee))return Ee;let De=Date.parse(F);if(!Number.isNaN(De))return De}return Date.now()},Y=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ne=new Map,ce=new Map,xe=new Map,me=new Map,oe=null,Ze=(F,Ee,De)=>{var It;let Ne=xe.get(F);Ne||(Ne=[],xe.set(F,Ne));let _e=0,mt=Ne.length;for(;_e<mt;){let Kt=_e+mt>>>1;Ne[Kt].seq<Ee?_e=Kt+1:mt=Kt}((It=Ne[_e])==null?void 0:It.seq)===Ee?Ne[_e]={seq:Ee,text:De}:Ne.splice(_e,0,{seq:Ee,text:De});let at="";for(let Kt=0;Kt<Ne.length;Kt++)at+=Ne[Kt].text;return at},We=(F,Ee)=>{let De=Y(Ee),Ne=ce.get(F.id),_e=Xg(Ne,De);F.rawContent=_e;let mt=ne.get(F.id),at=et=>{var re;let _t=(re=F.content)!=null?re:"";et.trim()!==""&&(_t.trim().length===0||et.startsWith(_t)||et.trimStart().startsWith(_t.trim()))&&(F.content=et)},It=()=>{var et;if(mt){let _t=(et=mt.close)==null?void 0:et.call(mt);_t instanceof Promise&&_t.catch(()=>{})}ne.delete(F.id),ce.delete(F.id),F.streaming=!1,f(F)};if(!mt){at(De),It();return}let Kt=No(_e);if(Kt!==null&&Kt.trim()!==""){at(Kt),It();return}let z=et=>{var ve;let _t=typeof et=="string"?et:(ve=et==null?void 0:et.text)!=null?ve:null;if(_t!==null&&_t.trim()!=="")return _t;let re=mt.getExtractedText();return re!==null&&re.trim()!==""?re:De},qt;try{qt=mt.processChunk(_e)}catch{at(De),It();return}if(qt instanceof Promise){qt.then(et=>{at(z(et)),It()}).catch(()=>{at(De),It()});return}at(z(qt)),It()},fe=[],X=!1,$e,Ht=()=>{X||(X=!0,queueMicrotask(()=>{X=!1,$e()}))},he=new Ja((F,Ee)=>{fe.push({payloadType:F,payload:Ee}),Ht()}),pe=null,Pn=new Map,Ut=(gn=this.config.iterationDisplay)!=null?gn:"separate";for($e=()=>{var F,Ee,De,Ne,_e,mt,at,It,Kt,z,qt,et,_t,re,ve,Et,Jt,nn,Cn,Wt,kt,wt,At,Gt,ot,Dn,tr,An,Nn,bt,Er,On,Co,In,Go,Gr,Wr,St,Fn,$n,Sn,Lt,nr,rr,_n,Xr,Rr,Qr,jn,Dt,Tn,or,Yr,Hr,Zr,Mr,Un,hr,xt,Qt,Yt,qn,eo,sr,br,zn,_,ar,ye,Vn,ir,yr,Ts,xr,vr,wr,Br,Ao,va,Es,wa,Xo,yt,Ms,lr,Wn,Ca,Aa,Qo,Dr,Sa,So,ks,Nr,Ls,to,no,Ta,Ea,Xi,To,ro,Ma,Ps,oo,ka,Is,so,Ws,La,Or,Pa,ao,Nt,Yo,Zo,Rs,kr,Ia,Hs,Bs,Wa,es,ts,Eo,Ra,Ha,Ds,Ns,Os,Fs,En,Kn,Fr,ct,$s,Mo,Cr;for(let ns=0;ns<fe.length;ns++){let Je=fe[ns].payloadType,A=fe[ns].payload;if(Je==="reason_start"){let j=(F=be(A,!0))!=null?F:`reason-${l()}`,M=Be(j);M.reasoning=(Ee=M.reasoning)!=null?Ee:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(Ne=M.reasoning.startedAt)!=null?Ne:ze((De=A.startedAt)!=null?De:A.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",f(M)}else if(Je==="reason_delta"||Je==="reason_chunk"){let j=(mt=(_e=be(A,!1))!=null?_e:be(A,!0))!=null?mt:`reason-${l()}`,M=Be(j);M.reasoning=(at=M.reasoning)!=null?at:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(Kt=M.reasoning.startedAt)!=null?Kt:ze((It=A.startedAt)!=null?It:A.timestamp);let Z=(et=(qt=(z=A.reasoningText)!=null?z:A.text)!=null?qt:A.delta)!=null?et:"";if(Z&&A.hidden!==!0){let ie=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ie!==void 0){let G=Ze(j,ie,String(Z));M.reasoning.chunks=[G]}else M.reasoning.chunks.push(String(Z))}if(M.reasoning.status=A.done?"complete":"streaming",A.done){M.reasoning.completedAt=ze((_t=A.completedAt)!=null?_t:A.timestamp);let ie=(re=M.reasoning.startedAt)!=null?re:Date.now();M.reasoning.durationMs=Math.max(0,((ve=M.reasoning.completedAt)!=null?ve:Date.now())-ie)}M.streaming=M.reasoning.status!=="complete",f(M)}else if(Je==="reason_complete"){let j=(Jt=(Et=be(A,!1))!=null?Et:be(A,!0))!=null?Jt:`reason-${l()}`,M=B.get(j);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=ze((nn=A.completedAt)!=null?nn:A.timestamp);let ie=(Cn=M.reasoning.startedAt)!=null?Cn:Date.now();M.reasoning.durationMs=Math.max(0,((Wt=M.reasoning.completedAt)!=null?Wt:Date.now())-ie),M.streaming=!1,f(M)}let Z=K(A);Z&&S.byStep.delete(Z)}else if(Je==="tool_start"){let j=(kt=ae(A,!0))!=null?kt:`tool-${l()}`,M=(wt=A.toolName)!=null?wt:A.name;if(le(M)){J.add(j);continue}let Z=Se(j),ie=(At=Z.toolCall)!=null?At:{id:j,status:"pending"};ie.name=M!=null?M:ie.name,ie.status="running",A.args!==void 0?ie.args=A.args:A.parameters!==void 0&&(ie.args=A.parameters),ie.startedAt=(ot=ie.startedAt)!=null?ot:ze((Gt=A.startedAt)!=null?Gt:A.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,Z.toolCall=ie,Z.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(Z.agentMetadata={executionId:(Dn=G==null?void 0:G.executionId)!=null?Dn:A.executionId,iteration:(tr=G==null?void 0:G.iteration)!=null?tr:A.iteration}),f(Z)}else if(Je==="tool_chunk"||Je==="tool_delta"){let j=(Nn=(An=ae(A,!1))!=null?An:ae(A,!0))!=null?Nn:`tool-${l()}`;if(J.has(j))continue;let M=Se(j),Z=(bt=M.toolCall)!=null?bt:{id:j,status:"running"};Z.startedAt=(On=Z.startedAt)!=null?On:ze((Er=A.startedAt)!=null?Er:A.timestamp);let ie=(Go=(In=(Co=A.text)!=null?Co:A.delta)!=null?In:A.message)!=null?Go:"";ie&&(Z.chunks=(Gr=Z.chunks)!=null?Gr:[],Z.chunks.push(String(ie))),Z.status="running",M.toolCall=Z,M.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(M.agentMetadata=(Fn=M.agentMetadata)!=null?Fn:{executionId:(Wr=G==null?void 0:G.executionId)!=null?Wr:A.executionId,iteration:(St=G==null?void 0:G.iteration)!=null?St:A.iteration}),f(M)}else if(Je==="tool_complete"){let j=(Sn=($n=ae(A,!1))!=null?$n:ae(A,!0))!=null?Sn:`tool-${l()}`;if(J.has(j)){J.delete(j);continue}let M=Se(j),Z=(Lt=M.toolCall)!=null?Lt:{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=ze((nr=A.completedAt)!=null?nr:A.timestamp);let ie=(rr=A.duration)!=null?rr:A.executionTime;if(typeof ie=="number")Z.durationMs=ie;else{let Fe=(_n=Z.startedAt)!=null?_n:Date.now();Z.durationMs=Math.max(0,((Xr=Z.completedAt)!=null?Xr:Date.now())-Fe)}M.toolCall=Z,M.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(M.agentMetadata=(jn=M.agentMetadata)!=null?jn:{executionId:(Rr=G==null?void 0:G.executionId)!=null?Rr:A.executionId,iteration:(Qr=G==null?void 0:G.iteration)!=null?Qr:A.iteration}),f(M);let ke=se(A);ke&&I.byCall.delete(ke)}else if(Je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let j=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,M=(Dt=j!=null?j:A.toolId)!=null?Dt:`local-${l()}`,Z=Se(M),ie=A.toolName,G=po(ie),ke=(Tn=Z.toolCall)!=null?Tn:{id:M,status:"pending"};ke.name=ie,ke.args=A.parameters,ke.status=G?"running":"complete",ke.chunks=(or=ke.chunks)!=null?or:[],ke.startedAt=(Hr=ke.startedAt)!=null?Hr:ze((Yr=A.startedAt)!=null?Yr:A.timestamp),G?(ke.completedAt=void 0,ke.duration=void 0,ke.durationMs=void 0):ke.completedAt=(Zr=ke.completedAt)!=null?Zr:ke.startedAt,Z.toolCall=ke,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(Un=A.executionId)!=null?Un:(Mr=Z.agentMetadata)==null?void 0:Mr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},f(Z)}else if(Je==="text_start"){if((hr=A.toolContext)!=null&&hr.toolId)continue;let j=A.partId;if(j!==void 0&&w.current!==null&&j!==w.current){let M=m;M&&(M.streaming=!1,f(M),oe=M,m=null,T=!0)}j!==void 0&&(w.current=j)}else if(Je==="text_end"){if((xt=A.toolContext)!=null&&xt.toolId)continue;let j=m;j&&(j.streaming=!1,f(j),oe=j,m=null,T=!0)}else if(Je==="step_chunk"||Je==="step_delta"){let j=A.stepType,M=A.executionType;if(j==="tool"||M==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Yt=(Qt=A.id)!=null?Qt:Z.stepId)!=null?Yt:`step-${l()}`),dt=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Xe=`${Z.toolId}::${Fe}`,Qe=W.get(Xe);if(dt!==""&&Qe!==void 0&&Qe!==""&&Qe!==dt){let Pt=P.get($(Z.toolId,Fe,Qe));Pt&&Pt.streaming!==!1&&(Pt.streaming=!1,f(Pt))}dt!==""&&W.set(Xe,dt);let tt=R(Z.toolId,Fe,dt,Z.executionId),Zt=(br=(sr=(eo=(qn=A.text)!=null?qn:A.delta)!=null?eo:A.content)!=null?sr:A.chunk)!=null?br:"";Zt&&(tt.content+=String(Zt),tt.streaming=!0,f(tt)),A.isComplete&&(tt.streaming=!1,f(tt));continue}let ie=A.partId;if(ie!==void 0&&w.current!==null&&ie!==w.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),oe=Fe,m=null,T=!0)}ie!==void 0&&(w.current=ie);let G=ie!==void 0&&(zn=me.get(ie))!=null?zn:Ce();ie!==void 0&&(G.partId||(G.partId=ie),me.set(ie,G));let ke=(Vn=(ye=(ar=(_=A.text)!=null?_:A.delta)!=null?ar:A.content)!=null?ye:A.chunk)!=null?Vn:"";if(ke){let Fe=typeof A.seq=="number"?A.seq:void 0,dt=ie!=null?ie:G.id,Xe=Fe!==void 0?Ze(dt,Fe,String(ke)):((ir=ce.get(G.id))!=null?ir:"")+ke;G.rawContent=Xe,ne.has(G.id)||ne.set(G.id,this.createStreamParser());let Qe=ne.get(G.id),tt=Xe.trim().startsWith("{")||Xe.trim().startsWith("[");if(tt&&ce.set(G.id,Xe),Qe.__isPlainTextParser===!0){G.content=Fe!==void 0?Xe:G.content+ke,ce.delete(G.id),ne.delete(G.id),G.rawContent=void 0,f(G);continue}let Pt=Qe.processChunk(Xe);if(Pt instanceof Promise)Pt.then(Bt=>{var bn;let cn=typeof Bt=="string"?Bt:(bn=Bt==null?void 0:Bt.text)!=null?bn:null;if(cn!==null&&cn.trim()!=="")G.content=cn,f(G);else if(!tt&&!Xe.trim().startsWith("<")){let hn=m,rn=hn&&hn.id===G.id?hn:G;rn.id===G.id&&(rn.content=Fe!==void 0?Xe:rn.content+ke,ce.delete(rn.id),ne.delete(rn.id),rn.rawContent=void 0,f(rn))}}).catch(()=>{G.content=Fe!==void 0?Xe:G.content+ke,ce.delete(G.id),ne.delete(G.id),G.rawContent=void 0,f(G)});else{let Bt=typeof Pt=="string"?Pt:(yr=Pt==null?void 0:Pt.text)!=null?yr:null;Bt!==null&&Bt.trim()!==""?(G.content=Bt,f(G)):!tt&&!Xe.trim().startsWith("<")&&(G.content=Fe!==void 0?Xe:G.content+ke,ce.delete(G.id),ne.delete(G.id),G.rawContent=void 0,f(G))}}if(A.isComplete){let Fe=(xr=(Ts=A.result)==null?void 0:Ts.response)!=null?xr:G.content;if(Fe){let dt=ce.get(G.id),Xe=dt!=null?dt:Y(Fe);G.rawContent=Xe;let Qe=ne.get(G.id),tt=null,Zt=!1;if(Qe&&(tt=Qe.getExtractedText(),tt===null&&(tt=No(Xe)),tt===null)){let Pt=Qe.processChunk(Xe);Pt instanceof Promise?(Zt=!0,Pt.then(Bt=>{var bn;let cn=typeof Bt=="string"?Bt:(bn=Bt==null?void 0:Bt.text)!=null?bn:null;if(cn!==null){let hn=m;hn&&hn.id===G.id&&(hn.content=cn,hn.streaming=!1,ne.delete(hn.id),ce.delete(hn.id),f(hn))}})):tt=typeof Pt=="string"?Pt:(vr=Pt==null?void 0:Pt.text)!=null?vr:null}if(!Zt){tt!==null&&tt.trim()!==""?G.content=tt:ce.has(G.id)||(G.content=Y(Fe));let Pt=ne.get(G.id);if(Pt){let Bt=(wr=Pt.close)==null?void 0:wr.call(Pt);Bt instanceof Promise&&Bt.catch(()=>{}),ne.delete(G.id)}ce.delete(G.id),G.streaming=!1,f(G)}}}}else if(Je==="step_complete"){let j=A.stepType,M=A.executionType;if(j==="tool"||M==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Ao=(Br=A.id)!=null?Br:Z.stepId)!=null?Ao:"");if(Fe){let dt=D(Z.toolId,Fe);for(let[Xe,Qe]of P)Xe.startsWith(dt)&&Qe.streaming!==!1&&(Qe.streaming=!1,f(Qe));W.delete(`${Z.toolId}::${Fe}`)}continue}let ie=A.stopReason;if(T){if(m!==null){let Xe=m;ie&&(Xe.stopReason=ie),ne.delete(Xe.id),ce.delete(Xe.id),Xe.streaming!==!1&&(Xe.streaming=!1,f(Xe))}let Fe=(va=A.result)==null?void 0:va.response,dt=oe;dt&&(ie&&(dt.stopReason=ie),Fe!=null?We(dt,Fe):(ne.delete(dt.id),ce.delete(dt.id))),oe=null;continue}let G=(Es=A.result)==null?void 0:Es.response,ke=Ce();if(ie&&(ke.stopReason=ie),G!=null){let Fe=ne.get(ke.id),dt=!1,Xe=!1;if(Fe){let Qe=Fe.getExtractedText(),tt=ce.get(ke.id),Zt=tt!=null?tt:Y(G);if(ke.rawContent=Zt,Qe!==null&&Qe.trim()!=="")ke.content=Qe,dt=!0;else{let Pt=No(Zt);if(Pt!==null)ke.content=Pt,dt=!0;else{let Bt=Fe.processChunk(Zt);if(Bt instanceof Promise)Xe=!0,Bt.then(cn=>{var hn;let bn=typeof cn=="string"?cn:(hn=cn==null?void 0:cn.text)!=null?hn:null;if(bn!==null&&bn.trim()!==""){let rn=m;rn&&rn.id===ke.id&&(rn.content=bn,rn.streaming=!1,ne.delete(rn.id),ce.delete(rn.id),f(rn))}else{let rn=Fe.getExtractedText(),cr=m;cr&&cr.id===ke.id&&(rn!==null&&rn.trim()!==""?cr.content=rn:ce.has(cr.id)||(cr.content=Y(G)),cr.streaming=!1,ne.delete(cr.id),ce.delete(cr.id),f(cr))}});else{let cn=typeof Bt=="string"?Bt:(wa=Bt==null?void 0:Bt.text)!=null?wa:null;if(cn!==null&&cn.trim()!=="")ke.content=cn,dt=!0;else{let bn=Fe.getExtractedText();bn!==null&&bn.trim()!==""&&(ke.content=bn,dt=!0)}}}}}if(!Xe){if(!ke.rawContent){let Qe=ce.get(ke.id);ke.rawContent=Qe!=null?Qe:Y(G)}if(!dt&&!ce.has(ke.id)&&(ke.content=Y(G)),Fe){let Qe=(Xo=Fe.close)==null?void 0:Xo.call(Fe);Qe instanceof Promise&&Qe.catch(()=>{})}ne.delete(ke.id),ce.delete(ke.id),ke.streaming=!1,f(ke)}}else ne.delete(ke.id),ce.delete(ke.id),ke.streaming=!1,f(ke)}else if(Je==="flow_complete"){let j=(yt=A.result)==null?void 0:yt.response;if(T){if(m!==null){let M=m;ne.delete(M.id),ce.delete(M.id),M.streaming!==!1&&(M.streaming=!1,f(M))}}else if(j!=null){let M=Ce(),Z=ce.get(M.id),ie=Z!=null?Z:Y(j);M.rawContent=ie;let G=Y(j),ke=ne.get(M.id);if(ke){let Xe=No(ie);if(Xe!==null)G=Xe;else{let Qe=ke.processChunk(ie);Qe instanceof Promise&&Qe.then(Zt=>{var Bt;let Pt=typeof Zt=="string"?Zt:(Bt=Zt==null?void 0:Zt.text)!=null?Bt:null;Pt!==null&&(M.content=Pt,M.streaming=!1,f(M))});let tt=ke.getExtractedText();tt!==null&&(G=tt)}}ne.delete(M.id),ce.delete(M.id);let Fe=G!==M.content,dt=M.streaming!==!1;Fe&&(M.content=G),M.streaming=!1,(Fe||dt)&&f(M)}else if(m!==null){let M=m;ne.delete(M.id),ce.delete(M.id),M.streaming!==!1&&(M.streaming=!1,f(M))}n({type:"status",status:"idle"})}else if(Je==="agent_start")pe={executionId:A.executionId,agentId:(Ms=A.agentId)!=null?Ms:"virtual",agentName:(lr=A.agentName)!=null?lr:"",status:"running",currentIteration:0,maxTurns:(Wn=A.maxTurns)!=null?Wn:1,startedAt:ze(A.startedAt)};else if(Je==="agent_iteration_start"){if(pe&&(pe.currentIteration=A.iteration),Ut==="separate"&&A.iteration>1){let j=m;j&&(j.streaming=!1,f(j),Pn.set(A.iteration-1,j),m=null)}}else if(Je==="agent_turn_start")v=null;else if(Je==="agent_turn_delta"){if(A.contentType==="text"){let j=Ce();j.content+=(Ca=A.delta)!=null?Ca:"",j.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:pe==null?void 0:pe.agentName},v=j,f(j)}else if(A.contentType==="thinking"){let j=(Aa=A.turnId)!=null?Aa:`agent-think-${A.iteration}`,M=Be(j);M.reasoning=(Qo=M.reasoning)!=null?Qo:{id:j,status:"streaming",chunks:[]},M.reasoning.chunks.push((Dr=A.delta)!=null?Dr:""),M.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(M)}else if(A.contentType==="tool_input"){let j=(Sa=A.toolCallId)!=null?Sa:I.lastId;if(j){let M=k.get(j);M!=null&&M.toolCall&&(M.toolCall.chunks=(So=M.toolCall.chunks)!=null?So:[],M.toolCall.chunks.push((ks=A.delta)!=null?ks:""),f(M))}}}else if(Je==="agent_turn_complete"){let j=A.turnId;if(j){let ie=B.get(j);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=ze(A.completedAt);let G=(Nr=ie.reasoning.startedAt)!=null?Nr:Date.now();ie.reasoning.durationMs=Math.max(0,((Ls=ie.reasoning.completedAt)!=null?Ls:Date.now())-G),ie.streaming=!1,f(ie)}}let M=A.stopReason,Z=m!=null?m:v;if(M&&Z!==null){let ie=A.turnId;(!ie||((to=Z.agentMetadata)==null?void 0:to.turnId)===ie)&&(Z.stopReason=M,f(Z))}}else if(Je==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let j=(no=A.toolCallId)!=null?no:`agent-tool-${l()}`;Pe(se(A),j);let M=Se(j),Z=(Ta=M.toolCall)!=null?Ta:{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=(Xi=(Ea=A.toolName)!=null?Ea:A.name)!=null?Xi:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=ze((To=A.startedAt)!=null?To:A.timestamp),M.toolCall=Z,M.streaming=!0,M.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(M)}else if(Je==="agent_tool_delta"){let j=(ro=A.toolCallId)!=null?ro:I.lastId;if(j){let M=(Ma=k.get(j))!=null?Ma:Se(j);M.toolCall&&(M.toolCall.chunks=(Ps=M.toolCall.chunks)!=null?Ps:[],M.toolCall.chunks.push((oo=A.delta)!=null?oo:""),M.toolCall.status="running",M.streaming=!0,f(M))}}else if(Je==="agent_tool_complete"){let j=(ka=A.toolCallId)!=null?ka:I.lastId;if(j){let M=(Is=k.get(j))!=null?Is:Se(j);if(M.toolCall){M.toolCall.status="complete",A.result!==void 0&&(M.toolCall.result=A.result),typeof A.executionTime=="number"&&(M.toolCall.durationMs=A.executionTime),M.toolCall.completedAt=ze((so=A.completedAt)!=null?so:A.timestamp),M.streaming=!1,f(M);let Z=se(A);Z&&I.byCall.delete(Z)}}}else if(Je==="agent_media"){let j=Array.isArray(A.media)?A.media:[],M=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let ie=Z,G=typeof ie.type=="string"?ie.type:void 0,ke=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Fe=null,dt="";if(G==="media"){let Xe=typeof ie.data=="string"?ie.data:void 0;if(!Xe)continue;dt=ke.length>0?ke:"application/octet-stream",Fe=`data:${dt};base64,${Xe}`}else if(G==="image-url"){let Xe=typeof ie.url=="string"?ie.url:void 0;if(!Xe)continue;dt=ke,Fe=Xe}else if(G==="file-url"){let Xe=typeof ie.url=="string"?ie.url:void 0;if(!Xe)continue;dt=ke,Fe=Xe}else continue;if(Fe)if(G==="image-url"||dt.startsWith("image/"))M.push({type:"image",image:Fe,...dt?{mimeType:dt}:{}});else if(dt.startsWith("audio/"))M.push({type:"audio",audio:Fe,mimeType:dt});else if(dt.startsWith("video/"))M.push({type:"video",video:Fe,mimeType:dt});else{let Xe=dt||"application/octet-stream";M.push({type:"file",data:Fe,mimeType:Xe,filename:Jg(Xe)})}}if(M.length>0){let Z=l(),ie=A.toolCallId,ke={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:M,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(ke);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,x.current=null}}else if(Je!=="agent_iteration_complete"){if(Je==="agent_reflection"||Je==="agent_reflect"){let j=`agent-reflection-${A.executionId}-${A.iteration}`,M={id:j,role:"assistant",content:(Ws=A.reflection)!=null?Ws:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(La=A.reflection)!=null?La:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(M)}else if(Je==="agent_complete"){pe&&(pe.status=A.success?"complete":"error",pe.completedAt=ze(A.completedAt),pe.stopReason=A.stopReason);let j=m;j&&(j.streaming=!1,f(j)),n({type:"status",status:"idle"})}else if(Je==="agent_error"){let j=typeof A.error=="string"?A.error:(Pa=(Or=A.error)==null?void 0:Or.message)!=null?Pa:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):n({type:"error",error:new Error(j)})}else if(Je!=="agent_ping"){if(Je==="agent_approval_start"){let j=(ao=A.approvalId)!=null?ao:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Nt=pe==null?void 0:pe.agentId)!=null?Nt:"virtual",executionId:(Zo=(Yo=A.executionId)!=null?Yo:pe==null?void 0:pe.executionId)!=null?Zo:"",toolName:(Rs=A.toolName)!=null?Rs:"",toolType:A.toolType,description:(Ia=A.description)!=null?Ia:`Execute ${(kr=A.toolName)!=null?kr:"tool"}`,parameters:A.parameters}};f(M)}else if(Je==="step_await"&&A.awaitReason==="approval_required"){let j=(Hs=A.approvalId)!=null?Hs:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Bs=pe==null?void 0:pe.agentId)!=null?Bs:"virtual",executionId:(es=(Wa=A.executionId)!=null?Wa:pe==null?void 0:pe.executionId)!=null?es:"",toolName:(ts=A.toolName)!=null?ts:"",toolType:A.toolType,description:(Ra=A.description)!=null?Ra:`Execute ${(Eo=A.toolName)!=null?Eo:"tool"}`,parameters:A.parameters}};f(M)}else if(Je==="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:(Ha=A.decision)!=null?Ha:"approved",agentId:(Ds=pe==null?void 0:pe.agentId)!=null?Ds:"virtual",executionId:(Os=(Ns=A.executionId)!=null?Ns:pe==null?void 0:pe.executionId)!=null?Os:"",toolName:(Fs=A.toolName)!=null?Fs:"",description:(En=A.description)!=null?En:"",resolvedAt:Date.now()}};f(Z)}}else if(Je==="artifact_start"||Je==="artifact_delta"||Je==="artifact_update"||Je==="artifact_complete"){if(Je==="artifact_start"){let j=A.artifactType,M=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:M,artifactType:j,title:Z,component:typeof A.component=="string"?A.component:void 0}),de.set(M,{markdown:"",title:Z}),!V.has(M)){V.add(M);let ie={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:M,title:Z,artifactType:j,status:"streaming"}})};ue.set(M,ie),f(ie)}}else if(Je==="artifact_delta"){let j=String(A.id),M=typeof A.delta=="string"?A.delta:String((Kn=A.delta)!=null?Kn:"");n({type:"artifact_delta",id:j,artDelta:M});let Z=de.get(j);Z&&(Z.markdown+=M)}else if(Je==="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(Je==="artifact_complete"){let j=String(A.id);n({type:"artifact_complete",id:j});let M=ue.get(j);if(M){M.streaming=!1;try{let Z=JSON.parse((Fr=M.rawContent)!=null?Fr:"{}");if(Z.props){Z.props.status="complete";let ie=de.get(j);ie!=null&&ie.markdown&&(Z.props.markdown=ie.markdown)}M.rawContent=JSON.stringify(Z)}catch{}de.delete(j),f(M),ue.delete(j)}}}else if(Je==="transcript_insert"){let j=A.message;if(!j||typeof j!="object")continue;let M=String((ct=j.id)!=null?ct:`msg-${l()}`),Z=j.role,G={id:M,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(f(G),G.rawContent)try{let ke=JSON.parse(G.rawContent),Fe=($s=ke==null?void 0:ke.props)==null?void 0:$s.artifactId;typeof Fe=="string"&&V.add(Fe)}catch{}m=null,x.current=null,ne.delete(M),ce.delete(M)}else if(Je==="error"||Je==="step_error"||Je==="dispatch_error"||Je==="flow_error"){let j=null;if(A.error instanceof Error)j=A.error;else if(Je==="dispatch_error"){let M=(Mo=A.message)!=null?Mo:A.error;M!=null&&M!==""&&(j=new Error(String(M)))}else if(Je==="step_error"||Je==="flow_error"){let M=A.error;typeof M=="string"&&M!==""?j=new Error(M):M!=null&&typeof M=="object"&&"message"in M&&(j=new Error(String((Cr=M.message)!=null?Cr:M)))}else Je==="error"&&A.error!=null&&A.error!==""&&(j=new Error(String(A.error)));if(j){n({type:"error",error:j});let M=m;M&&M.streaming&&(M.streaming=!1,f(M)),n({type:"status",status:"idle"})}}}}}fe.length=0};;){let{done:F,value:Ee}=await s.read();if(F)break;a+=o.decode(Ee,{stream:!0});let De=a.split(`
10
10
 
11
- `);a=(Bn=Ne.pop())!=null?Bn:"";for(let Fe of Ne){let Ue=Fe.split(`
12
- `),pt="message",ot="";for(let z of Ue)z.startsWith("event:")?pt=z.replace("event:","").trim():z.startsWith("data:")&&(ot+=z.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(z){n({type:"error",error:z instanceof Error?z:new Error("Failed to parse chat stream payload")});continue}let Ut=pt!=="message"?pt:(Yn=St.type)!=null?Yn:"message";if((ze=this.onSSEEvent)==null||ze.call(this,Ut,St),this.parseSSEEvent){x.current=u;let z=await this.handleCustomSSEEvent(St,n,x,g,l,w);if(x.current&&x.current!==u&&(u=x.current),z)continue}pe.push(Ut,St),je()}}pe.flushPending(),je(),pe.destroy()}};function lu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function os(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Bo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function cu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function du(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function pu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function uu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function qs(e){return{type:"text",text:e}}function mu(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 gu(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 fu(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 hu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],jg=["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"],Or=[...hu,...jg];function Ug(e){return hu.includes(e)||e.startsWith("image/")}function Xa(e){return Ug(e.type)}async function yu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Xa(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 bu(e,t=Or,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 qg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function xu(e,t){let n=qg(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 Qa=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 Ya=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 p=0;p<a.length;p++)i+=a[p]*a[p];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 Ya;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 p=`${o}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let v=!1,x=E=>{v||(v=!0,clearTimeout(w),u(new Error(E)))},w=setTimeout(()=>x("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",E=>{if(!E.wasClean&&!v){let B=E.code!==1006?` (code ${E.code})`:"";x("WebSocket connection failed"+B+"."+m)}},{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 Qa(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(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),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 Do=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 No(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(!Do.isSupported())throw new Error("Browser speech recognition not supported");return new Do(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Za(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return No({type:"runtype",runtype:e.runtype});if(Do.isSupported())return No({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 Za(e),!0}catch{return!1}}function vu(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}
11
+ `);a=(Bn=De.pop())!=null?Bn:"";for(let Ne of De){let _e=Ne.split(`
12
+ `),mt="message",at="";for(let z of _e)z.startsWith("event:")?mt=z.replace("event:","").trim():z.startsWith("data:")&&(at+=z.replace("data:","").trim());if(!at)continue;let It;try{It=JSON.parse(at)}catch(z){n({type:"error",error:z instanceof Error?z:new Error("Failed to parse chat stream payload")});continue}let Kt=mt!=="message"?mt:(er=It.type)!=null?er:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,Kt,It),this.parseSSEEvent){x.current=m;let z=await this.handleCustomSSEEvent(It,n,x,f,l,w);if(x.current&&x.current!==m&&(m=x.current),z)continue}he.push(Kt,It),$e()}}he.flushPending(),$e(),he.destroy()}};function mu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function cs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Xa="[Image]";function gu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function fu(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function hu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function bu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Js(e){return{type:"text",text:e}}function yu(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 xu(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 vu(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 wu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Qg=["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"],Ur=[...wu,...Qg];function Yg(e){return wu.includes(e)||e.startsWith("image/")}function Qa(e){return Yg(e.type)}async function Cu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Qa(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 Au(e,t=Ur,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 Zg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Su(e,t){let n=Zg(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 Ya=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 Za=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 p=0;p<a.length;p++)i+=a[p]*a[p];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 Gs=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 Za;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 p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" 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=T=>{v||(v=!0,clearTimeout(w),m(new Error(T)))},w=setTimeout(()=>x("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!v){let B=T.code!==1006?` (code ${T.code})`:"";x("WebSocket connection failed"+B+"."+u)}},{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 Ya(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 p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),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 $o=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 _o(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Gs(e.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ei(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return _o({type:"runtype",runtype:e.runtype});if($o.isSupported())return _o({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Xs(e){try{return ei(e),!0}catch{return!1}}function Tu(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}
13
13
 
14
- _Details: ${n.message}_`:r}var Ks=e=>({isError:!0,content:[{type:"text",text:e}]}),Cu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ss=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 p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&ao(p.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 p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(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 Ho(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=No(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 p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,g,u,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let w=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(E=>E.role==="assistant"))==null?void 0:v.id;w&&this.ttsSpokenMessageIds.add(w)}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 p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,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,p;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:(p=t.browser)==null?void 0:p.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 Ho(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:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?os():n==="assistant"?Bo():`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},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}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:p,streaming:m=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:s==="user"?os():s==="assistant"?Bo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};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,p,m,g,u;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=os(),o=Bo(),a={id:s,role:"user",content:r||Ga,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 w=vu(v,this.config.errorMessage);if(w){let E={id:o,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Bo();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 p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=vu(l,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(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,p,m;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 g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let u=null;if(g instanceof Response){if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${g.status}`)}u=g.body}else g instanceof ReadableStream&&(u=g);u?await this.connectStream(u,{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(g){let u=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)))}}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 p,m,g,u,v,x,w,E,B,L,I,R;let r=this.messages.find(S=>S.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(g=t.toolCall)==null?void 0:g.name;if(!s||!o){(v=(u=this.callbacks).onError)==null||v.call(u,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 S=(x=t.toolCall)==null?void 0:x.args,W=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(W.length===1){let $=typeof((w=W[0])==null?void 0:w.question)=="string"?W[0].question:"";$&&(a={[$]:n})}}this.markAskUserQuestionResolved(t,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(B=t.toolCall)==null?void 0:B.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let S=typeof n=="string"?n:Object.entries(n).map(([W,$])=>`${W}: ${Array.isArray($)?$.join(", "):$}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};l.forEach((W,$)=>{let N=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!N)return;let H=S[N],j=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${$}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(s,{[o]:n});if(!S.ok){let W=await S.json().catch(()=>null);throw new Error((L=W==null?void 0:W.error)!=null?L:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let W=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(R=(I=this.callbacks).onError)==null||R.call(I,S instanceof Error?S:new Error(String(S)))}}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)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,s=Date.now()){this.messages.some(o=>o.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async m=>{var I,R,S,W,$,N,H;let g=(I=m.toolCall)==null?void 0:I.name,u=(R=m.toolCall)==null?void 0:R.id;if(!g||!u)return null;let v=`${t}:${u}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return null;this.webMcpInflightKeys.add(v),r.push(v);let x=this.markWebMcpToolRunning(m),w=new AbortController;this.webMcpResolveControllers.add(w),s.push(w);let E=(W=(S=m.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?W:g,B=this.client.executeWebMcpToolCall(g,($=m.toolCall)==null?void 0:$.args,w.signal),L;if(!B)L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{L=await B}catch(j){let V=j instanceof Error&&(j.name==="AbortError"||j.message.includes("aborted")||j.message.includes("abort"));return V||(H=(N=this.callbacks).onError)==null||H.call(N,j instanceof Error?j:new Error(String(j))),this.markWebMcpToolComplete(m,Ks(V?"Aborted by cancel()":Cu(j)),x),this.webMcpInflightKeys.delete(v),null}return w.signal.aborted?(this.markWebMcpToolComplete(m,Ks("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:E,output:L,toolMessage:m,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=a.filter(u=>u!==null),i.length===0)return;let m={};for(let u of i)m[u.resumeKey]=u.output;let g=await this.client.resumeFlow(t,m,{signal:o.signal});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error((d=u==null?void 0:u.error)!=null?d:`Resume failed: ${g.status}`)}for(let u of i)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(m){if(!(m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,m instanceof Error?m:new Error(String(m)));else for(let u of i)this.markWebMcpToolComplete(u.toolMessage,Ks("Aborted by cancel()"),u.startedAt)}finally{for(let m of r)this.webMcpInflightKeys.delete(m);for(let m of s)this.webMcpResolveControllers.delete(m);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,v,x,w,E,B,L,I,R,S,W,$;let n=(u=t.agentMetadata)==null?void 0:u.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(x=t.toolCall)==null?void 0:x.id;if(!n){(E=(w=this.callbacks).onError)==null||E.call(w,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let N=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(N)||this.webMcpResolvedKeys.has(N))return;this.webMcpInflightKeys.add(N);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(N)}catch(H){(L=(B=this.callbacks).onError)==null||L.call(B,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(N)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(I=t.toolCall)==null?void 0:I.args,p=this.client.executeWebMcpToolCall(r,l,d),m="execute",g=a;try{let N;if(p?N=await p:N={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ks("Aborted by cancel()"),a);return}let H=(S=(R=t.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?S:r;m="resume",await this.resumeWithToolOutput(n,H,N,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,N,a,g)},signal:d})}catch(N){let H=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));(m==="execute"||H||d.aborted)&&this.markWebMcpToolComplete(t,Ks(H||d.aborted?"Aborted by cancel()":Cu(N)),a),H||($=(W=this.callbacks).onError)==null||$.call(W,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),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.client.resetClientToolsFingerprint(),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 p,m,g,u,v,x,w,E,B,L;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&ao(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let I=`${d}:${l}`,R=this.webMcpInflightKeys.has(I),S=this.webMcpResolvedKeys.has(I),W=(x=s.toolCall)==null?void 0:x.name,$=((w=s.agentMetadata)==null?void 0:w.executionId)===d&&((E=s.toolCall)==null?void 0:E.id)===l&&W!==void 0&&ao(W)&&((B=s.toolCall)==null?void 0:B.status)==="complete";(R||S||$)&&(a.agentMetadata={...(L=a.agentMetadata)!=null?L:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}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},Tr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var C=require("lucide"),zg={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},be=(e,t=24,n="currentColor",r=2)=>{let s=zg[e];return s?Vg(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 Vg(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,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var ei={allowedTypes:Or,maxFileSize:10*1024*1024,maxFiles:4};function Kg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Jg(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 Fo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ei.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ei.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:ei.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:ei.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 p=bu(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,m);continue}try{let m=await yu(l),g=Xa(l)?URL.createObjectURL(l):null,u={id:Kg(),file:l,previewUrl:g,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}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=Xa(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=Jg(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=xu(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 wu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Js(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];wu(o)&&wu(s)?n[r]=Js(o,s):n[r]=s}return n}var Xn="min(440px, calc(100vw - 24px))",ti="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 Au(e,t){if(!(!e&&!t))return e?t?Js(e,t):e:t}function ni(e){var t,n,r,s,o,a,i,d,l,p,m,g,u,v,x,w,E,B,L,I,R;return e?{...Nt,...e,theme:Au(Nt.theme,e.theme),darkTheme:Au(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 xe,Pe,De,te,Ie,K,ce,Ce;let S=(xe=Nt.features)==null?void 0:xe.artifacts,W=(Pe=e.features)==null?void 0:Pe.artifacts,$=(De=Nt.features)==null?void 0:De.scrollToBottom,N=(te=e.features)==null?void 0:te.scrollToBottom,H=(Ie=Nt.features)==null?void 0:Ie.streamAnimation,j=(K=e.features)==null?void 0:K.streamAnimation,V=(ce=Nt.features)==null?void 0:ce.askUserQuestion,se=(Ce=e.features)==null?void 0:Ce.askUserQuestion,He=S===void 0&&W===void 0?void 0:{...S,...W,layout:{...S==null?void 0:S.layout,...W==null?void 0:W.layout}},qe=$===void 0&&N===void 0?void 0:{...$,...N},Oe=H===void 0&&j===void 0?void 0:{...H,...j},fe=V===void 0&&se===void 0?void 0:{...V,...se,styles:{...V==null?void 0:V.styles,...se==null?void 0:se.styles}};return{...Nt.features,...e.features,...qe!==void 0?{scrollToBottom:qe}:{},...He!==void 0?{artifacts:He}:{},...Oe!==void 0?{streamAnimation:Oe}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),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:{...(m=(p=Nt.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(g=e.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(E=(w=e.layout)==null?void 0:w.messages)==null?void 0:E.timestamp}},slots:{...(B=Nt.layout)==null?void 0:B.slots,...(L=e.layout)==null?void 0:L.slots}},markdown:{...Nt.markdown,...e.markdown,options:{...(I=Nt.markdown)==null?void 0:I.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Nt.messageActions,...e.messageActions}}:Nt}var el={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"}},tl={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"}},nl={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:ti,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 as(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."))?as(e,r):r}function ri(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=as(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 rl(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 Su(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]=Su(o,s):n[r]=s}return n}function Gg(e,t){return t?Su(e,t):e}function is(e,t={}){var s,o,a,i,d,l,p,m,g,u,v,x,w;let n={palette:el,semantic:tl,components:nl},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,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.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,...(w=e==null?void 0:e.semantic)==null?void 0:w.typography}},components:Gg(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=rl(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(B=>B.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)r=E.transform(r);return r}function oi(e){var x,w,E,B,L,I,R,S,W,$,N,H,j,V,se,He,qe,Oe,fe,xe,Pe,De,te,Ie,K,ce,Ce,he,we,Ke,Q,ne,ae,me,le,oe,Ye,We,de,G,je,Mt,pe,ie,kn,$t,cn,Bn,Yn,ze,O,Se,Ne,Fe,Ue,pt,ot,St,Ut,z,_t,Ze,Ft,re,ge,Ct,qt,en,yn,Tt,wt,ht,bt,Vt,nt,Dn,Zn,bn,Nn,mt,vr,Fn,bo,Ln,zo,zr,Mr,xt,On,$n,xn,Pt,er,tr,_n,Vr,kr,Kr,jn,Rt,vn,nr,Jr,Lr,Gr,Cr,Un,dr,ft,Gt,Xt,qn,Xr,rr,pr,zn;let t=ri(e),n={};for(let[T,Vn]of Object.entries(t)){let ur=T.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"]=(w=n["--persona-semantic-colors-secondary"])!=null?w:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(E=n["--persona-semantic-colors-accent"])!=null?E:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(B=n["--persona-semantic-colors-surface"])!=null?B:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(L=n["--persona-semantic-colors-background"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(I=n["--persona-semantic-colors-container"])!=null?I:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(R=n["--persona-semantic-colors-text"])!=null?R:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(S=n["--persona-semantic-colors-text-muted"])!=null?S:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(W=n["--persona-semantic-colors-text-inverse"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-border"]=($=n["--persona-semantic-colors-border"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(N=n["--persona-semantic-colors-divider"])!=null?N:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(V=n["--persona-components-voice-processing-icon"])!=null?V:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(se=n["--persona-components-voice-speaking-icon"])!=null?se:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(He=n["--persona-components-approval-requested-background"])!=null?He:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(qe=n["--persona-components-approval-requested-border"])!=null?qe: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"]=(fe=n["--persona-components-approval-approve-background"])!=null?fe:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(xe=n["--persona-components-approval-deny-background"])!=null?xe:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Pe=n["--persona-components-attachment-image-background"])!=null?Pe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(De=n["--persona-components-attachment-image-border"])!=null?De:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(te=n["--persona-semantic-typography-fontFamily"])!=null?te:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Ie=n["--persona-semantic-typography-fontSize"])!=null?Ie: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"]=(ce=n["--persona-semantic-typography-lineHeight"])!=null?ce: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"]=(Ce=n["--persona-palette-radius-sm"])!=null?Ce:"0.125rem",n["--persona-radius-md"]=(he=n["--persona-palette-radius-md"])!=null?he:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(Ke=n["--persona-palette-radius-xl"])!=null?Ke:"0.75rem",n["--persona-radius-full"]=(Q=n["--persona-palette-radius-full"])!=null?Q:"9999px",n["--persona-launcher-radius"]=(ae=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?ae:"9999px",n["--persona-launcher-bg"]=(me=n["--persona-components-launcher-background"])!=null?me:n["--persona-primary"],n["--persona-launcher-fg"]=(le=n["--persona-components-launcher-foreground"])!=null?le:n["--persona-text-inverse"],n["--persona-launcher-border"]=(oe=n["--persona-components-launcher-border"])!=null?oe: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"]=(We=n["--persona-components-button-primary-foreground"])!=null?We:n["--persona-text-inverse"],n["--persona-button-radius"]=(G=(de=n["--persona-components-button-primary-borderRadius"])!=null?de:n["--persona-palette-radius-full"])!=null?G:"9999px",n["--persona-panel-radius"]=(Mt=(je=n["--persona-components-panel-borderRadius"])!=null?je:n["--persona-radius-xl"])!=null?Mt:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(kn=(ie=n["--persona-components-panel-shadow"])!=null?ie:n["--persona-palette-shadows-xl"])!=null?kn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(cn=($t=n["--persona-components-input-borderRadius"])!=null?$t: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"]=(O=(ze=n["--persona-components-message-assistant-borderRadius"])!=null?ze:n["--persona-radius-lg"])!=null?O:"0.5rem",n["--persona-header-bg"]=(Se=n["--persona-components-header-background"])!=null?Se:n["--persona-surface"],n["--persona-header-border"]=(Ne=n["--persona-components-header-border"])!=null?Ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Fe=n["--persona-components-header-iconBackground"])!=null?Fe:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ue=n["--persona-components-header-iconForeground"])!=null?Ue:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(pt=n["--persona-components-header-titleForeground"])!=null?pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(ot=n["--persona-components-header-subtitleForeground"])!=null?ot:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(St=n["--persona-components-header-actionIconForeground"])!=null?St:n["--persona-muted"];let r=(Ut=e.components)==null?void 0:Ut.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(z=e.components)==null?void 0:z.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ze=n["--persona-components-introCard-borderRadius"])!=null?Ze:"1rem",n["--persona-intro-card-padding"]=(Ft=n["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",n["--persona-intro-card-shadow"]=(ge=(re=s==null?void 0:s.shadow)!=null?re:n["--persona-components-introCard-shadow"])!=null?ge:"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"]=(qt=n["--persona-components-input-placeholder"])!=null?qt: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"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(ht=n["--persona-components-message-assistant-text"])!=null?ht:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Vt=n["--persona-components-message-assistant-shadow"])!=null?Vt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Dn=(nt=n["--persona-components-scrollToBottom-background"])!=null?nt:n["--persona-button-primary-bg"])!=null?Dn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?bn: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"]=(bo=(Fn=(vr=n["--persona-components-scrollToBottom-borderRadius"])!=null?vr:n["--persona-button-radius"])!=null?Fn:n["--persona-radius-full"])!=null?bo:"9999px",n["--persona-scroll-to-bottom-shadow"]=(zo=(Ln=n["--persona-components-scrollToBottom-shadow"])!=null?Ln:n["--persona-palette-shadows-sm"])!=null?zo:"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"]=(On=(xt=n["--persona-components-scrollToBottom-fontSize"])!=null?xt:n["--persona-palette-typography-fontSize-sm"])!=null?On:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($n=n["--persona-components-scrollToBottom-iconSize"])!=null?$n:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Pt=n["--persona-components-reasoningBubble-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(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"]=(vn=n["--persona-components-markdown-table-headerBackground"])!=null?vn: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"]=(Cr=n["--persona-components-markdown-blockquote-textColor"])!=null?Cr: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"]=(ft=n["--persona-components-collapsibleWidget-border"])!=null?ft:n["--persona-border"],n["--persona-message-border"]=(Gt=n["--persona-components-message-border"])!=null?Gt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let T=v.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Xt=n["--persona-dropdown-bg"])!=null?Xt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Xr=n["--persona-dropdown-shadow"])!=null?Xr:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(rr=n["--persona-dropdown-radius"])!=null?rr:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(pr=n["--persona-dropdown-item-hover-bg"])!=null?pr:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(v!=null&&v.tab){let T=v.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(v!=null&&v.pane){let T=v.pane;if(T.toolbarBackground){let Vn=(zn=as(e,T.toolbarBackground))!=null?zn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Vn}}return n}var Tu={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 Xg={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"}}},Eu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Gs=()=>{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"},Qg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Gs()},ol=e=>Qg(e),Yg=e=>is(e),Zg=e=>{var n;let t=is(void 0,{validate:!1});return is({...e,palette:{...t.palette,colors:{...Xg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ls=e=>{let t=ol(e),n=Eu(e==null?void 0:e.theme),r=Eu(e==null?void 0:e.darkTheme);return t==="dark"?Zg(Js(n!=null?n:{},r!=null?r:{})):Yg(n)},ef=e=>oi(e),io=(e,t)=>{var o;let n=ls(t),r=ef(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)},si=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Gs())});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(Gs());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 Mu=require("idiomorph"),ai=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Mu.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 ii={index:-1,draft:""};function ku(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:{...ii}}}function Lu(e,t){var n,r,s,o,a,i,d,l,p,m,g,u,v,x,w,E,B,L,I,R,S,W,$,N,H,j,V,se,He,qe,Oe,fe,xe,Pe,De,te,Ie,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,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(v=(u=e.toolCall)==null?void 0:u.status)!=null?v:"",(w=(x=e.toolCall)==null?void 0:x.name)!=null?w:"",(L=(B=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:B.length)!=null?L:0,(W=(S=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?W:"",typeof(($=e.toolCall)==null?void 0:$.args)=="string"?e.toolCall.args.length:(N=e.toolCall)!=null&&N.args?JSON.stringify(e.toolCall.args).length:0,(V=(j=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:j.length)!=null?V:0,(Oe=(qe=(He=(se=e.reasoning)==null?void 0:se.chunks)==null?void 0:He[e.reasoning.chunks.length-1])==null?void 0:qe.length)!=null?Oe:0,(De=(Pe=(xe=(fe=e.reasoning)==null?void 0:fe.chunks)==null?void 0:xe[e.reasoning.chunks.length-1])==null?void 0:Pe.slice(-32))!=null?De:"",(Ie=(te=e.contentParts)==null?void 0:te.length)!=null?Ie:0,(K=e.stopReason)!=null?K:"",t].join("\0")}function Pu(){return new Map}function Iu(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Wu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Ru(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function li(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Qs(e,t){return Xs(e)-e.scrollTop<=t}function ci(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,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function di(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,lo=hn+1;var Ys={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},tf=["pre","code","a","script","style"],pi=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Ys.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ys.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ys.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ys.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ys.buffer}},Bu=[{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"}],Zs=new Map;for(let e of Bu)Zs.set(e.name,e);var Du=e=>{Zs.set(e.name,e)},Nu=e=>{Bu.some(t=>t.name===e)||Zs.delete(e)},Fu=()=>Array.from(Zs.keys()),ea=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Zs.get(e))!=null?r:null},ui=(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},nf=(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},rf=(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},sl=/\s/,of=(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},sf=(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(sl.test(o[i])){let l=i;for(;l<o.length&&sl.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 p=i;for(;p<o.length&&!sl.test(o[p]);)l.appendChild(nf(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},af=(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(rf(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},ta=(e,t,n,r)=>{var m,g;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:tf).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)of(d,o)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?sf:af;for(let u of i)p(u,n,l);return s.innerHTML},mi=(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},na=(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},Hu=new WeakMap,lf=(e,t)=>{var o;if(!e.styles)return;let n=Hu.get(t);if(n||(n=new Set,Hu.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)},al=new WeakMap,cf=(e,t)=>{if(!e.onAttach)return;let n=al.get(t);if(n||(n=new Map,al.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Ou=e=>{let t=al.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},il=(e,t)=>{lf(e,t),cf(e,t)};function ll(e,t=hn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var ra=0,co=null;function cl(e=document){var n;if(ra++,ra===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;co={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,ra=Math.max(0,ra-1),ra===0&&co)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=co.originalOverflow,s.style.position=co.originalPosition,s.style.top=co.originalTop,s.style.width=co.originalWidth,o.scrollTo(0,co.scrollY),co=null}}}var gi={side:"right",width:"420px",animate:!0,reveal:"resize"},rn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},po=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:gi.side,width:(s=t==null?void 0:t.width)!=null?s:gi.width,animate:(o=t==null?void 0:t.animate)!=null?o:gi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:gi.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 oa=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:r}var Qs=e=>({isError:!0,content:[{type:"text",text:e}]}),Eu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ds=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 p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&po(p.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 p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(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 Oo(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 Xs((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=_o(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 p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,u,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&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.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 w=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:v.id;w&&this.ttsSpokenMessageIds.add(w)}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 p,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,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,p;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:(p=t.browser)==null?void 0:p.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 Oo(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:p,rawContent:u}=t,m={id:a!=null?a:n==="user"?cs():n==="assistant"?Fo():`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},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};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:p,streaming:u=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:s==="user"?cs():s==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...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,p,u,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=cs(),o=Fo(),a={id:s,role:"user",content:r||Xa,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 w=Tu(v,this.config.errorMessage);if(w){let T={id:o,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,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=Fo();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 p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=Tu(l,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(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,r){var p,u,f,m,v;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===s),i={id:s,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:o};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let w=null;if(x instanceof Response){if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${x.status}`)}w=x.body}else x instanceof ReadableStream&&(w=x);w?await this.connectStream(w,{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(x){let w=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}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 p,u,f,m,v,x,w,T,B,k,P,W;let r=this.messages.find(S=>S.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(u=t.agentMetadata)==null?void 0:u.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 S=(x=t.toolCall)==null?void 0:x.args,I=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(I.length===1){let $=typeof((w=I[0])==null?void 0:w.question)=="string"?I[0].question:"";$&&(a={[$]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(B=t.toolCall)==null?void 0:B.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let S=typeof n=="string"?n:Object.entries(n).map(([I,$])=>`${I}: ${Array.isArray($)?$.join(", "):$}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};l.forEach((I,$)=>{let D=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!D)return;let R=S[D],q=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${$}`,role:"user",content:q||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(s,{[o]:n});if(!S.ok){let I=await S.json().catch(()=>null);throw new Error((k=I==null?void 0:I.error)!=null?k:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let I=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(W=(P=this.callbacks).onError)==null||W.call(P,S instanceof Error?S:new Error(String(S)))}}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)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,s=Date.now()){this.messages.some(o=>o.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var P,W,S,I,$,D,R;let f=(P=u.toolCall)==null?void 0:P.name,m=(W=u.toolCall)==null?void 0:W.id;if(!f||!m)return null;let v=`${t}:${m}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return null;this.webMcpInflightKeys.add(v),r.push(v);let x=this.markWebMcpToolRunning(u),w=new AbortController;this.webMcpResolveControllers.add(w),s.push(w);let T=(I=(S=u.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?I:f,B=this.client.executeWebMcpToolCall(f,($=u.toolCall)==null?void 0:$.args,w.signal),k;if(!B)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await B}catch(q){let K=q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")||q.message.includes("abort"));return K||(R=(D=this.callbacks).onError)==null||R.call(D,q instanceof Error?q:new Error(String(q))),this.markWebMcpToolComplete(u,Qs(K?"Aborted by cancel()":Eu(q)),x),this.webMcpInflightKeys.delete(v),null}return w.signal.aborted?(this.markWebMcpToolComplete(u,Qs("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:k,toolMessage:u,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=a.filter(m=>m!==null),i.length===0)return;let u={};for(let m of i)u[m.resumeKey]=m.output;let f=await this.client.resumeFlow(t,u,{signal:o.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${f.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,u instanceof Error?u:new Error(String(u)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,Qs("Aborted by cancel()"),m.startedAt)}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 m,v,x,w,T,B,k,P,W,S,I,$;let n=(m=t.agentMetadata)==null?void 0:m.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(x=t.toolCall)==null?void 0:x.id;if(!n){(T=(w=this.callbacks).onError)==null||T.call(w,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let D=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(D)||this.webMcpResolvedKeys.has(D))return;this.webMcpInflightKeys.add(D);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(D)}catch(R){(k=(B=this.callbacks).onError)==null||k.call(B,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(D)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(P=t.toolCall)==null?void 0:P.args,p=this.client.executeWebMcpToolCall(r,l,d),u="execute",f=a;try{let D;if(p?D=await p:D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Qs("Aborted by cancel()"),a);return}let R=(S=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?S:r;u="resume",await this.resumeWithToolOutput(n,R,D,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,D,a,f)},signal:d})}catch(D){let R=D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")||D.message.includes("abort"));(u==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(t,Qs(R||d.aborted?"Aborted by cancel()":Eu(D)),a),R||($=(I=this.callbacks).onError)==null||$.call(I,D instanceof Error?D:new Error(String(D)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),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.client.resetClientToolsFingerprint(),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 p,u,f,m,v,x,w,T,B,k;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=n.toolCall)==null?void 0:u.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(m=n.toolCall)==null?void 0:m.id;if(i&&po(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let P=`${d}:${l}`,W=this.webMcpInflightKeys.has(P),S=this.webMcpResolvedKeys.has(P),I=(x=s.toolCall)==null?void 0:x.name,$=((w=s.agentMetadata)==null?void 0:w.executionId)===d&&((T=s.toolCall)==null?void 0:T.id)===l&&I!==void 0&&po(I)&&((B=s.toolCall)==null?void 0:B.status)==="complete";(W||S||$)&&(a.agentMetadata={...(k=a.agentMetadata)!=null?k:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}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},Pr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var C=require("lucide"),ef={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},we=(e,t=24,n="currentColor",r=2)=>{let s=ef[e];return s?tf(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 tf(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,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var ti={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function nf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function rf(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 jo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ti.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ti.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:ti.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:ti.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 p=Au(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,u);continue}try{let u=await Cu(l),f=Qa(l)?URL.createObjectURL(l):null,m={id:nf(),file:l,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}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=Qa(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=rf(t.file.type),d=we(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Su(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=we("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 Mu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ys(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];Mu(o)&&Mu(s)?n[r]=Ys(o,s):n[r]=s}return n}var Yn="min(440px, calc(100vw - 24px))",ni="440px",$t={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:Yn,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 ku(e,t){if(!(!e&&!t))return e?t?Ys(e,t):e:t}function ri(e){var t,n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,T,B,k,P,W;return e?{...$t,...e,theme:ku($t.theme,e.theme),darkTheme:ku($t.darkTheme,e.darkTheme),launcher:{...$t.launcher,...e.launcher,dock:{...(t=$t.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=$t.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...$t.copy,...e.copy},sendButton:{...$t.sendButton,...e.sendButton},statusIndicator:{...$t.statusIndicator,...e.statusIndicator},voiceRecognition:{...$t.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Be,Pe,J,ue,V,de,le;let S=(be=$t.features)==null?void 0:be.artifacts,I=(Be=e.features)==null?void 0:Be.artifacts,$=(Pe=$t.features)==null?void 0:Pe.scrollToBottom,D=(J=e.features)==null?void 0:J.scrollToBottom,R=(ue=$t.features)==null?void 0:ue.streamAnimation,q=(V=e.features)==null?void 0:V.streamAnimation,K=(de=$t.features)==null?void 0:de.askUserQuestion,se=(le=e.features)==null?void 0:le.askUserQuestion,Re=S===void 0&&I===void 0?void 0:{...S,...I,layout:{...S==null?void 0:S.layout,...I==null?void 0:I.layout}},Ge=$===void 0&&D===void 0?void 0:{...$,...D},Ce=R===void 0&&q===void 0?void 0:{...R,...q},He=K===void 0&&se===void 0?void 0:{...K,...se,styles:{...K==null?void 0:K.styles,...se==null?void 0:se.styles}};return{...$t.features,...e.features,...Ge!==void 0?{scrollToBottom:Ge}:{},...Re!==void 0?{artifacts:Re}:{},...Ce!==void 0?{streamAnimation:Ce}:{},...He!==void 0?{askUserQuestion:He}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:$t.suggestionChips,suggestionChipsConfig:{...$t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...$t.layout,...e.layout,header:{...(a=$t.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=$t.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=$t.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=$t.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(w=e.layout)==null?void 0:w.messages)==null?void 0:T.timestamp}},slots:{...(B=$t.layout)==null?void 0:B.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...$t.markdown,...e.markdown,options:{...(P=$t.markdown)==null?void 0:P.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...$t.messageActions,...e.messageActions}}:$t}var ol={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"}},sl={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"}},al={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:Yn,maxWidth:ni,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:"palette.shadows.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",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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 ps(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."))?ps(e,r):r}function oi(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=ps(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 il(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 Lu(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]=Lu(o,s):n[r]=s}return n}function of(e,t){return t?Lu(e,t):e}function us(e,t={}){var s,o,a,i,d,l,p,u,f,m,v,x,w;let n={palette:ol,semantic:sl,components:al},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,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.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,...(w=e==null?void 0:e.semantic)==null?void 0:w.typography}},components:of(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=il(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(B=>B.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function si(e){var x,w,T,B,k,P,W,S,I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,Pe,J,ue,V,de,le,ae,Se,ze,Y,ne,ce,xe,me,oe,Ze,We,fe,X,$e,Ht,he,pe,Pn,Ut,gn,Bn,er,Ue,F,Ee,De,Ne,_e,mt,at,It,Kt,z,qt,et,_t,re,ve,Et,Jt,nn,Cn,Wt,kt,wt,At,Gt,ot,Dn,tr,An,Nn,bt,Er,On,Co,In,Go,Gr,Wr,St,Fn,$n,Sn,Lt,nr,rr,_n,Xr,Rr,Qr,jn,Dt,Tn,or,Yr,Hr,Zr,Mr,Un,hr,xt,Qt,Yt,qn,eo,sr,br,zn,_,ar;let t=oi(e),n={};for(let[ye,Vn]of Object.entries(t)){let ir=ye.replace(/\./g,"-");n[`--persona-${ir}`]=Vn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(w=n["--persona-semantic-colors-secondary"])!=null?w:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(B=n["--persona-semantic-colors-surface"])!=null?B:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(P=n["--persona-semantic-colors-container"])!=null?P:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(S=n["--persona-semantic-colors-text-muted"])!=null?S:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=($=n["--persona-semantic-colors-border"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(D=n["--persona-semantic-colors-divider"])!=null?D:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(q=n["--persona-components-voice-recording-background"])!=null?q:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(K=n["--persona-components-voice-processing-icon"])!=null?K:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(se=n["--persona-components-voice-speaking-icon"])!=null?se:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Re=n["--persona-components-approval-requested-background"])!=null?Re:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ge=n["--persona-components-approval-requested-border"])!=null?Ge:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ce=n["--persona-components-approval-requested-text"])!=null?Ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(He=n["--persona-components-approval-requested-shadow"])!=null?He:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(be=n["--persona-components-approval-approve-background"])!=null?be:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Be=n["--persona-components-approval-deny-background"])!=null?Be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Pe=n["--persona-components-attachment-image-background"])!=null?Pe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(J=n["--persona-components-attachment-image-border"])!=null?J:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ue=n["--persona-semantic-typography-fontFamily"])!=null?ue:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(V=n["--persona-semantic-typography-fontSize"])!=null?V:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(de=n["--persona-semantic-typography-fontWeight"])!=null?de:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(le=n["--persona-semantic-typography-lineHeight"])!=null?le: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"]=(ae=n["--persona-palette-radius-sm"])!=null?ae:"0.125rem",n["--persona-radius-md"]=(Se=n["--persona-palette-radius-md"])!=null?Se:"0.375rem",n["--persona-radius-lg"]=(ze=n["--persona-palette-radius-lg"])!=null?ze:"0.5rem",n["--persona-radius-xl"]=(Y=n["--persona-palette-radius-xl"])!=null?Y:"0.75rem",n["--persona-radius-full"]=(ne=n["--persona-palette-radius-full"])!=null?ne:"9999px",n["--persona-launcher-radius"]=(xe=(ce=n["--persona-components-launcher-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?xe:"9999px",n["--persona-launcher-bg"]=(me=n["--persona-components-launcher-background"])!=null?me:n["--persona-primary"],n["--persona-launcher-fg"]=(oe=n["--persona-components-launcher-foreground"])!=null?oe:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ze=n["--persona-components-launcher-border"])!=null?Ze:n["--persona-border"],n["--persona-button-primary-bg"]=(We=n["--persona-components-button-primary-background"])!=null?We:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=($e=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?$e:"9999px",n["--persona-panel-radius"]=(he=(Ht=n["--persona-components-panel-borderRadius"])!=null?Ht:n["--persona-radius-xl"])!=null?he:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ut=(Pn=n["--persona-components-panel-shadow"])!=null?Pn:n["--persona-palette-shadows-xl"])!=null?Ut:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(gn=n["--persona-components-launcher-shadow"])!=null?gn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(er=(Bn=n["--persona-components-input-borderRadius"])!=null?Bn:n["--persona-radius-lg"])!=null?er:"0.5rem",n["--persona-message-user-radius"]=(F=(Ue=n["--persona-components-message-user-borderRadius"])!=null?Ue:n["--persona-radius-lg"])!=null?F:"0.5rem",n["--persona-message-assistant-radius"]=(De=(Ee=n["--persona-components-message-assistant-borderRadius"])!=null?Ee:n["--persona-radius-lg"])!=null?De:"0.5rem",n["--persona-header-bg"]=(Ne=n["--persona-components-header-background"])!=null?Ne:n["--persona-surface"],n["--persona-header-border"]=(_e=n["--persona-components-header-border"])!=null?_e:n["--persona-divider"],n["--persona-header-icon-bg"]=(mt=n["--persona-components-header-iconBackground"])!=null?mt:n["--persona-primary"],n["--persona-header-icon-fg"]=(at=n["--persona-components-header-iconForeground"])!=null?at:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(It=n["--persona-components-header-titleForeground"])!=null?It:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Kt=n["--persona-components-header-subtitleForeground"])!=null?Kt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(z=n["--persona-components-header-actionIconForeground"])!=null?z:n["--persona-muted"];let r=(qt=e.components)==null?void 0:qt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(et=e.components)==null?void 0:et.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(re=n["--persona-components-introCard-borderRadius"])!=null?re:"1rem",n["--persona-intro-card-padding"]=(ve=n["--persona-components-introCard-padding"])!=null?ve:"1.5rem",n["--persona-intro-card-shadow"]=(Jt=(Et=s==null?void 0:s.shadow)!=null?Et:n["--persona-components-introCard-shadow"])!=null?Jt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(nn=n["--persona-components-input-background"])!=null?nn:n["--persona-surface"],n["--persona-input-placeholder"]=(Cn=n["--persona-components-input-placeholder"])!=null?Cn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Wt=n["--persona-components-message-user-background"])!=null?Wt:n["--persona-accent"],n["--persona-message-user-text"]=(kt=n["--persona-components-message-user-text"])!=null?kt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(wt=n["--persona-components-message-user-shadow"])!=null?wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(At=n["--persona-components-message-assistant-background"])!=null?At:n["--persona-surface"],n["--persona-message-assistant-text"]=(Gt=n["--persona-components-message-assistant-text"])!=null?Gt:n["--persona-text"],n["--persona-message-assistant-border"]=(ot=n["--persona-components-message-assistant-border"])!=null?ot:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Dn=n["--persona-components-message-assistant-shadow"])!=null?Dn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(An=(tr=n["--persona-components-scrollToBottom-background"])!=null?tr:n["--persona-button-primary-bg"])!=null?An:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bt=(Nn=n["--persona-components-scrollToBottom-foreground"])!=null?Nn:n["--persona-button-primary-fg"])!=null?bt:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Er=n["--persona-components-scrollToBottom-border"])!=null?Er:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(On=n["--persona-components-scrollToBottom-size"])!=null?On:"40px",n["--persona-scroll-to-bottom-radius"]=(Go=(In=(Co=n["--persona-components-scrollToBottom-borderRadius"])!=null?Co:n["--persona-button-radius"])!=null?In:n["--persona-radius-full"])!=null?Go:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Wr=(Gr=n["--persona-components-scrollToBottom-shadow"])!=null?Gr:n["--persona-palette-shadows-sm"])!=null?Wr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(St=n["--persona-components-scrollToBottom-padding"])!=null?St:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Fn=n["--persona-components-scrollToBottom-gap"])!=null?Fn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Sn=($n=n["--persona-components-scrollToBottom-fontSize"])!=null?$n:n["--persona-palette-typography-fontSize-sm"])!=null?Sn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Lt=n["--persona-components-scrollToBottom-iconSize"])!=null?Lt:"14px",n["--persona-tool-bubble-shadow"]=(nr=n["--persona-components-toolBubble-shadow"])!=null?nr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(rr=n["--persona-components-reasoningBubble-shadow"])!=null?rr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(_n=n["--persona-components-composer-shadow"])!=null?_n:"none",n["--persona-md-inline-code-bg"]=(Xr=n["--persona-components-markdown-inlineCode-background"])!=null?Xr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Rr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Rr:n["--persona-text"],n["--persona-md-link-color"]=(jn=(Qr=n["--persona-components-markdown-link-foreground"])!=null?Qr:n["--persona-accent"])!=null?jn:"#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"]=(Dt=n["--persona-components-markdown-codeBlock-background"])!=null?Dt:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Tn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Tn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(or=n["--persona-components-markdown-codeBlock-textColor"])!=null?or:"inherit",n["--persona-md-table-header-bg"]=(Yr=n["--persona-components-markdown-table-headerBackground"])!=null?Yr:n["--persona-container"],n["--persona-md-table-border-color"]=(Hr=n["--persona-components-markdown-table-borderColor"])!=null?Hr:n["--persona-border"],n["--persona-md-hr-color"]=(Zr=n["--persona-components-markdown-hr-color"])!=null?Zr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Mr=n["--persona-components-markdown-blockquote-borderColor"])!=null?Mr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Un=n["--persona-components-markdown-blockquote-background"])!=null?Un:"transparent",n["--persona-md-blockquote-text-color"]=(hr=n["--persona-components-markdown-blockquote-textColor"])!=null?hr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(xt=n["--persona-components-collapsibleWidget-container"])!=null?xt:n["--persona-surface"],n["--cw-surface"]=(Qt=n["--persona-components-collapsibleWidget-surface"])!=null?Qt:n["--persona-surface"],n["--cw-border"]=(Yt=n["--persona-components-collapsibleWidget-border"])!=null?Yt:n["--persona-border"],n["--persona-message-border"]=(qn=n["--persona-components-message-border"])!=null?qn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.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=p==null?void 0:p.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,n["--persona-dropdown-bg"]=(eo=n["--persona-dropdown-bg"])!=null?eo:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(sr=n["--persona-dropdown-border"])!=null?sr:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(br=n["--persona-dropdown-shadow"])!=null?br:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(zn=n["--persona-dropdown-radius"])!=null?zn:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(_=n["--persona-dropdown-item-hover-bg"])!=null?_:ye.copyMenuItemHoverBackground),ye.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(n["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(n["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(n["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(n["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(n["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(n["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let Vn=(ar=ps(e,ye.toolbarBackground))!=null?ar:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Vn}}return n}var Pu={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 sf={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"}}},Iu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Zs=()=>{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"},af=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Zs()},ll=e=>af(e),lf=e=>us(e),cf=e=>{var n;let t=us(void 0,{validate:!1});return us({...e,palette:{...t.palette,colors:{...sf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ms=e=>{let t=ll(e),n=Iu(e==null?void 0:e.theme),r=Iu(e==null?void 0:e.darkTheme);return t==="dark"?cf(Ys(n!=null?n:{},r!=null?r:{})):lf(n)},df=e=>si(e),uo=(e,t)=>{let n=ms(t),r=df(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},ai=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Zs())});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(Zs());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 Wu=require("idiomorph"),ii=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Wu.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 li={index:-1,draft:""};function Ru(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:{...li}}}function Hu(e,t){var n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,T,B,k,P,W,S,I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,Pe,J,ue,V;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(w=(x=e.toolCall)==null?void 0:x.name)!=null?w:"",(k=(B=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:B.length)!=null?k:0,(I=(S=(W=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?I:"",typeof(($=e.toolCall)==null?void 0:$.args)=="string"?e.toolCall.args.length:(D=e.toolCall)!=null&&D.args?JSON.stringify(e.toolCall.args).length:0,(K=(q=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:q.length)!=null?K:0,(Ce=(Ge=(Re=(se=e.reasoning)==null?void 0:se.chunks)==null?void 0:Re[e.reasoning.chunks.length-1])==null?void 0:Ge.length)!=null?Ce:0,(Pe=(Be=(be=(He=e.reasoning)==null?void 0:He.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Be.slice(-32))!=null?Pe:"",(ue=(J=e.contentParts)==null?void 0:J.length)!=null?ue:0,(V=e.stopReason)!=null?V:"",t].join("\0")}function Bu(){return new Map}function Du(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Nu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Ou(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ci(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ea(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ta(e,t){return ea(e)-e.scrollTop<=t}function di(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,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function pi(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 vn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,mo=wn+1;var na={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},pf=["pre","code","a","script","style"],ui=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:na.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:na.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:na.speed,duration:(s=e==null?void 0:e.duration)!=null?s:na.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:na.buffer}},$u=[{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"}],ra=new Map;for(let e of $u)ra.set(e.name,e);var _u=e=>{ra.set(e.name,e)},ju=e=>{$u.some(t=>t.name===e)||ra.delete(e)},Uu=()=>Array.from(ra.keys()),oa=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=ra.get(e))!=null?r:null},mi=(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},uf=(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},mf=(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},cl=/\s/,gf=(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},ff=(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(cl.test(o[i])){let l=i;for(;l<o.length&&cl.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 p=i;for(;p<o.length&&!cl.test(o[p]);)l.appendChild(uf(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},hf=(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(mf(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},sa=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((u=r==null?void 0:r.skipTags)!=null?u:pf).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)gf(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?ff:hf;for(let m of i)p(m,n,l);return s.innerHTML},gi=(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},aa=(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},Fu=new WeakMap,bf=(e,t)=>{var o;if(!e.styles)return;let n=Fu.get(t);if(n||(n=new Set,Fu.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)},dl=new WeakMap,yf=(e,t)=>{if(!e.onAttach)return;let n=dl.get(t);if(n||(n=new Map,dl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},qu=e=>{let t=dl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},pl=(e,t)=>{bf(e,t),yf(e,t)};function ul(e,t=wn){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 ia=0,go=null;function ml(e=document){var n;if(ia++,ia===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;go={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,ia=Math.max(0,ia-1),ia===0&&go)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=go.originalOverflow,s.style.position=go.originalPosition,s.style.top=go.originalTop,s.style.width=go.originalWidth,o.scrollTo(0,go.scrollY),go=null}}}var fi={side:"right",width:"420px",animate:!0,reveal:"resize"},ln=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},fo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},mr=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:fi.side,width:(s=t==null?void 0:t.width)!=null?s:fi.width,animate:(o=t==null?void 0:t.animate)!=null?o:fi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:fi.reveal}};var Tr={"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 la=(e,t)=>{let n=h("button");n.type="button",n.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 Ks=e=>({isError:!0,content:[{type:"text",text:e}]
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 L,I,R,S,W,$,N,H,j,V,se,He,qe,Oe;let a=(L=o.launcher)!=null?L:{},i=rn(o),d=n.querySelector("[data-role='launcher-title']");if(d){let fe=(I=a.title)!=null?I:"Chat Assistant";d.textContent=fe,d.setAttribute("title",fe)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let fe=(R=a.subtitle)!=null?R:"Get answers fast";l.textContent=fe,l.setAttribute("title",fe)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let fe=(S=a.agentIconSize)!=null?S:"40px";if(m.style.height=fe,m.style.width=fe,m.innerHTML="",a.agentIconName){let xe=parseFloat(fe)||24,Pe=be(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(m.appendChild(Pe),m.style.display=""):(m.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=($=a.agentIconText)!=null?$:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let fe=(N=a.agentIconSize)!=null?N:"40px";g.style.height=fe,g.style.width=fe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let fe=(H=a.callToActionIconSize)!=null?H:"32px";u.style.height=fe,u.style.width=fe,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Pe=parseFloat(fe)||24,De=Math.max(Pe-xe,8),te=be(a.callToActionIconName,De,"currentColor",2);te?u.appendChild(te):u.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else u.textContent=(V=a.callToActionIconText)!=null?V:"\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",w="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?w:`${x} ${v}`,i||(n.style.zIndex=String((se=a.zIndex)!=null?se:hn));let E="1px solid var(--persona-border, #e5e7eb)",B="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=(He=a.border)!=null?He:E,n.style.boxShadow=(qe=a.shadow)!=null?qe:B,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 df="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",fi=(e,t={})=>{var x,w,E,B,L,I;let{showClose:n=!0,wrapperClassName:r=df,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(w=s!=null?s:a.closeButtonSize)!=null?w:"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 p=(E=a.closeButtonTooltipText)!=null?E:"Close chat",m=(B=a.closeButtonShowTooltip)!=null?B:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let g=(L=a.closeButtonIconName)!=null?L:"x",u=(I=a.closeButtonIconText)!=null?I:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let v=be(g,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=u,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 R=a.closeButtonBorderWidth||"0px",S=a.closeButtonBorderColor||"transparent";l.style.border=`${R} solid ${S}`,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),m&&p){let R=null,S=()=>{if(R)return;let $=l.ownerDocument,N=$.body;if(!N)return;R=Tr($,"div","persona-clear-chat-tooltip"),R.textContent=p;let H=Tr($,"div");H.className="persona-clear-chat-tooltip-arrow",R.appendChild(H);let j=l.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(lo),R.style.left=`${j.left+j.width/2}px`,R.style.top=`${j.top-8}px`,R.style.transform="translate(-50%, -100%)",N.appendChild(R)},W=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",W),l.addEventListener("focus",S),l.addEventListener("blur",W),d._cleanupTooltip=()=>{W(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",W),l.removeEventListener("focus",S),l.removeEventListener("blur",W)}}return{button:l,wrapper:d}},pf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",hi=(e,t={})=>{var R,S,W,$,N,H,j,V,se,He,qe,Oe,fe;let{wrapperClassName:n=pf,buttonSize:r,iconSize:s="20px"}=t,a=(S=((R=e==null?void 0:e.launcher)!=null?R:{}).clearChat)!=null?S:{},i=(W=r!=null?r:a.size)!=null?W:"32px",d=($=a.iconName)!=null?$:"refresh-cw",l=(N=a.iconColor)!=null?N:"",p=(H=a.backgroundColor)!=null?H:"",m=(j=a.borderWidth)!=null?j:"",g=(V=a.borderColor)!=null?V:"",u=(se=a.borderRadius)!=null?se:"",v=(He=a.paddingX)!=null?He:"",x=(qe=a.paddingY)!=null?qe:"",w=(Oe=a.tooltipText)!=null?Oe:"Clear chat",E=(fe=a.showTooltip)!=null?fe:!0,B=h("div",n),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",L.setAttribute("aria-label",w),L.style.color=l||Mn.actionIconColor;let I=be(d,s,"currentColor",1);if(I&&(I.style.display="block",L.appendChild(I)),p&&(L.style.backgroundColor=p,L.classList.remove("hover:persona-bg-gray-100")),m||g){let xe=m||"0px",Pe=g||"transparent";L.style.border=`${xe} solid ${Pe}`,L.classList.remove("persona-border-none")}if(u&&(L.style.borderRadius=u,L.classList.remove("persona-rounded-full")),v&&(L.style.paddingLeft=v,L.style.paddingRight=v),x&&(L.style.paddingTop=x,L.style.paddingBottom=x),B.appendChild(L),E&&w){let xe=null,Pe=()=>{if(xe)return;let te=L.ownerDocument,Ie=te.body;if(!Ie)return;xe=Tr(te,"div","persona-clear-chat-tooltip"),xe.textContent=w;let K=Tr(te,"div");K.className="persona-clear-chat-tooltip-arrow",xe.appendChild(K);let ce=L.getBoundingClientRect();xe.style.position="fixed",xe.style.zIndex=String(lo),xe.style.left=`${ce.left+ce.width/2}px`,xe.style.top=`${ce.top-8}px`,xe.style.transform="translate(-50%, -100%)",Ie.appendChild(xe)},De=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};B.addEventListener("mouseenter",Pe),B.addEventListener("mouseleave",De),L.addEventListener("focus",Pe),L.addEventListener("blur",De),B._cleanupTooltip=()=>{De(),B.removeEventListener("mouseenter",Pe),B.removeEventListener("mouseleave",De),L.removeEventListener("focus",Pe),L.removeEventListener("blur",De)}}return{button:L,wrapper:B}};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 R,S,W,$,N,H,j,V,se,He,qe,Oe,fe,xe,Pe,De;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=(R=t==null?void 0:t.launcher)!=null?R:{},o=(S=s.headerIconSize)!=null?S:"48px",a=(W=s.closeButtonPlacement)!=null?W:"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 te=parseFloat(o)||24,Ie=be(d,te*.6,"currentColor",1);Ie?l.replaceChildren(Ie):l.textContent=(H=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?H:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let te=h("img");te.src=t.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=o,te.style.width=o,l.replaceChildren(te)}else l.textContent=(se=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?se:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=h("span","persona-text-base persona-font-semibold");m.style.color=Mn.titleColor,m.textContent=(qe=(He=t==null?void 0:t.launcher)==null?void 0:He.title)!=null?qe:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(fe=(Oe=t==null?void 0:t.launcher)==null?void 0:Oe.subtitle)!=null?fe:"Here to help you get answers fast",p.append(m,g),i?r.append(p):r.append(l,p);let u=(xe=s.clearChat)!=null?xe:{},v=(Pe=u.enabled)!=null?Pe:!0,x=(De=u.placement)!=null?De:"inline",w=null,E=null;if(v){let Ie=hi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=Ie.button,E=Ie.wrapper,x==="top-right"&&(E.style.right="48px"),x==="inline"&&r.appendChild(E)}let B=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:L,wrapper:I}=fi(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:L,closeButtonWrapper:I,clearChatButton:w,clearChatButtonWrapper:E}},Oo=(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 uo(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(lo)):(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 u of t){if(u.dividerBefore){let w=document.createElement("hr");a.appendChild(w)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let w=be(u.icon,16,"currentColor",1.5);w&&v.appendChild(w)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",w=>{w.stopPropagation(),p(),n(u.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:g}}function jt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=be(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function sa(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 p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=be(t,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function aa(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 p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=jt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=h("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function l(p){a=p,d()}return{element:o,setSelected:l}}function yi(e){var u,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 p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=be(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"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,w;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(w=d.border)!=null?w:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=uo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let w=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",w?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var dl=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 uf(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=uo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var pl=e=>{var B,L,I,R,S,W,$,N,H;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(B=t==null?void 0:t.launcher)!=null?B:{},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,p;if(d)l=yi({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(I=l.querySelector(".persona-combo-btn-label"))!=null?I:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(R=a.title)!=null?R:"Chat Assistant",l.appendChild(p),uf(l,s==null?void 0:s.trailingActions,(S=s==null?void 0:s.onAction)!=null?S:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=s.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||V()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),V())})}let j=s==null?void 0:s.titleRowHover;j&&(l.style.borderRadius=(W=j.borderRadius)!=null?W:"10px",l.style.padding=($=j.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 V,se;l.style.backgroundColor=(V=j.background)!=null?V:"",l.style.borderColor=(se=j.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(N=a.closeButtonSize)!=null?N:"32px",g=h("div",""),u=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");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||Mn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=be(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let w=h("div");w.style.display="none";let E=h("span");return E.style.display="none",{header:i,iconHolder:w,headerTitle:p,headerSubtitle:E,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},bi={default:dl,minimal:pl},ul=e=>{var t;return(t=bi[e])!=null?t:bi.default},cs=(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}),p=h("div");p.style.display="none";let m=h("span"),g=h("span"),u=h("button");u.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=ul(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 xi=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}},vi=e=>{var R,S,W,$,N,H,j,V,se,He,qe,Oe;let t=(R=e==null?void 0:e.sendButton)!=null?R:{},n=(S=t.useIcon)!=null?S:!1,r=(W=t.iconText)!=null?W:"\u2191",s=t.iconName,o=($=t.stopIconName)!=null?$:"square",a=(N=t.tooltipText)!=null?N:"Send message",i=(H=t.stopTooltipText)!=null?H:"Stop generating",d=(V=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?V:"Send",l=(He=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?He:"Stop",p=(qe=t.showTooltip)!=null?qe:!1,m=(Oe=t.size)!=null?Oe:"40px",g=t.backgroundColor,u=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 w=null,E=null;if(n){x.style.width=m,x.style.height=m,x.style.minWidth=m,x.style.minHeight=m,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",u?x.style.color=u:x.style.color="var(--persona-button-primary-fg, #ffffff)";let fe=parseFloat(m)||24,xe=(u==null?void 0:u.trim())||"currentColor";s?(w=be(s,fe,xe,2),w?x.appendChild(w):x.textContent=r):x.textContent=r,E=be(o,fe,xe,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,u?x.style.color=u: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 B=null;p&&a&&(B=h("div","persona-send-button-tooltip"),B.textContent=a,v.appendChild(B)),x.setAttribute("aria-label",a),v.appendChild(x);let L="send";return{button:x,wrapper:v,setMode:fe=>{if(fe===L)return;L=fe;let xe=fe==="stop"?i:a;if(x.setAttribute("aria-label",xe),B&&(B.textContent=xe),n){if(w&&E){let Pe=fe==="stop"?E:w;x.replaceChildren(Pe)}}else x.textContent=fe==="stop"?l:d}}},Ci=e=>{var B,L,I,R,S,W,$,N,H,j,V,se;let t=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((L=t.provider)==null?void 0:L.type)==="runtype";if(!(r||s))return null;let a=(R=(I=e==null?void 0:e.sendButton)==null?void 0:I.size)!=null?R:"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=(S=t.iconName)!=null?S:"mic",p=(W=t.iconSize)!=null?W:a,m=parseFloat(p)||24,g=(N=t.backgroundColor)!=null?N:($=e==null?void 0:e.sendButton)==null?void 0:$.backgroundColor,u=(j=t.iconColor)!=null?j:(H=e==null?void 0:e.sendButton)==null?void 0:H.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let x=be(l,m,u||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),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 w=(V=t.tooltipText)!=null?V:"Start voice recognition";if(((se=t.showTooltip)!=null?se:!1)&&w){let He=h("div","persona-send-button-tooltip");He.textContent=w,i.appendChild(He)}return{button:d,wrapper:i}},wi=e=>{var v,x,w,E,B,L,I,R;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(w=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?w:"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=((E=t.allowedTypes)!=null?E:Or).join(","),s.multiple=((B=t.maxFiles)!=null?B: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",(L=t.buttonTooltipText)!=null?L:"Attach file");let i=(I=t.buttonIconName)!=null?I:"paperclip",d=n,l=parseFloat(d)||40,p=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 m=be(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",S=>{S.preventDefault(),s.click()}),o.appendChild(a);let g=(R=t.buttonTooltipText)!=null?R:"Attach file",u=h("div","persona-send-button-tooltip");return u.textContent=g,o.appendChild(u),{button:a,wrapper:o,input:s,previewsContainer:r}},Ai=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},Si=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ds=e=>{var v,x,w,E,B,L;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=Si(),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}=xi(t);a();let i=vi(t),d=Ci(t),l=wi(t),p=Ai(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let m=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(g,u),s.append(m),s.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{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:p,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var $u=()=>{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}},_u=e=>{var v,x,w,E,B,L;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=Si();r.style.display="none";let s=Ai(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=xi(t);o.style.maxHeight="100px",a();let i=vi(t),d=Ci(t),l=wi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let g=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(m,o,g),l&&n.append(l.previewsContainer),n.append(p,r,s);let u=p;return{footer:n,suggestions:r,composerForm:p,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:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var ju=e=>{var p,m,g,u,v,x,w,E,B,L,I,R,S,W,$,N,H;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=rn(e);if(po(e)){let j=(u=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?u:{},V=h("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",V.style.zIndex=String((w=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?w:hn);let se=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",V.appendChild(se);let He=h("div","persona-widget-pill-root");return He.setAttribute("data-persona-composer-bar",""),He.dataset.state="collapsed",He.dataset.expandedSize=(E=j.expandedSize)!=null?E:"anchored",He.style.zIndex=String((L=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?L:hn),{wrapper:V,panel:se,pillRoot:He}}if(n){let j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(V),{wrapper:j,panel:V}}if(!t){let j=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?R:"100%";return j.style.width=se,V.style.width="100%",j.appendChild(V),{wrapper:j,panel:V}}let s=(S=e==null?void 0:e.launcher)!=null?S:{},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(($=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?$:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?H: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}},mf=(e,t)=>{var I,R,S,W,$,N,H,j,V;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}=fi(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=(S=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?S:!0,a=null,i=null;if(o){let se=hi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=($=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?$:"Hello \u{1F44B}";let g=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(H=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",p.append(m,g);let u=h("div","persona-flex persona-flex-col persona-gap-3"),v=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let w=h("div","persona-composer-overlay persona-pointer-events-none");w.setAttribute("data-persona-composer-overlay",""),w.style.position="absolute",w.style.left="0",w.style.right="0",w.style.bottom="0",w.style.zIndex="20";let E=_u({config:e}),{root:B,textNode:L}=$u();return n.append(d,s,l,w),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:w,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:m,introSubtitle:g,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:B,peekTextNode:L}},Uu=(e,t=!0)=>{var w,E,B,L,I,R,S,W,$;if(po(e))return mf(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=(w=e==null?void 0:e.layout)==null?void 0:w.header,s=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,o=r?cs(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=rn(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=(L=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?L:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(R=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),m=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((W=e==null?void 0:e.copy)==null?void 0:W.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=ds({config:e}),v=(($=e==null?void 0:e.layout)==null?void 0:$.showFooter)!==!1;s?Oo(n,o,e):(o.header.style.display="none",Oo(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||(u.footer.style.display="none"),n.append(u.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.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:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var gf=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}},ff=(e,t)=>{if(!e)return null;let n=gf(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},hf=(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},yf=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ml=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(":"))},gl=320,zu=320,bf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),xf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),vf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Cf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),wf=(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 m;let l=h("img");l.alt=((m=i.alt)==null?void 0:m.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=`${gl}px`,l.style.maxHeight=`${zu}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 p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),yf(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Af=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(!ml(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=`${gl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Sf=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(!ml(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=`${gl}px`,s.style.maxHeight=`${zu}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}},Tf=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(!ml(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}},$o=()=>{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},fl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:$o};if(t){let s=t(r);if(s!==null)return s}return $o()},Ef=(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},qu=(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},Mf=(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},hl=(e,t,n)=>{var u,v,x,w,E,B;let r=(u=t.showCopy)!=null?u:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let L=h("div");return L.style.display="none",L.id=`actions-${e.id}`,L.setAttribute("data-actions-for",e.id),L}let a=(w=t.visibility)!=null?w:"hover",i=(E=t.align)!=null?E:"right",d=(B=t.layout)!=null?B:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=(L,I,R)=>{let S=jt({icon:L,label:I,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",R),S};return r&&m.appendChild(g("copy","Copy message","copy")),s&&m.appendChild(g("thumbs-up","Upvote","upvote")),o&&m.appendChild(g("thumbs-down","Downvote","downvote")),m},ps=(e,t,n,r,s,o)=>{var te,Ie,K,ce,Ce,he,we,Ke,Q,ne,ae,me,le,oe,Ye,We,de;let a=n!=null?n:{},i=(te=a.layout)!=null?te:"bubble",d=a.avatar,l=a.timestamp,p=(Ie=d==null?void 0:d.show)!=null?Ie:!1,m=(K=l==null?void 0:l.show)!=null?K:!1,g=(ce=d==null?void 0:d.position)!=null?ce:"left",u=(Ce=l==null?void 0:l.position)!=null?Ce:"below",v=Mf(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 w=bf(e),E=(we=(he=e.content)==null?void 0:he.trim())!=null?we:"",L=w.length>0&&E===Ga,I=pi((Q=(Ke=o==null?void 0:o.widgetConfig)==null?void 0:Ke.features)==null?void 0:Q.streamAnimation),R=(me=(ae=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.features)==null?void 0:ae.streamAnimation)==null?void 0:me.plugins,S=e.role==="assistant"&&I.type!=="none"?ea(I.type,R):null,W=e.role==="assistant"&&((le=S==null?void 0:S.isAnimating)==null?void 0:le.call(S,e))===!0,$=e.role==="assistant"&&S!==null&&(!!e.streaming||W);$&&(S!=null&&S.bubbleClass)&&x.classList.add(S.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),$&&S&&(S.containerClass&&N.classList.add(S.containerClass),N.style.setProperty("--persona-stream-step",`${I.speed}ms`),N.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let H=$?ui((oe=e.content)!=null?oe:"",I.buffer,S,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",j=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=j;$&&(S==null?void 0:S.wrap)==="char"?V=ta(j,"char",e.id,{skipTags:S.skipTags}):$&&(S==null?void 0:S.wrap)==="word"&&(V=ta(j,"word",e.id,{skipTags:S.skipTags}));let se=null;if(L?(se=document.createElement("div"),se.innerHTML=V,se.style.display="none",N.appendChild(se)):N.innerHTML=V,$&&(S!=null&&S.useCaret)&&!L&&E){let G=mi(),je=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),Mt=je[je.length-1];if(Mt!=null&&Mt.parentNode)Mt.parentNode.insertBefore(G,Mt.nextSibling);else{let pe=N.lastElementChild;pe?pe.appendChild(G):N.appendChild(G)}}if(m&&u==="inline"&&e.createdAt){let G=qu(e,l);G.classList.add("persona-ml-2","persona-inline"),N.appendChild(G)}if(w.length>0){let G=wf(w,!L&&!!E,()=>{L&&se&&(se.style.display="")});G?x.appendChild(G):L&&se&&(se.style.display="")}let He=xf(e);if(He.length>0){let G=Af(He);G&&x.appendChild(G)}let qe=vf(e);if(qe.length>0){let G=Sf(qe);G&&x.appendChild(G)}let Oe=Cf(e);if(Oe.length>0){let G=Tf(Oe);G&&x.appendChild(G)}if(x.appendChild(N),m&&u==="below"&&e.createdAt){let G=qu(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let fe=e.role==="assistant"?ff(e.stopReason,(de=(We=o==null?void 0:o.widgetConfig)==null?void 0:We.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(H&&H.trim()),je=I.placeholder==="skeleton",Mt=je&&I.buffer==="line"&&G;if(G)Mt&&x.appendChild(na());else if(je)x.appendChild(na());else{let pe=fl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);pe&&x.appendChild(pe)}}if(fe&&e.stopReason&&!e.streaming&&(E||(N.style.display="none"),x.appendChild(hf(e.stopReason,fe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=hl(e,r,s);x.appendChild(G)}if(!p||e.role==="system")return x;let Pe=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),De=Ef(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Pe.append(x,De):Pe.append(De,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Pe},Vu=(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}):ps(e,t,n,r,s,o)};var us=new Set,kf=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Lf=(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
- `):""},Ku=(e,t)=>{let n=us.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")},yl=(e,t)=>{var qe,Oe,fe,xe,Pe,De,te,Ie,K,ce,Ce;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=(qe=t==null?void 0:t.features)==null?void 0:qe.reasoningDisplay)!=null?Oe:{},o=s.expandable!==!1,a=o&&us.has(e.id),i=n.status!=="complete",d=Lf(e,(fe=s.previewMaxLines)!=null?fe: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 p=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(xe=t==null?void 0:t.reasoning)!=null?xe:{},v=String((Pe=n.startedAt)!=null?Pe:Date.now()),x=()=>{let he=h("span","");return he.setAttribute("data-tool-elapsed",v),he.textContent=_a(n),he},w=(De=u.renderCollapsedSummary)==null?void 0:De.call(u,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:_a(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(m.textContent=w,p.appendChild(m)):w instanceof HTMLElement?p.appendChild(w):(m.textContent=g,p.appendChild(m));let E=h("span","persona-text-xs persona-text-persona-primary");E.textContent=ou(n),p.appendChild(E);let B=(te=s.loadingAnimation)!=null?te:"none",L=u.activeTextTemplate,I=u.completeTextTemplate,R=i?L:I,S=w instanceof HTMLElement,W=(he,we,Ke)=>{let Q=Ke;for(let ne of we){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(Q)),ae.textContent=ne===" "?"\xA0":ne,he.appendChild(ae),Q++}return Q},$=(he,we)=>{m.textContent="";let Ke=ja(he,""),Q=0;for(let ne of Ke){let ae=ne.styles.length>0?(()=>{let me=h("span",ne.styles.map(le=>`persona-tool-text-${le}`).join(" "));return m.appendChild(me),me})():m;if(ne.isDuration&&i)ae.appendChild(x());else{let me=ne.isDuration?_a(n):ne.text;we?Q=W(ae,me,Q):ae.appendChild(document.createTextNode(me))}}};if(!S&&R)if(E.style.display="none",m.style.display="",i&&B!=="none"){let he=(Ie=u.loadingAnimationDuration)!=null?Ie:2e3;m.setAttribute("data-preserve-animation","true"),B==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`),$(R,!1)):(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`),B==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),$(R,!0))}else $(R,!1);else if(!S&&i&&B!=="none"){m.style.display="";let he=(K=u.loadingAnimationDuration)!=null?K:2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`),B==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let we=m.textContent||g;m.textContent="",W(m,we,0)}n.status==="complete"&&(m.style.display="none")}else S||(n.status==="complete"?m.style.display="none":m.style.display="");let N=null;if(o){N=h("div","persona-flex persona-items-center");let we=be(a?"chevron-up":"chevron-down",16,"currentColor",2);we?N.appendChild(we):N.textContent=a?"Hide":"Show";let Ke=h("div","persona-flex persona-items-center persona-ml-auto");Ke.append(N),l.append(p,Ke)}else l.append(p);let H=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","reasoning"),H.style.display="none",H.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let he=(Ce=(ce=t==null?void 0:t.reasoning)==null?void 0:ce.renderCollapsedPreview)==null?void 0:Ce.call(ce,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});kf(H,he)||(H.textContent=d),H.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,H),r;let j=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let V=n.chunks.join(""),se=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return se.textContent=V||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(se),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),N){N.innerHTML="";let we=be(a?"chevron-up":"chevron-down",16,"currentColor",2);we?N.appendChild(we):N.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(l,H,j),r};var ms=new Set,Pf=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),If=(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=rs(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Wf=(e,t)=>{var p,m,g,u,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=If(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?su(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},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=Yi(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Yi(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Ju=(e,t,n)=>{var p;let r=ms.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},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 m=s.toggleTextColor||s.headerTextColor||"currentColor",g=be(r?"chevron-up":"chevron-down",16,m,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},bl=(e,t)=>{var V,se,He,qe,Oe,fe,xe,Pe,De;let n=e.toolCall,r=(V=t==null?void 0:t.toolCall)!=null?V:{},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=(He=(se=t==null?void 0:t.features)==null?void 0:se.toolCallDisplay)!=null?He:{},a=o.expandable!==!1,i=a&&ms.has(e.id),{summary:d,previewText:l,isActive:p}=Wf(e,t),m=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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((qe=n.startedAt)!=null?qe:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",v),te.textContent=Us(n),te},w=(fe=r.renderCollapsedSummary)==null?void 0:fe.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Oe=o.collapsedMode)!=null?Oe:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Us(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(u.textContent=w,g.appendChild(u)):w instanceof HTMLElement?g.appendChild(w):(u.textContent=d,g.appendChild(u));let E=(xe=o.loadingAnimation)!=null?xe:"none",B=r.activeTextTemplate,L=r.completeTextTemplate,I=p?B:L,R=w instanceof HTMLElement,S=(te,Ie,K)=>{let ce=K;for(let Ce of Ie){let he=h("span","persona-tool-char");he.style.setProperty("--char-index",String(ce)),he.textContent=Ce===" "?"\xA0":Ce,te.appendChild(he),ce++}return ce},W=(te,Ie)=>{var he;u.textContent="";let K=((he=n.name)==null?void 0:he.trim())||"tool",ce=ja(te,K),Ce=0;for(let we of ce){let Ke=we.styles.length>0?(()=>{let Q=h("span",we.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(Q),Q})():u;if(we.isDuration&&p)Ke.appendChild(x());else{let Q=we.isDuration?Us(n):we.text;Ie?Ce=S(Ke,Q,Ce):Ke.appendChild(document.createTextNode(Q))}}};if(!R)if(p&&E!=="none"){let te=(Pe=r.loadingAnimationDuration)!=null?Pe:2e3;if(u.setAttribute("data-preserve-animation","true"),E==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${te}ms`),I&&W(I,!1);else if(u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${te}ms`),E==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)W(I,!0);else{let Ie=u.textContent||d;u.textContent="",S(u,Ie,0)}}else I&&W(I,!1);let $=null;if(a){$=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",Ie=be(i?"chevron-up":"chevron-down",16,te,2);Ie?$.appendChild(Ie):$.textContent=i?"Hide":"Show";let K=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append($),m.append(g,K)}else m.append(g);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","tool"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let te=(De=r.renderCollapsedPreview)==null?void 0:De.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Pf(N,te)||(N.textContent=l),N.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,N),s;let H=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),n.name){let te=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?te.style.color=r.contentTextColor:r.headerTextColor&&(te.style.color=r.headerTextColor),te.textContent=n.name,H.appendChild(te)}if(n.args!==void 0){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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=rs(n.args),te.append(Ie,K),H.appendChild(te)}if(n.chunks&&n.chunks.length){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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(""),te.append(Ie,K),H.appendChild(te)}if(n.status==="complete"&&n.result!==void 0){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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=rs(n.result),te.append(Ie,K),H.appendChild(te)}if(n.status==="complete"&&typeof n.duration=="number"){let te=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(te.style.color=r.contentTextColor),te.textContent=`Duration: ${n.duration}ms`,H.appendChild(te)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",Ie=be(i?"chevron-up":"chevron-down",16,te,2);Ie?$.appendChild(Ie):$.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),s.append(m,N,H),s};var mo=require("partial-json");var vl="ask_user_question",xl=8,gs="data-persona-ask-sheet-for",Rf="Other",Hf="Other\u2026",Xu="Type your own answer here",Qu="Send",Bf="Next",Df="Back",Nf="Submit all",Ff="Skip",Of=3,Cl="data-ask-current-index",wl="data-ask-question-count",Yu="data-ask-answers",Al="data-ask-grouped",Zu="data-ask-layout",$f=e=>e.layout==="pills"?"pills":"rows",_f=e=>e.getAttribute(Zu)==="pills"?"pills":"rows",Gu=!1,em=e=>e.replace(/["\\]/g,"\\$&"),_r=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===vl,Ti=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,mo.parse)(s,mo.STR|mo.OBJ|mo.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},ia=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>xl&&!Gu&&(Gu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${xl}.`)),t.slice(0,xl)},jf=e=>{var t;return(t=ia(e)[0])!=null?t:null},Uf=(e,t)=>{var n;return(n=ia(e)[t])!=null?n:null},tm=(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))},nm=(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},qf=(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=nm(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},zf=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},Vf=(e,t,n,r)=>{var p,m,g;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(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<Of;u++)o.appendChild(zf(r));return o}if(d.forEach((u,v)=>{o.appendChild(qf(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?Rf:Hf;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"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(p=t.freeTextPlaceholder)!=null?p:Xu,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),x.appendChild(w),v.appendChild(x);let E=nm(r,a,d.length);E&&v.appendChild(E),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=(g=t.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},rm=(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:Xu,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:Qu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Kf=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:Qu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Jf=(e,t,n)=>{var l,p,m,g;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:Df,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=(p=n.skipLabel)!=null?p:Ff,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?(m=n.submitAllLabel)!=null?m:Nf:(g=n.nextLabel)!=null?g:Bf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},_o=e=>{let t=e.getAttribute(Yu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},om=(e,t)=>{e.setAttribute(Yu,JSON.stringify(t))},lr=e=>{var n;let t=Number((n=e.getAttribute(Cl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Gf=(e,t)=>{e.setAttribute(Cl,String(Math.max(0,Math.floor(t))))},fs=e=>{var n;let t=Number((n=e.getAttribute(wl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},go=e=>e.getAttribute(Al)==="true",Xf=(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},Qf=(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)))},Ei=(e,t)=>{let{payload:n}=jr(t),r=ia(n),s=_o(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},sm=e=>{let t=_o(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 m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});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=""},am=e=>{if(!go(e))return;let t=_o(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}},Sl=(e,t,n)=>{let r=Ti(n),s=_f(e),{payload:o,complete:a}=jr(t),i=go(e),d=lr(e),l=fs(e),p=i?Uf(o,d):jf(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let B=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=B,v.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let B=Vf(p,r,a,s);x.replaceWith(B)}if(s!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(rm(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!w?e.appendChild(Kf(r)):(!m||i)&&w&&w.remove(),e.setAttribute("data-multi-select",m?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let B=Jf(d,l,r);E?E.replaceWith(B):e.appendChild(B)}else E&&E.remove();sm(e),am(e)},Yf=(e,t,n)=>{let r=Ti(t),s=$f(r),o=e.toolCall.id,a=ia(n),i=Math.max(1,a.length),d=i>1,l=Xf(e,a),p=d?Qf(e,i):0,m=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(gs,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(wl,String(i)),m.setAttribute(Cl,String(p)),m.setAttribute(Al,d?"true":"false"),m.setAttribute(Zu,s),om(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),tm(m,r);let g=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=h("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),m.appendChild(g);let w=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),m.appendChild(w),s!=="rows"&&m.appendChild(rm(r,s)),Sl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Zf=(e,t,n)=>{let{payload:r}=jr(t),s=Math.max(1,ia(r).length);s>fs(e)&&(e.setAttribute(wl,String(s)),s>1&&!go(e)&&e.setAttribute(Al,"true")),Sl(e,t,n)},im=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Ti(t);tm(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},hs=(e,t,n)=>{if(!n||!_r(e)||Ti(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${gs}]`).forEach(l=>{l.getAttribute(gs)!==s&&l.remove()});let a=n.querySelector(`[${gs}="${em(s)}"]`);if(a){Zf(a,e,t);return}let{payload:i}=jr(e),d=Yf(e,t,i);n.appendChild(d)},fo=(e,t)=>{if(!e)return;let n=t?`[${gs}="${em(t)}"]`:`[${gs}]`;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)})},Tl=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),ho=(e,t)=>{let n=_o(e),r=lr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,om(e,n),sm(e),am(e)},Mi=(e,t,n,r)=>{let s=fs(e),o=Math.max(0,Math.min(s-1,r));Gf(e,o),Sl(e,t,n)};var El=(e,t)=>{var x,w,E,B,L,I,R,S,W,$,N,H;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=(w=r==null?void 0:r.borderColor)!=null?w:"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)":(E=r==null?void 0:r.titleColor)!=null?E:"currentColor",p=be(d,20,l,2);p&&i.appendChild(p);let m=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),u=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(B=r==null?void 0:r.title)!=null?B:"Approval Required",g.appendChild(u),!s){let j=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");j.setAttribute("data-approval-status",n.status),n.status==="approved"?(j.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",j.style.color="var(--persona-palette-colors-success-700, #15803d)",j.textContent="Approved"):n.status==="denied"?(j.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",j.style.color="var(--persona-palette-colors-error-700, #b91c1c)",j.textContent="Denied"):n.status==="timeout"&&(j.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",j.style.color="var(--persona-palette-colors-warning-700, #b45309)",j.textContent="Timeout"),g.appendChild(j)}m.appendChild(g);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,m.appendChild(v),n.parameters){let j=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(j.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(j.style.color=r.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=rs(n.parameters),m.appendChild(j)}if(s){let j=h("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let V=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");V.type="button",V.style.backgroundColor=(L=r==null?void 0:r.approveButtonColor)!=null?L:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(I=r==null?void 0:r.approveButtonTextColor)!=null?I:"#ffffff",V.setAttribute("data-approval-action","approve");let se=be("shield-check",14,(R=r==null?void 0:r.approveButtonTextColor)!=null?R:"#ffffff",2);se&&(se.style.marginRight="4px",V.appendChild(se));let He=document.createTextNode((S=r==null?void 0:r.approveLabel)!=null?S:"Approve");V.appendChild(He);let qe=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");qe.type="button",qe.style.backgroundColor=(W=r==null?void 0:r.denyButtonColor)!=null?W:"transparent",qe.style.color=($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",qe.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,qe.setAttribute("data-approval-action","deny");let Oe=be("shield-x",14,(N=r==null?void 0:r.denyButtonTextColor)!=null?N:"var(--persona-feedback-error, #dc2626)",2);Oe&&(Oe.style.marginRight="4px",qe.appendChild(Oe));let fe=document.createTextNode((H=r==null?void 0:r.denyLabel)!=null?H:"Deny");qe.appendChild(fe),j.append(V,qe),m.appendChild(j)}return a.append(i,m),o.appendChild(a),o};var lm=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(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=s?s.isStreaming():!1,g=u=>{switch(u){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(u=>{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=u,v.disabled=m,i!=null&&i.fontFamily&&(v.style.fontFamily=g(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(u))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var la=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 ca=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 eh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),th=new Set(["step_start","execution_start"]),nh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),rh=new Set(["step_complete","agent_turn_complete"]),oh=new Set(["flow_complete","agent_complete"]),cm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),pm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,jo=(e,t)=>{let n=e[t];return pm(n)?n:void 0};function Ml(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ki(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function sh(e,t){return typeof t.type=="string"?t.type:e}function ah(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 ih(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 dm(e){var r,s,o,a,i;let t=jo(e,"result"),n=[jo(e,"tokens"),jo(e,"totalTokens"),t?jo(t,"tokens"):void 0,jo(e,"usage"),t?jo(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 lh(e){var n,r,s,o,a;let t=jo(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 ch(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var da=class{constructor(t=ch){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:ki(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(!pm(n)){cm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=sh(t,n),s=this.now();if(eh.has(r)){this.startRun(s);return}if(th.has(r)){this.run||this.startRun(s);return}if(nh.has(r)){if(!ih(r,n))return;let a=ah(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+Ml(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ki(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(rh.has(r)){if(!this.run)return;let a=this.run,i=dm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ml(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:ki(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(oh.has(r)){if(!this.run)return;let a=this.run,i=dm(n),d=i!=null?i:a.exactOutputTokens+Ml(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:ki(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(cm.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=lh(n);return o!=null?o:r-t.startedAt}};function ys(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var dh={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)"}},ph={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},uh=["flowName","stepName","reasoningText","text","name","tool","toolName"],mh=100;function gh(e,t){let n={...dh,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return ph}function fh(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function hh(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 yh(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 bh(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 xh(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 vh(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ch(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 wh(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 kl(e,t,n,r,s,o,a,i){var g;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ys(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var V,se;let u=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"),w=be(d?"chevron-down":"chevron-right","14px","currentColor",2);w&&x.appendChild(w);let E=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=(V=r.timestampFormat)!=null?V:"relative";E.textContent=B==="relative"?fh(e.timestamp,n):hh(e.timestamp);let L=null;r.showSequenceNumbers!==!1&&(L=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let I=gh(e.type,r.badgeColors),R=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");R.style.backgroundColor=I.bg,R.style.color=I.text,R.style.borderColor=I.text+"50",R.textContent=e.type;let S=(se=r.descriptionFields)!=null?se:uh,W=yh(e.payload,S),$=null;W&&($=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=W);let N=h("div","persona-flex-1 persona-min-w-0"),H=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),j=be("clipboard","12px","currentColor",1.5);return j&&H.appendChild(j),H.addEventListener("click",async He=>{He.stopPropagation(),await bh(xh(e)),H.innerHTML="";let qe=be("check","12px","currentColor",1.5);qe&&H.appendChild(qe),setTimeout(()=>{H.innerHTML="";let Oe=be("clipboard","12px","currentColor",1.5);Oe&&H.appendChild(Oe)},1500)}),v.appendChild(x),v.appendChild(E),L&&v.appendChild(L),v.appendChild(R),$&&v.appendChild($),v.appendChild(N),v.appendChild(H),u.appendChild(v),d&&u.appendChild(wh(e,a,i)),u}}function um(e){var v,x,w,E,B;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",p=(w=i==null?void 0:i.label)!=null?w:"",m=(B=(E=s==null?void 0:s.features)==null?void 0:E.eventStream)!=null?B:{},g=o.find(L=>L.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let L=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>u().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return u();function u(){let L=m.classNames,I=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ys(I,L==null?void 0:L.panel);let R=[],S="",W="",$=null,N=[],H={},j=0,V=li(),se=0,He=0,qe=!1,Oe=null,fe=!1,xe=0,Pe=new Set,De=new Map,te="",Ie="",K=null,ce,Ce,he,we,Ke,Q=null,ne=null,ae=null;function me(){let re=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ge=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");ys(ge,L==null?void 0:L.headerBar);let Ct=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ct.textContent="Events",ce=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"),ce.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",Q=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Q.textContent="-- tok/s",ae=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"),ae.style.display="none",ae.style.pointerEvents="none";let Zn=ne,bn=ae,Nn=()=>{if(!bn.textContent)return;let vr=Zn.getBoundingClientRect(),Fn=re.getBoundingClientRect();bn.style.left=`${vr.left-Fn.left}px`,bn.style.top=`${vr.bottom-Fn.top+4}px`,bn.style.display="block"},mt=()=>{bn.style.display="none"};ne.addEventListener("mouseenter",Nn),ne.addEventListener("mouseleave",mt),ne.appendChild(Dn),ne.appendChild(Q)}let qt=h("div","persona-flex-1");Ce=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",Ce.appendChild(en),he=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),he.type="button",he.title="Copy All";let Tt=be("clipboard-copy","12px","currentColor",1.5);Tt&&he.appendChild(Tt);let wt=h("span","persona-text-xs");wt.textContent="Copy All",he.appendChild(wt),ge.appendChild(Ct),ge.appendChild(ce),ne&&ge.appendChild(ne),ge.appendChild(qt),ge.appendChild(Ce),ge.appendChild(he);let ht=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ys(ht,L==null?void 0:L.searchBar);let bt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),Vt=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&Vt.appendChild(bt),we=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"),ys(we,L==null?void 0:L.searchInput),we.type="text",we.placeholder="Search event payloads...",Ke=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"),Ke.type="button",Ke.style.display="none";let nt=be("x","12px","currentColor",2);return nt&&Ke.appendChild(nt),ht.appendChild(Vt),ht.appendChild(we),ht.appendChild(Ke),re.appendChild(ge),re.appendChild(ht),ae&&re.appendChild(ae),re}let le,oe=o.find(re=>re.renderEventStreamToolbar);if(oe!=null&&oe.renderEventStreamToolbar&&s){let re=oe.renderEventStreamToolbar({config:s,defaultRenderer:()=>me(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ge=>{S=ge,Bn(),O()},onSearchChange:ge=>{W=ge,Bn(),O()}});le=re!=null?re:me()}else le=me();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 We(){if(!a||!Q||!ne)return;let re=a();Q.textContent=vh(re);let ge=Ch(re);ae&&(ae.textContent=ge,ge||(ae.style.display="none")),ge?ne.setAttribute("aria-label",ge):ne.removeAttribute("aria-label")}let de=h("div","persona-flex-1 persona-min-h-0 persona-relative"),G=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.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");ys(je,L==null?void 0:L.scrollIndicator),je.style.display="none",je.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Mt=be(l,"14px","currentColor",2);Mt&&je.appendChild(Mt);let pe=h("span","");pe.textContent=p,je.appendChild(pe);let ie=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ie.style.display="none",de.appendChild(G),de.appendChild(ie),de.appendChild(je),I.setAttribute("tabindex","0"),I.appendChild(le),I.appendChild(Ye),I.appendChild(de);function kn(){let re=t.getAll(),ge={};for(let wt of re)ge[wt.type]=(ge[wt.type]||0)+1;let Ct=Object.keys(ge).sort(),qt=Ct.length!==N.length||!Ct.every((wt,ht)=>wt===N[ht]),en=!qt&&Ct.some(wt=>ge[wt]!==H[wt]),yn=re.length!==Object.values(H).reduce((wt,ht)=>wt+ht,0);if(!qt&&!en&&!yn||(N=Ct,H=ge,!Ce))return;let Tt=Ce.value;if(Ce.options[0].textContent="All events",qt){for(;Ce.options.length>1;)Ce.remove(1);for(let wt of Ct){let ht=h("option","");ht.value=wt,ht.textContent=`${wt} (${ge[wt]||0})`,Ce.appendChild(ht)}Tt&&Ct.includes(Tt)?Ce.value=Tt:Tt&&(Ce.value="",S="")}else for(let wt=1;wt<Ce.options.length;wt++){let ht=Ce.options[wt];ht.textContent=`${ht.value} (${ge[ht.value]||0})`}}function $t(){let re=t.getAll();if(S&&(re=re.filter(ge=>ge.type===S)),W){let ge=W.toLowerCase();re=re.filter(Ct=>Ct.type.toLowerCase().includes(ge)||Ct.payload.toLowerCase().includes(ge))}return re}function cn(){return S!==""||W!==""}function Bn(){j=0,se=0,V.resume(),je.style.display="none"}function Yn(re){Pe.has(re)?Pe.delete(re):Pe.add(re),K=re;let ge=G.scrollTop,Ct=V.isFollowing();fe=!0,V.pause(),O(),G.scrollTop=ge,Ct&&V.resume(),fe=!1}function ze(){return Qs(G,50)}function O(){He=Date.now(),qe=!1,We(),kn();let re=t.getEvictedCount();re>0?(Ye.textContent=`${re.toLocaleString()} older events truncated`,Ye.style.display=""):Ye.style.display="none",R=$t();let ge=R.length,Ct=t.getSize()>0;ce&&(ce.textContent=String(t.getSize())),ge===0&&Ct&&cn()?(ie.textContent=W?`No events matching '${W}'`:"No events matching filter",ie.style.display="",G.style.display="none"):(ie.style.display="none",G.style.display=""),he&&(he.title=cn()?`Copy Filtered (${ge})`:"Copy All"),d&&!V.isFollowing()&&ge>j&&(se+=ge-j,pe.textContent=p?`${p}${se>0?` (${se})`:""}`:"",je.style.display=""),j=ge;let qt=t.getAll(),en=qt.length>0?qt[0].timestamp:0,yn=new Set(R.map(ht=>ht.id));for(let ht of Pe)yn.has(ht)||Pe.delete(ht);let Tt=S!==te||W!==Ie,wt=De.size===0&&R.length>0;if(Tt||wt||R.length===0){G.innerHTML="",De.clear();let ht=document.createDocumentFragment();for(let bt=0;bt<R.length;bt++){let Vt=kl(R[bt],bt,en,m,Pe,Yn,o,s);De.set(R[bt].id,Vt),ht.appendChild(Vt)}G.appendChild(ht),te=S,Ie=W,K=null}else{if(K!==null){let bt=De.get(K);if(bt&&bt.parentNode===G){let Vt=R.findIndex(nt=>nt.id===K);if(Vt>=0){let nt=kl(R[Vt],Vt,en,m,Pe,Yn,o,s);G.insertBefore(nt,bt),bt.remove(),De.set(K,nt)}}K=null}let ht=new Set(R.map(bt=>bt.id));for(let[bt,Vt]of De)ht.has(bt)||(Vt.remove(),De.delete(bt));for(let bt=0;bt<R.length;bt++){let Vt=R[bt];if(!De.has(Vt.id)){let nt=kl(Vt,bt,en,m,Pe,Yn,o,s);De.set(Vt.id,nt),G.appendChild(nt)}}}V.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Se(){if(Date.now()-He>=mh){Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),O();return}qe||(qe=!0,Oe=requestAnimationFrame(()=>{Oe=null,O()}))}let Ne=(re,ge)=>{if(!he)return;he.innerHTML="";let Ct=be(re,"12px","currentColor",1.5);Ct&&he.appendChild(Ct);let qt=h("span","persona-text-xs");qt.textContent="Copy All",he.appendChild(qt),setTimeout(()=>{he.innerHTML="";let en=be("clipboard-copy","12px","currentColor",1.5);en&&he.appendChild(en);let yn=h("span","persona-text-xs");yn.textContent="Copy All",he.appendChild(yn),he.disabled=!1},ge)},Fe=async()=>{if(he){he.disabled=!0;try{let re;cn()?re=R:n?(re=await n(),re.length===0&&(re=t.getAll())):re=t.getAll();let ge=re.map(Ct=>{try{return JSON.parse(Ct.payload)}catch{return Ct.payload}});await navigator.clipboard.writeText(JSON.stringify(ge,null,2)),Ne("check",1500)}catch{Ne("x",1500)}}},Ue=()=>{Ce&&(S=Ce.value,Bn(),O())},pt=()=>{!we||!Ke||(Ke.style.display=we.value?"":"none",$&&clearTimeout($),$=setTimeout(()=>{W=we.value,Bn(),O()},150))},ot=()=>{!we||!Ke||(we.value="",W="",Ke.style.display="none",$&&clearTimeout($),Bn(),O())},St=()=>{if(fe)return;let re=G.scrollTop,{action:ge,nextLastScrollTop:Ct}=ci({following:V.isFollowing(),currentScrollTop:re,lastScrollTop:xe,nearBottom:ze(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=Ct,ge==="resume"?(V.resume(),se=0,je.style.display="none"):ge==="pause"&&(V.pause(),d&&(pe.textContent=p,je.style.display=""))},Ut=re=>{let ge=di({following:V.isFollowing(),deltaY:re.deltaY,nearBottom:ze(),resumeWhenNearBottom:!0});ge==="pause"?(V.pause(),d&&(pe.textContent=p,je.style.display="")):ge==="resume"&&(V.resume(),se=0,je.style.display="none")},z=()=>{d&&(G.scrollTop=G.scrollHeight,V.resume(),se=0,je.style.display="none")},_t=re=>{let ge=re.target;if(!ge||ge.closest("button"))return;let Ct=ge.closest("[data-event-id]");if(!Ct)return;let qt=Ct.getAttribute("data-event-id");qt&&Yn(qt)},Ze=re=>{if((re.metaKey||re.ctrlKey)&&re.key==="f"){re.preventDefault(),we==null||we.focus(),we==null||we.select();return}re.key==="Escape"&&(we&&document.activeElement===we?(ot(),we.blur(),I.focus()):r&&r())};he&&he.addEventListener("click",Fe),Ce&&Ce.addEventListener("change",Ue),we&&we.addEventListener("input",pt),Ke&&Ke.addEventListener("click",ot),G.addEventListener("scroll",St),G.addEventListener("wheel",Ut,{passive:!0}),G.addEventListener("click",_t),je.addEventListener("click",z),I.addEventListener("keydown",Ze);function Ft(){$&&clearTimeout($),Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),qe=!1,De.clear(),he&&he.removeEventListener("click",Fe),Ce&&Ce.removeEventListener("change",Ue),we&&we.removeEventListener("input",pt),Ke&&Ke.removeEventListener("click",ot),G.removeEventListener("scroll",St),G.removeEventListener("wheel",Ut),G.removeEventListener("click",_t),je.removeEventListener("click",z),I.removeEventListener("keydown",Ze)}return{element:I,update:Se,destroy:Ft}}}function mm(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 p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var gm=(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",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>mm(e,t)});if(p)return p}return mm(e,t)};var Ll=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 Ll;Ur.register("PersonaArtifactCard",gm);function Ah(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 fm(e,t){var Ce,he,we,Ke;let n=(he=(Ce=e.features)==null?void 0:Ce.artifacts)==null?void 0:he.layout,s=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",o=(Ke=n==null?void 0:n.panePadding)==null?void 0:Ke.trim(),a=e.markdown?Io(e.markdown):null,i=ts(e.sanitize),d=Q=>{let ne=a?a(Q):Wo(Q);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,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};l&&l.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let u=h("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let x="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=s?jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):jt({icon:"eye",label:"Rendered view"}),B=s?jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):jt({icon:"code-2",label:"Source"}),L=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,R=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,W=!!(R&&S&&S.length>0),$=null,N,H=null,j=null;if(s&&(I||R)&&!W){if(N=I?sa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Q=be("chevron-down",14,"currentColor",2);Q&&N.appendChild(Q)}}else s&&W?($=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),N=I?sa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=jt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),$.append(N,H)):s?N=jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):N=jt({icon:"copy",label:"Copy"});let V=s?jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):jt({icon:"refresh-cw",label:"Refresh"}),se=s?jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):jt({icon:"x",label:"Close"}),He=()=>{var le,oe,Ye;let Q=(le=De.find(We=>We.id===te))!=null?le:De[De.length-1],ne=(oe=Q==null?void 0:Q.id)!=null?oe:null,ae=(Q==null?void 0:Q.artifactType)==="markdown"&&(Ye=Q.markdown)!=null?Ye:"",me=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:ae,jsonPayload:me,id:ne}},qe=async()=>{var le;let{markdown:Q,jsonPayload:ne}=He(),ae=(le=De.find(oe=>oe.id===te))!=null?le:De[De.length-1],me=(ae==null?void 0:ae.artifactType)==="markdown"?Q:ae?ne:"";try{await navigator.clipboard.writeText(me)}catch{}};if(N.addEventListener("click",async()=>{let Q=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Q&&W){let{markdown:ne,jsonPayload:ae,id:me}=He();try{await Q({actionId:"primary",artifactId:me,markdown:ne,jsonPayload:ae})}catch{}return}await qe()}),H&&(S!=null&&S.length)){let Q=()=>{var ae;return(ae=m.closest("[data-persona-root]"))!=null?ae:document.body},ne=()=>{j=uo({items:S.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:me,jsonPayload:le,id:oe}=He(),Ye=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ye?await Ye({actionId:ae,artifactId:oe,markdown:me,jsonPayload:le}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(me):ae==="json"||ae==="source"?await navigator.clipboard.writeText(le):await navigator.clipboard.writeText(me||le)}catch{}},anchor:$!=null?$:H,position:"bottom-right",portal:Q()})};m.isConnected?ne():requestAnimationFrame(ne),H.addEventListener("click",ae=>{ae.stopPropagation(),j==null||j.toggle()})}V.addEventListener("click",async()=>{var Q;try{await((Q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Q.call(n))}catch{}K()}),se.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let Oe=()=>{s&&(E.setAttribute("aria-pressed",x==="rendered"?"true":"false"),B.setAttribute("aria-pressed",x==="source"?"true":"false"))};E.addEventListener("click",()=>{x="rendered",Oe(),K()}),B.addEventListener("click",()=>{x="source",Oe(),K()});let fe=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?(g.replaceChildren(),w.append(E,B),$?L.append($,V,se):L.append(N,V,se),g.append(w,fe,L),Oe()):(g.appendChild(u),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let xe=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"),Pe=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(xe.style.paddingLeft=o,xe.style.paddingRight=o,Pe.style.padding=o),m.appendChild(g),m.appendChild(xe),m.appendChild(Pe);let De=[],te=null,Ie=!1,K=()=>{var me,le,oe,Ye;let Q=s&&De.length<=1;xe.classList.toggle("persona-hidden",Q),xe.replaceChildren();for(let We of De){let de=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");de.type="button",de.textContent=We.title||We.id.slice(0,8),We.id===te&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>t.onSelect(We.id)),xe.appendChild(de)}Pe.replaceChildren();let ne=te&&De.find(We=>We.id===te)||De[De.length-1];if(!ne)return;if(s){let We=ne.artifactType==="markdown"?"MD":(me=ne.component)!=null?me:"Component",G=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";fe.textContent=`${G} \xB7 ${We}`}else u.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&x==="source"){let de=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(le=ne.markdown)!=null?le:"",Pe.appendChild(de);return}let We=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((oe=ne.markdown)!=null?oe:""),Pe.appendChild(We);return}let ae=ne.component?Ur.get(ne.component):void 0;if(ae){let de={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=ae((Ye=ne.props)!=null?Ye:{},de);if(G){Pe.appendChild(G);return}}catch{}}Pe.appendChild(Ah(ne))},ce=()=>{var ne;let Q=De.length>0;if(m.classList.toggle("persona-hidden",!Q),l){let ae=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,le=((ne=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&le&&Ie?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(Q){var ne,ae,me;De=Q.artifacts,te=(me=(ae=Q.selectedId)!=null?ae:(ne=Q.artifacts[Q.artifacts.length-1])==null?void 0:ne.id)!=null?me:null,De.length>0&&(Ie=!0),K(),ce()},setMobileOpen(Q){Ie=Q,!Q&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):ce()}}}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 hm(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 Sh(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 Li(e,t){var d,l,p,m,g,u,v,x,w,E;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"),Sh(e),hm(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",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"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=(u=n==null?void 0:n.paneBackground)==null?void 0:u.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=(w=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),hm(e,t)}var ym=["panel","seamless"];function Pi(e,t){var i,d,l,p,m,g;for(let u of ym)e.classList.remove(`persona-artifact-appearance-${u}`);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=ym.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.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 u=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function bm(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 Th(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 Eh(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 Mh(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function kh(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function xm(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 vm(e,t,n,r,s,o){let a=Th(s,200),i=kh(t,n,r,200);i=Math.max(a,i);let d=Eh(o);return d!==null&&(i=Math.min(i,d)),Mh(e,a,i)}var Cm={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"}},Pl=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,w;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=Cm[a])!=null?x:Cm.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 E=h("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,d.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var S,W;let B=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${t.id}-${a}-${E.name}`;let L=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=E.label,B.appendChild(L);let I=(S=E.type)!=null?S:"text",R;I==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=I),R.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",R.id=`${t.id}-${a}-${E.name}`,R.name=E.name,R.placeholder=(W=E.placeholder)!=null?W:"",E.required&&(R.required=!0),B.appendChild(R),p.appendChild(B)});let m=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=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");u.type="submit",u.textContent=(w=i.submitLabel)!=null?w:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async E=>{var R,S;E.preventDefault();let B=(R=n.formEndpoint)!=null?R:"/form",L=new FormData(p),I={};L.forEach((W,$)=>{I[$]=W}),I.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let $=await W.json();g.textContent=(S=$.message)!=null?S:"Thanks! We'll be in touch soon.",$.success&&$.nextPrompt&&await r.sendMessage(String($.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Il=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()}},pa=new Il;var wm=()=>{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 Lh=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Ph=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},ua=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Lh(e),n=Ph(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}},Wl=e=>typeof e=="string"?e:e==null?"":String(e),Uo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Wl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=Wl(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:Wl(n.text)}}},Am=e=>Array.isArray(e)?e.map(t=>String(t)):[],ma=e=>{let t=new Set(Am(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Am(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,p)=>l||(p==null?void 0:p({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 p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ih=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}},Wh=e=>e.map(t=>({...t,streaming:!1})),Rh=e=>e.map(t=>({...t,status:"complete"})),Ii=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Ih(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?Wh(n.messages):void 0,artifacts:n.artifacts?Rh(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 bs=require("partial-json");function Hh(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Bh(e,t){if(!Hh(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 Wi(){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,bs.parse)(n,bs.STR|bs.OBJ),o=Bh(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Sm(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ri(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 Tm(){let e=Wi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Em(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 Hi(e){let t=Em(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 Bi(e){let t=Em(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 Dh=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Di(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=Dh}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,u.appendChild(x),g.appendChild(u);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let S=1;S<=5;S++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),W.title=l[S-1],W.dataset.rating=String(S),W.innerHTML=`
23
+ `,n.addEventListener("click",t);let r=o=>{var k,P,W,S,I,$,D,R,q,K,se,Re,Ge;let a=(k=o.launcher)!=null?k:{},i=ln(o),d=n.querySelector("[data-role='launcher-title']");if(d){let Ce=(P=a.title)!=null?P:"Chat Assistant";d.textContent=Ce,d.setAttribute("title",Ce)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Ce=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=Ce,l.setAttribute("title",Ce)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let Ce=(S=a.agentIconSize)!=null?S:"40px";if(u.style.height=Ce,u.style.width=Ce,u.innerHTML="",a.agentIconName){let He=parseFloat(Ce)||24,be=we(a.agentIconName,He*.6,"var(--persona-text-inverse, #ffffff)",2);be?(u.appendChild(be),u.style.display=""):(u.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=($=a.agentIconText)!=null?$:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let Ce=(D=a.agentIconSize)!=null?D:"40px";f.style.height=Ce,f.style.width=Ce,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(R=a.callToActionIconSize)!=null?R:"32px";m.style.height=Ce,m.style.width=Ce,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let He=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,He=(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 be=parseFloat(Ce)||24,Be=Math.max(be-He,8),Pe=we(a.callToActionIconName,Be,"currentColor",2);Pe?m.appendChild(Pe):m.textContent=(q=a.callToActionIconText)!=null?q:"\u2197"}else m.textContent=(K=a.callToActionIconText)!=null?K:"\u2197"}let v=a.position&&Tr[a.position]?Tr[a.position]:Tr["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",w="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?w:`${x} ${v}`,i||(n.style.zIndex=String((se=a.zIndex)!=null?se:wn));let T="1px solid var(--persona-border, #e5e7eb)",B="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Re=a.border)!=null?Re:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:B,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=(Ge=a.collapsedMaxWidth)!=null?Ge:"",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 xf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",hi=(e,t={})=>{var x,w,T,B,k,P;let{showClose:n=!0,wrapperClassName:r=xf,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(w=s!=null?s:a.closeButtonSize)!=null?w:"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 p=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(B=a.closeButtonShowTooltip)!=null?B:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(k=a.closeButtonIconName)!=null?k:"x",m=(P=a.closeButtonIconText)!=null?P:"\xD7";l.style.color=a.closeButtonColor||Ln.actionIconColor;let v=we(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 W=a.closeButtonBorderWidth||"0px",S=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${S}`,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),u&&p){let W=null,S=()=>{if(W)return;let $=l.ownerDocument,D=$.body;if(!D)return;W=Pr($,"div","persona-clear-chat-tooltip"),W.textContent=p;let R=Pr($,"div");R.className="persona-clear-chat-tooltip-arrow",W.appendChild(R);let q=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(mo),W.style.left=`${q.left+q.width/2}px`,W.style.top=`${q.top-8}px`,W.style.transform="translate(-50%, -100%)",D.appendChild(W)},I=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",I),l.addEventListener("focus",S),l.addEventListener("blur",I),d._cleanupTooltip=()=>{I(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",I),l.removeEventListener("focus",S),l.removeEventListener("blur",I)}}return{button:l,wrapper:d}},vf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bi=(e,t={})=>{var W,S,I,$,D,R,q,K,se,Re,Ge,Ce,He;let{wrapperClassName:n=vf,buttonSize:r,iconSize:s="20px"}=t,a=(S=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?S:{},i=(I=r!=null?r:a.size)!=null?I:"32px",d=($=a.iconName)!=null?$:"refresh-cw",l=(D=a.iconColor)!=null?D:"",p=(R=a.backgroundColor)!=null?R:"",u=(q=a.borderWidth)!=null?q:"",f=(K=a.borderColor)!=null?K:"",m=(se=a.borderRadius)!=null?se:"",v=(Re=a.paddingX)!=null?Re:"",x=(Ge=a.paddingY)!=null?Ge:"",w=(Ce=a.tooltipText)!=null?Ce:"Clear chat",T=(He=a.showTooltip)!=null?He:!0,B=h("div",n),k=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");k.style.height=i,k.style.width=i,k.type="button",k.setAttribute("aria-label",w),k.style.color=l||Ln.actionIconColor;let P=we(d,s,"currentColor",1);if(P&&(P.style.display="block",k.appendChild(P)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),u||f){let be=u||"0px",Be=f||"transparent";k.style.border=`${be} solid ${Be}`,k.classList.remove("persona-border-none")}if(m&&(k.style.borderRadius=m,k.classList.remove("persona-rounded-full")),v&&(k.style.paddingLeft=v,k.style.paddingRight=v),x&&(k.style.paddingTop=x,k.style.paddingBottom=x),B.appendChild(k),T&&w){let be=null,Be=()=>{if(be)return;let J=k.ownerDocument,ue=J.body;if(!ue)return;be=Pr(J,"div","persona-clear-chat-tooltip"),be.textContent=w;let V=Pr(J,"div");V.className="persona-clear-chat-tooltip-arrow",be.appendChild(V);let de=k.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(mo),be.style.left=`${de.left+de.width/2}px`,be.style.top=`${de.top-8}px`,be.style.transform="translate(-50%, -100%)",ue.appendChild(be)},Pe=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};B.addEventListener("mouseenter",Be),B.addEventListener("mouseleave",Pe),k.addEventListener("focus",Be),k.addEventListener("blur",Pe),B._cleanupTooltip=()=>{Pe(),B.removeEventListener("mouseenter",Be),B.removeEventListener("mouseleave",Pe),k.removeEventListener("focus",Be),k.removeEventListener("blur",Pe)}}return{button:k,wrapper:B}};var Ln={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))"},qr=e=>{var W,S,I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,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=(W=t==null?void 0:t.launcher)!=null?W:{},o=(S=s.headerIconSize)!=null?S:"48px",a=(I=s.closeButtonPlacement)!=null?I:"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 J=parseFloat(o)||24,ue=we(d,J*.6,"currentColor",1);ue?l.replaceChildren(ue):l.textContent=(R=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?R:"\u{1F4AC}"}else if((q=t==null?void 0:t.launcher)!=null&&q.iconUrl){let J=h("img");J.src=t.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=o,J.style.width=o,l.replaceChildren(J)}else l.textContent=(se=(K=t==null?void 0:t.launcher)==null?void 0:K.agentIconText)!=null?se:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=h("span","persona-text-base persona-font-semibold");u.style.color=Ln.titleColor,u.textContent=(Ge=(Re=t==null?void 0:t.launcher)==null?void 0:Re.title)!=null?Ge:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Ln.subtitleColor,f.textContent=(He=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?He:"Here to help you get answers fast",p.append(u,f),i?r.append(p):r.append(l,p);let m=(be=s.clearChat)!=null?be:{},v=(Be=m.enabled)!=null?Be:!0,x=(Pe=m.placement)!=null?Pe:"inline",w=null,T=null;if(v){let ue=bi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=ue.button,T=ue.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let B=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:k,wrapper:P}=hi(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:k,closeButtonWrapper:P,clearChatButton:w,clearChatButtonWrapper:T}},Uo=(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 ho(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(mo)):(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 w=document.createElement("hr");a.appendChild(w)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let w=we(m.icon,16,"currentColor",1.5);w&&v.appendChild(w)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",w=>{w.stopPropagation(),p(),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)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Vt(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=we(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function ca(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 p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=we(t,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function da(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 p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Vt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),o.appendChild(u)}function l(p){a=p,d()}return{element:o,setSelected:l}}function yi(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 p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=we(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),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,w;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(w=d.border)!=null?w:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=ho({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 w=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",w?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.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 gl=e=>{var r;let t=qr({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 wf(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=we(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=ho({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var fl=e=>{var B,k,P,W,S,I,$,D,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(B=t==null?void 0:t.launcher)!=null?B:{},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,p;if(d)l=yi({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Ln.titleColor,p=(P=l.querySelector(".persona-combo-btn-label"))!=null?P:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Ln.titleColor,p.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(p),wf(l,s==null?void 0:s.trailingActions,(S=s==null?void 0:s.onAction)!=null?S:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let K=s.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||K()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),K())})}let q=s==null?void 0:s.titleRowHover;q&&(l.style.borderRadius=(I=q.borderRadius)!=null?I:"10px",l.style.padding=($=q.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 K,se;l.style.backgroundColor=(K=q.background)!=null?K:"",l.style.borderColor=(se=q.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(D=a.closeButtonSize)!=null?D:"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=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Ln.actionIconColor;let v=(R=a.closeButtonIconName)!=null?R:"x",x=we(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let w=h("div");w.style.display="none";let T=h("span");return T.style.display="none",{header:i,iconHolder:w,headerTitle:p,headerSubtitle:T,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},xi={default:gl,minimal:fl},hl=e=>{var t;return(t=xi[e])!=null?t:xi.default},gs=(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}),p=h("div");p.style.display="none";let u=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=hl(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 vi=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}},wi=e=>{var W,S,I,$,D,R,q,K,se,Re,Ge,Ce;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(S=t.useIcon)!=null?S:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=($=t.stopIconName)!=null?$:"square",a=(D=t.tooltipText)!=null?D:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(K=(q=e==null?void 0:e.copy)==null?void 0:q.sendButtonLabel)!=null?K:"Send",l=(Re=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?Re:"Stop",p=(Ge=t.showTooltip)!=null?Ge:!1,u=(Ce=t.size)!=null?Ce:"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 w=null,T=null;if(n){x.style.width=u,x.style.height=u,x.style.minWidth=u,x.style.minHeight=u,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 He=parseFloat(u)||24,be=(m==null?void 0:m.trim())||"currentColor";s?(w=we(s,He,be,2),w?x.appendChild(w):x.textContent=r):x.textContent=r,T=we(o,He,be,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 B=null;p&&a&&(B=h("div","persona-send-button-tooltip"),B.textContent=a,v.appendChild(B)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:He=>{if(He===k)return;k=He;let be=He==="stop"?i:a;if(x.setAttribute("aria-label",be),B&&(B.textContent=be),n){if(w&&T){let Be=He==="stop"?T:w;x.replaceChildren(Be)}}else x.textContent=He==="stop"?l:d}}},Ci=e=>{var B,k,P,W,S,I,$,D,R,q,K,se;let t=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||s))return null;let a=(W=(P=e==null?void 0:e.sendButton)==null?void 0:P.size)!=null?W:"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=(S=t.iconName)!=null?S:"mic",p=(I=t.iconSize)!=null?I:a,u=parseFloat(p)||24,f=(D=t.backgroundColor)!=null?D:($=e==null?void 0:e.sendButton)==null?void 0:$.backgroundColor,m=(q=t.iconColor)!=null?q:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=we(l,u,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 w=(K=t.tooltipText)!=null?K:"Start voice recognition";if(((se=t.showTooltip)!=null?se:!1)&&w){let Re=h("div","persona-send-button-tooltip");Re.textContent=w,i.appendChild(Re)}return{button:d,wrapper:i}},Ai=e=>{var v,x,w,T,B,k,P,W;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(w=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?w:"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=((T=t.allowedTypes)!=null?T:Ur).join(","),s.multiple=((B=t.maxFiles)!=null?B: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",(k=t.buttonTooltipText)!=null?k:"Attach file");let i=(P=t.buttonIconName)!=null?P:"paperclip",d=n,l=parseFloat(d)||40,p=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 u=we(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",S=>{S.preventDefault(),s.click()}),o.appendChild(a);let f=(W=t.buttonTooltipText)!=null?W:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},Si=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},Ti=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var fs=e=>{var v,x,w,T,B,k;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=Ti(),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}=vi(t);a();let i=wi(t),d=Ci(t),l=Ai(t),p=Si(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let u=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),u.append(f,m),s.append(u),s.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{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:p,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var zu=()=>{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=we("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=we("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},Vu=e=>{var v,x,w,T,B,k;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=Ti();r.style.display="none";let s=Si(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=vi(t);o.style.maxHeight="100px",a();let i=wi(t),d=Ci(t),l=Ai(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.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),p.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(u,o,f),l&&n.append(l.previewsContainer),n.append(p,r,s);let m=p;return{footer:n,suggestions:r,composerForm:p,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:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Ku=e=>{var p,u,f,m,v,x,w,T,B,k,P,W,S,I,$,D,R;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=ln(e);if(fo(e)){let q=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},K=h("div","persona-widget-wrapper persona-fixed persona-transition");K.setAttribute("data-persona-composer-bar",""),K.dataset.state="collapsed",K.dataset.expandedSize=(v=q.expandedSize)!=null?v:"anchored",K.style.zIndex=String((w=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?w:wn);let se=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",K.appendChild(se);let Re=h("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(T=q.expandedSize)!=null?T:"anchored",Re.style.zIndex=String((k=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?k:wn),{wrapper:K,panel:se,pillRoot:Re}}if(n){let q=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),K=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return q.appendChild(K),{wrapper:q,panel:K}}if(!t){let q=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),K=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.width)!=null?W:"100%";return q.style.width=se,K.style.width="100%",q.appendChild(K),{wrapper:q,panel:K}}let s=(S=e==null?void 0:e.launcher)!=null?S:{},o=s.position&&Tr[s.position]?Tr[s.position]:Tr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(($=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?$:wn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:Yn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Cf=(e,t)=>{var P,W,S,I,$,D,R,q,K;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}=hi(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=(S=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.clearChat)==null?void 0:W.enabled)!=null?S:!0,a=null,i=null;if(o){let se=bi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let u=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=($=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?$:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(R=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",p.append(u,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(q=e==null?void 0:e.layout)==null?void 0:q.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((K=e==null?void 0:e.copy)==null?void 0:K.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,m);let w=h("div","persona-composer-overlay persona-pointer-events-none");w.setAttribute("data-persona-composer-overlay",""),w.style.position="absolute",w.style.left="0",w.style.right="0",w.style.bottom="0",w.style.zIndex="20";let T=Vu({config:e}),{root:B,textNode:k}=zu();return n.append(d,s,l,w),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:w,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:u,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:B,peekTextNode:k}},Ju=(e,t=!0)=>{var w,T,B,k,P,W,S,I,$;if(fo(e))return Cf(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=(w=e==null?void 0:e.layout)==null?void 0:w.header,s=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,o=r?gs(e,r,{showClose:t}):qr({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=ln(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=(k=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?k:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),u=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=fs({config:e}),v=(($=e==null?void 0:e.layout)==null?void 0:$.showFooter)!==!1;s?Uo(n,o,e):(o.header.style.display="none",Uo(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:p,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 Af=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}},Sf=(e,t)=>{if(!e)return null;let n=Af(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Tf=(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},Ef=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bl=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(":"))},yl=320,Xu=320,Mf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),kf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Lf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Pf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),If=(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 u;let l=h("img");l.alt=((u=i.alt)==null?void 0:u.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=`${yl}px`,l.style.maxHeight=`${Xu}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 p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),Ef(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Wf=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(!bl(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=`${yl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Rf=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(!bl(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=`${yl}px`,s.style.maxHeight=`${Xu}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}},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","files");let n=0;return e.forEach(r=>{if(!bl(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}},qo=()=>{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},xl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:qo};if(t){let s=t(r);if(s!==null)return s}return qo()},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},Gu=(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},Df=(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},vl=(e,t,n)=>{var m,v,x,w,T,B;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 k=h("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}let a=(w=t.visibility)!=null?w:"hover",i=(T=t.align)!=null?T:"right",d=(B=t.layout)!=null?B:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(k,P,W)=>{let S=Vt({icon:k,label:P,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",W),S};return r&&u.appendChild(f("copy","Copy message","copy")),s&&u.appendChild(f("thumbs-up","Upvote","upvote")),o&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},hs=(e,t,n,r,s,o)=>{var J,ue,V,de,le,ae,Se,ze,Y,ne,ce,xe,me,oe,Ze,We,fe;let a=n!=null?n:{},i=(J=a.layout)!=null?J:"bubble",d=a.avatar,l=a.timestamp,p=(ue=d==null?void 0:d.show)!=null?ue:!1,u=(V=l==null?void 0:l.show)!=null?V:!1,f=(de=d==null?void 0:d.position)!=null?de:"left",m=(le=l==null?void 0:l.position)!=null?le:"below",v=Df(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 w=Mf(e),T=(Se=(ae=e.content)==null?void 0:ae.trim())!=null?Se:"",k=w.length>0&&T===Xa,P=ui((Y=(ze=o==null?void 0:o.widgetConfig)==null?void 0:ze.features)==null?void 0:Y.streamAnimation),W=(xe=(ce=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.features)==null?void 0:ce.streamAnimation)==null?void 0:xe.plugins,S=e.role==="assistant"&&P.type!=="none"?oa(P.type,W):null,I=e.role==="assistant"&&((me=S==null?void 0:S.isAnimating)==null?void 0:me.call(S,e))===!0,$=e.role==="assistant"&&S!==null&&(!!e.streaming||I);$&&(S!=null&&S.bubbleClass)&&x.classList.add(S.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),$&&S&&(S.containerClass&&D.classList.add(S.containerClass),D.style.setProperty("--persona-stream-step",`${P.speed}ms`),D.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let R=$?mi((oe=e.content)!=null?oe:"",P.buffer,S,e,!!e.streaming):(Ze=e.content)!=null?Ze:"",q=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),K=q;$&&(S==null?void 0:S.wrap)==="char"?K=sa(q,"char",e.id,{skipTags:S.skipTags}):$&&(S==null?void 0:S.wrap)==="word"&&(K=sa(q,"word",e.id,{skipTags:S.skipTags}));let se=null;if(k?(se=document.createElement("div"),se.innerHTML=K,se.style.display="none",D.appendChild(se)):D.innerHTML=K,$&&(S!=null&&S.useCaret)&&!k&&T){let X=gi(),$e=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ht=$e[$e.length-1];if(Ht!=null&&Ht.parentNode)Ht.parentNode.insertBefore(X,Ht.nextSibling);else{let he=D.lastElementChild;he?he.appendChild(X):D.appendChild(X)}}if(u&&m==="inline"&&e.createdAt){let X=Gu(e,l);X.classList.add("persona-ml-2","persona-inline"),D.appendChild(X)}if(w.length>0){let X=If(w,!k&&!!T,()=>{k&&se&&(se.style.display="")});X?x.appendChild(X):k&&se&&(se.style.display="")}let Re=kf(e);if(Re.length>0){let X=Wf(Re);X&&x.appendChild(X)}let Ge=Lf(e);if(Ge.length>0){let X=Rf(Ge);X&&x.appendChild(X)}let Ce=Pf(e);if(Ce.length>0){let X=Hf(Ce);X&&x.appendChild(X)}if(x.appendChild(D),u&&m==="below"&&e.createdAt){let X=Gu(e,l);X.classList.add("persona-mt-1"),x.appendChild(X)}let He=e.role==="assistant"?Sf(e.stopReason,(fe=(We=o==null?void 0:o.widgetConfig)==null?void 0:We.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(R&&R.trim()),$e=P.placeholder==="skeleton",Ht=$e&&P.buffer==="line"&&X;if(X)Ht&&x.appendChild(aa());else if($e)x.appendChild(aa());else{let he=xl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&x.appendChild(he)}}if(He&&e.stopReason&&!e.streaming&&(T||(D.style.display="none"),x.appendChild(Tf(e.stopReason,He))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=vl(e,r,s);x.appendChild(X)}if(!p||e.role==="system")return x;let Be=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"?Be.append(x,Pe):Be.append(Pe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Be},Qu=(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}):hs(e,t,n,r,s,o)};var bs=new Set,Nf=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Of=(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
+ `):""},Yu=(e,t)=>{let n=bs.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=we(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")},wl=(e,t)=>{var Ge,Ce,He,be,Be,Pe,J,ue,V,de,le;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=(Ce=(Ge=t==null?void 0:t.features)==null?void 0:Ge.reasoningDisplay)!=null?Ce:{},o=s.expandable!==!1,a=o&&bs.has(e.id),i=n.status!=="complete",d=Of(e,(He=s.previewMaxLines)!=null?He:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(be=t==null?void 0:t.reasoning)!=null?be:{},v=String((Be=n.startedAt)!=null?Be:Date.now()),x=()=>{let ae=h("span","");return ae.setAttribute("data-tool-elapsed",v),ae.textContent=ja(n),ae},w=(Pe=m.renderCollapsedSummary)==null?void 0:Pe.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ja(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(u.textContent=w,p.appendChild(u)):w instanceof HTMLElement?p.appendChild(w):(u.textContent=f,p.appendChild(u));let T=h("span","persona-text-xs persona-text-persona-primary");T.textContent=cu(n),p.appendChild(T);let B=(J=s.loadingAnimation)!=null?J:"none",k=m.activeTextTemplate,P=m.completeTextTemplate,W=i?k:P,S=w instanceof HTMLElement,I=(ae,Se,ze)=>{let Y=ze;for(let ne of Se){let ce=h("span","persona-tool-char");ce.style.setProperty("--char-index",String(Y)),ce.textContent=ne===" "?"\xA0":ne,ae.appendChild(ce),Y++}return Y},$=(ae,Se)=>{u.textContent="";let ze=Ua(ae,""),Y=0;for(let ne of ze){let ce=ne.styles.length>0?(()=>{let xe=h("span",ne.styles.map(me=>`persona-tool-text-${me}`).join(" "));return u.appendChild(xe),xe})():u;if(ne.isDuration&&i)ce.appendChild(x());else{let xe=ne.isDuration?ja(n):ne.text;Se?Y=I(ce,xe,Y):ce.appendChild(document.createTextNode(xe))}}};if(!S&&W)if(T.style.display="none",u.style.display="",i&&B!=="none"){let ae=(ue=m.loadingAnimationDuration)!=null?ue:2e3;u.setAttribute("data-preserve-animation","true"),B==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),$(W,!1)):(u.classList.add(`persona-tool-loading-${B}`),u.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),B==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),$(W,!0))}else $(W,!1);else if(!S&&i&&B!=="none"){u.style.display="";let ae=(V=m.loadingAnimationDuration)!=null?V:2e3;if(u.setAttribute("data-preserve-animation","true"),B==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ae}ms`);else{u.classList.add(`persona-tool-loading-${B}`),u.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),B==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Se=u.textContent||f;u.textContent="",I(u,Se,0)}n.status==="complete"&&(u.style.display="none")}else S||(n.status==="complete"?u.style.display="none":u.style.display="");let D=null;if(o){D=h("div","persona-flex persona-items-center");let Se=we(a?"chevron-up":"chevron-down",16,"currentColor",2);Se?D.appendChild(Se):D.textContent=a?"Hide":"Show";let ze=h("div","persona-flex persona-items-center persona-ml-auto");ze.append(D),l.append(p,ze)}else l.append(p);let R=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let ae=(le=(de=t==null?void 0:t.reasoning)==null?void 0:de.renderCollapsedPreview)==null?void 0:le.call(de,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Nf(R,ae)||(R.textContent=d),R.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,R),r;let q=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");q.style.display=a?"":"none";let K=n.chunks.join(""),se=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return se.textContent=K||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),q.appendChild(se),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let Se=we(a?"chevron-up":"chevron-down",16,"currentColor",2);Se?D.appendChild(Se):D.textContent=a?"Hide":"Show"}q.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(l,R,q),r};var ys=new Set,Ff=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$f=(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=ls(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},_f=(e,t)=>{var p,u,f,m,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",o=$f(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?du(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=nl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=nl(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Zu=(e,t,n)=>{var p;let r=ys.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},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 u=s.toggleTextColor||s.headerTextColor||"currentColor",f=we(r?"chevron-up":"chevron-down",16,u,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")},Cl=(e,t)=>{var K,se,Re,Ge,Ce,He,be,Be,Pe;let n=e.toolCall,r=(K=t==null?void 0:t.toolCall)!=null?K:{},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),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let o=(Re=(se=t==null?void 0:t.features)==null?void 0:se.toolCallDisplay)!=null?Re:{},a=o.expandable!==!1,i=a&&ys.has(e.id),{summary:d,previewText:l,isActive:p}=_f(e,t),u=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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.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((Ge=n.startedAt)!=null?Ge:Date.now()),x=()=>{let J=h("span","");return J.setAttribute("data-tool-elapsed",v),J.textContent=Ks(n),J},w=(He=r.renderCollapsedSummary)==null?void 0:He.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ce=o.collapsedMode)!=null?Ce:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ks(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(m.textContent=w,f.appendChild(m)):w instanceof HTMLElement?f.appendChild(w):(m.textContent=d,f.appendChild(m));let T=(be=o.loadingAnimation)!=null?be:"none",B=r.activeTextTemplate,k=r.completeTextTemplate,P=p?B:k,W=w instanceof HTMLElement,S=(J,ue,V)=>{let de=V;for(let le of ue){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(de)),ae.textContent=le===" "?"\xA0":le,J.appendChild(ae),de++}return de},I=(J,ue)=>{var ae;m.textContent="";let V=((ae=n.name)==null?void 0:ae.trim())||"tool",de=Ua(J,V),le=0;for(let Se of de){let ze=Se.styles.length>0?(()=>{let Y=h("span",Se.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return m.appendChild(Y),Y})():m;if(Se.isDuration&&p)ze.appendChild(x());else{let Y=Se.isDuration?Ks(n):Se.text;ue?le=S(ze,Y,le):ze.appendChild(document.createTextNode(Y))}}};if(!W)if(p&&T!=="none"){let J=(Be=r.loadingAnimationDuration)!=null?Be:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),P&&I(P,!1);else if(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),T==="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)),P)I(P,!0);else{let ue=m.textContent||d;m.textContent="",S(m,ue,0)}}else P&&I(P,!1);let $=null;if(a){$=h("div","persona-flex persona-items-center");let J=r.toggleTextColor||r.headerTextColor||"currentColor",ue=we(i?"chevron-up":"chevron-down",16,J,2);ue?$.appendChild(ue):$.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append($),u.append(f,V)}else u.append(f);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","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let J=(Pe=r.renderCollapsedPreview)==null?void 0:Pe.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Ff(D,J)||(D.textContent=l),D.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(u,D),s;let R=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let J=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?J.style.color=r.contentTextColor:r.headerTextColor&&(J.style.color=r.headerTextColor),J.textContent=n.name,R.appendChild(J)}if(n.args!==void 0){let J=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ue.style.color=r.labelTextColor),ue.textContent="Arguments";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=ls(n.args),J.append(ue,V),R.appendChild(J)}if(n.chunks&&n.chunks.length){let J=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ue.style.color=r.labelTextColor),ue.textContent="Activity";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=n.chunks.join(""),J.append(ue,V),R.appendChild(J)}if(n.status==="complete"&&n.result!==void 0){let J=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ue.style.color=r.labelTextColor),ue.textContent="Result";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=ls(n.result),J.append(ue,V),R.appendChild(J)}if(n.status==="complete"&&typeof n.duration=="number"){let J=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(J.style.color=r.contentTextColor),J.textContent=`Duration: ${n.duration}ms`,R.appendChild(J)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let J=r.toggleTextColor||r.headerTextColor||"currentColor",ue=we(i?"chevron-up":"chevron-down",16,J,2);ue?$.appendChild(ue):$.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),s.append(u,D,R),s};var bo=require("partial-json");var Sl="ask_user_question",Al=8,xs="data-persona-ask-sheet-for",jf="Other",Uf="Other\u2026",tm="Type your own answer here",nm="Send",qf="Next",zf="Back",Vf="Submit all",Kf="Skip",Jf=3,Tl="data-ask-current-index",El="data-ask-question-count",rm="data-ask-answers",Ml="data-ask-grouped",om="data-ask-layout",Gf=e=>e.layout==="pills"?"pills":"rows",Xf=e=>e.getAttribute(om)==="pills"?"pills":"rows",em=!1,sm=e=>e.replace(/["\\]/g,"\\$&"),zr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Sl,Ei=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Vr=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,bo.parse)(s,bo.STR|bo.OBJ|bo.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},pa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Al&&!em&&(em=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Al}.`)),t.slice(0,Al)},Qf=e=>{var t;return(t=pa(e)[0])!=null?t:null},Yf=(e,t)=>{var n;return(n=pa(e)[t])!=null?n:null},am=(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))},im=(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},Zf=(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=im(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},eh=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},th=(e,t,n,r)=>{var p,u,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<Jf;m++)o.appendChild(eh(r));return o}if(d.forEach((m,v)=>{o.appendChild(Zf(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?jf:Uf;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"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(p=t.freeTextPlaceholder)!=null?p:tm,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),x.appendChild(w),v.appendChild(x);let T=im(r,a,d.length);T&&v.appendChild(T),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},lm=(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:tm,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:nm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},nh=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:nm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},rh=(e,t,n)=>{var l,p,u,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:zf,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=(p=n.skipLabel)!=null?p:Kf,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?(u=n.submitAllLabel)!=null?u:Vf:(f=n.nextLabel)!=null?f:qf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},zo=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},gr=e=>{var n;let t=Number((n=e.getAttribute(Tl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},oh=(e,t)=>{e.setAttribute(Tl,String(Math.max(0,Math.floor(t))))},vs=e=>{var n;let t=Number((n=e.getAttribute(El))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(Ml)==="true",sh=(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},ah=(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)))},Mi=(e,t)=>{let{payload:n}=Vr(t),r=pa(n),s=zo(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},dm=e=>{let t=zo(e),n=gr(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 u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});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=""},pm=e=>{if(!yo(e))return;let t=zo(e),n=gr(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}},kl=(e,t,n)=>{let r=Ei(n),s=Xf(e),{payload:o,complete:a}=Vr(t),i=yo(e),d=gr(e),l=vs(e),p=i?Yf(o,d):Qf(o),u=!!(p!=null&&p.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 B=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=B,v.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let B=th(p,r,a,s);x.replaceWith(B)}if(s!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(lm(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(nh(r)):(!u||i)&&w&&w.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let B=rh(d,l,r);T?T.replaceWith(B):e.appendChild(B)}else T&&T.remove();dm(e),pm(e)},ih=(e,t,n)=>{let r=Ei(t),s=Gf(r),o=e.toolCall.id,a=pa(n),i=Math.max(1,a.length),d=i>1,l=sh(e,a),p=d?ah(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(xs,o),u.setAttribute("data-tool-call-id",o),u.setAttribute("data-message-id",e.id),u.setAttribute(El,String(i)),u.setAttribute(Tl,String(p)),u.setAttribute(Ml,d?"true":"false"),u.setAttribute(om,s),cm(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),am(u,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),u.appendChild(f);let w=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),s!=="rows"&&u.appendChild(lm(r,s)),kl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},lh=(e,t,n)=>{let{payload:r}=Vr(t),s=Math.max(1,pa(r).length);s>vs(e)&&(e.setAttribute(El,String(s)),s>1&&!yo(e)&&e.setAttribute(Ml,"true")),kl(e,t,n)},um=(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=Ei(t);am(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=Vr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},ws=(e,t,n)=>{if(!n||!zr(e)||Ei(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${xs}]`).forEach(l=>{l.getAttribute(xs)!==s&&l.remove()});let a=n.querySelector(`[${xs}="${sm(s)}"]`);if(a){lh(a,e,t);return}let{payload:i}=Vr(e),d=ih(e,t,i);n.appendChild(d)},xo=(e,t)=>{if(!e)return;let n=t?`[${xs}="${sm(t)}"]`:`[${xs}]`;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)})},Ll=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),vo=(e,t)=>{let n=zo(e),r=gr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,cm(e,n),dm(e),pm(e)},ki=(e,t,n,r)=>{let s=vs(e),o=Math.max(0,Math.min(s-1,r));oh(e,o),kl(e,t,n)};var Li=new Map,ch=e=>{let n=(e.startsWith(_r)?e.slice(_r.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},mm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,gm=(e,t)=>{var r,s,o;let n=(s=(r=mm(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=Li.get(e))!=null?o:n==="expanded"},fm=(e,t,n)=>{var a,i;let r=mm(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=we(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},hm=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=gm(e,n);fm(r,o,n),s.style.display=o?"":"none"};var Pi=(e,t)=>{var I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,Pe;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=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=($=r==null?void 0:r.borderColor)!=null?$:"var(--persona-approval-border, #fef08a)",o.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!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)":(D=r==null?void 0:r.titleColor)!=null?D:"currentColor",p=we(d,20,l,2);p&&i.appendChild(p);let u=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 J=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",n.status),n.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):n.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):n.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),f.appendChild(J)}u.appendChild(f);let x=n.toolType==="webmcp"||n.toolName.startsWith(_r)?tl(n.toolName):void 0,w=(q=r==null?void 0:r.formatDescription)==null?void 0:q.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{}}),T=!n.toolName,B=w||(T?n.description:`The assistant wants to use \u201C${x!=null?x:ch(n.toolName)}\u201D.`),k=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=B,u.appendChild(k);let P=(K=r==null?void 0:r.detailsDisplay)!=null?K:"collapsed",W=!!n.description&&!T,S=W||!!n.parameters;if(P!=="hidden"&&S){let J=gm(e.id,t),ue=h("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ue.type="button",ue.setAttribute("data-expand-header","true"),ue.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ue.style.color=r.descriptionColor);let V=h("span");V.setAttribute("data-approval-details-label","true");let de=h("span","persona-inline-flex persona-items-center");de.setAttribute("data-approval-details-chevron","true"),ue.append(V,de),fm(ue,J,t),u.appendChild(ue);let le=h("div");if(le.setAttribute("data-approval-details","true"),le.style.display=J?"":"none",W){let ae=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor),ae.textContent=n.description,le.appendChild(ae)}if(n.parameters){let ae=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&&(ae.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ae.style.color=r.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=ls(n.parameters),le.appendChild(ae)}u.appendChild(le)}if(s){let J=h("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let ue=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");ue.type="button",ue.style.backgroundColor=(se=r==null?void 0:r.approveButtonColor)!=null?se:"var(--persona-approval-approve-bg, #22c55e)",ue.style.color=(Re=r==null?void 0:r.approveButtonTextColor)!=null?Re:"#ffffff",ue.setAttribute("data-approval-action","approve");let V=we("shield-check",14,(Ge=r==null?void 0:r.approveButtonTextColor)!=null?Ge:"#ffffff",2);V&&(V.style.marginRight="4px",ue.appendChild(V));let de=document.createTextNode((Ce=r==null?void 0:r.approveLabel)!=null?Ce:"Approve");ue.appendChild(de);let le=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");le.type="button",le.style.backgroundColor=(He=r==null?void 0:r.denyButtonColor)!=null?He:"transparent",le.style.color=(be=r==null?void 0:r.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",le.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,le.setAttribute("data-approval-action","deny");let ae=we("shield-x",14,(Be=r==null?void 0:r.denyButtonTextColor)!=null?Be:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",le.appendChild(ae));let Se=document.createTextNode((Pe=r==null?void 0:r.denyLabel)!=null?Pe:"Deny");le.appendChild(Se),J.append(ue,le),u.appendChild(J)}return a.append(i,u),o.appendChild(a),o};var bm=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 p=document.createDocumentFragment(),u=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=u,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))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var ua=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 ma=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 dh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),ph=new Set(["step_start","execution_start"]),uh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),mh=new Set(["step_complete","agent_turn_complete"]),gh=new Set(["flow_complete","agent_complete"]),ym=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),vm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Vo=(e,t)=>{let n=e[t];return vm(n)?n:void 0};function Pl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function fh(e,t){return typeof t.type=="string"?t.type:e}function hh(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 bh(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 xm(e){var r,s,o,a,i;let t=Vo(e,"result"),n=[Vo(e,"tokens"),Vo(e,"totalTokens"),t?Vo(t,"tokens"):void 0,Vo(e,"usage"),t?Vo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Zn(d.output))!=null?r:Zn(d.outputTokens))!=null?s:Zn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Zn(e.outputTokens))!=null?o:Zn(e.completionTokens))!=null?i:t?(a=Zn(t.outputTokens))!=null?a:Zn(t.completionTokens):void 0}function yh(e){var n,r,s,o,a;let t=Vo(e,"result");return(a=(s=(r=(n=Zn(e.executionTime))!=null?n:Zn(e.executionTimeMs))!=null?r:Zn(e.execution_time))!=null?s:Zn(e.duration))!=null?a:t?(o=Zn(t.executionTime))!=null?o:Zn(t.executionTimeMs):void 0}function xh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ga=class{constructor(t=xh){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:Ii(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(!vm(n)){ym.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=fh(t,n),s=this.now();if(dh.has(r)){this.startRun(s);return}if(ph.has(r)){this.run||this.startRun(s);return}if(uh.has(r)){if(!bh(r,n))return;let a=hh(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+Pl(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ii(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(mh.has(r)){if(!this.run)return;let a=this.run,i=xm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Pl(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:Ii(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(gh.has(r)){if(!this.run)return;let a=this.run,i=xm(n),d=i!=null?i:a.exactOutputTokens+Pl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:Ii(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(ym.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=yh(n);return o!=null?o:r-t.startedAt}};function Cs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var vh={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)"}},wh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ch=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ah=100;function Sh(e,t){let n={...vh,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return wh}function Th(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Eh(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 Mh(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 kh(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 Lh(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 Ph(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ih(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 Wh(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 Il(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");Cs(l,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var K,se;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"),w=we(d?"chevron-down":"chevron-right","14px","currentColor",2);w&&x.appendChild(w);let T=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=(K=r.timestampFormat)!=null?K:"relative";T.textContent=B==="relative"?Th(e.timestamp,n):Eh(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let P=Sh(e.type,r.badgeColors),W=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");W.style.backgroundColor=P.bg,W.style.color=P.text,W.style.borderColor=P.text+"50",W.textContent=e.type;let S=(se=r.descriptionFields)!=null?se:Ch,I=Mh(e.payload,S),$=null;I&&($=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=I);let D=h("div","persona-flex-1 persona-min-w-0"),R=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),q=we("clipboard","12px","currentColor",1.5);return q&&R.appendChild(q),R.addEventListener("click",async Re=>{Re.stopPropagation(),await kh(Lh(e)),R.innerHTML="";let Ge=we("check","12px","currentColor",1.5);Ge&&R.appendChild(Ge),setTimeout(()=>{R.innerHTML="";let Ce=we("clipboard","12px","currentColor",1.5);Ce&&R.appendChild(Ce)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(W),$&&v.appendChild($),v.appendChild(D),v.appendChild(R),m.appendChild(v),d&&m.appendChild(Wh(e,a,i)),m}}function wm(e){var v,x,w,T,B;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",p=(w=i==null?void 0:i.label)!=null?w:"",u=(B=(T=s==null?void 0:s.features)==null?void 0:T.eventStream)!=null?B:{},f=o.find(k=>k.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let k=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return m();function m(){let k=u.classNames,P=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Cs(P,k==null?void 0:k.panel);let W=[],S="",I="",$=null,D=[],R={},q=0,K=ci(),se=0,Re=0,Ge=!1,Ce=null,He=!1,be=0,Be=new Set,Pe=new Map,J="",ue="",V=null,de,le,ae,Se,ze,Y=null,ne=null,ce=null;function xe(){let re=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ve=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Cs(ve,k==null?void 0:k.headerBar);let Et=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Et.textContent="Events",de=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"),de.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",Y=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"),Y.textContent="-- tok/s",ce=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"),ce.style.display="none",ce.style.pointerEvents="none";let tr=ne,An=ce,Nn=()=>{if(!An.textContent)return;let Er=tr.getBoundingClientRect(),On=re.getBoundingClientRect();An.style.left=`${Er.left-On.left}px`,An.style.top=`${Er.bottom-On.top+4}px`,An.style.display="block"},bt=()=>{An.style.display="none"};ne.addEventListener("mouseenter",Nn),ne.addEventListener("mouseleave",bt),ne.appendChild(Dn),ne.appendChild(Y)}let Jt=h("div","persona-flex-1");le=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 nn=h("option","");nn.value="",nn.textContent="All events",le.appendChild(nn),ae=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"),ae.type="button",ae.title="Copy All";let Wt=we("clipboard-copy","12px","currentColor",1.5);Wt&&ae.appendChild(Wt);let kt=h("span","persona-text-xs");kt.textContent="Copy All",ae.appendChild(kt),ve.appendChild(Et),ve.appendChild(de),ne&&ve.appendChild(ne),ve.appendChild(Jt),ve.appendChild(le),ve.appendChild(ae);let wt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Cs(wt,k==null?void 0:k.searchBar);let At=we("search","14px","var(--persona-muted, #9ca3af)",1.5),Gt=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");At&&Gt.appendChild(At),Se=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"),Cs(Se,k==null?void 0:k.searchInput),Se.type="text",Se.placeholder="Search event payloads...",ze=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"),ze.type="button",ze.style.display="none";let ot=we("x","12px","currentColor",2);return ot&&ze.appendChild(ot),wt.appendChild(Gt),wt.appendChild(Se),wt.appendChild(ze),re.appendChild(ve),re.appendChild(wt),ce&&re.appendChild(ce),re}let me,oe=o.find(re=>re.renderEventStreamToolbar);if(oe!=null&&oe.renderEventStreamToolbar&&s){let re=oe.renderEventStreamToolbar({config:s,defaultRenderer:()=>xe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ve=>{S=ve,Bn(),F()},onSearchChange:ve=>{I=ve,Bn(),F()}});me=re!=null?re:xe()}else me=xe();let Ze=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");Ze.style.display="none";function We(){if(!a||!Y||!ne)return;let re=a();Y.textContent=Ph(re);let ve=Ih(re);ce&&(ce.textContent=ve,ve||(ce.style.display="none")),ve?ne.setAttribute("aria-label",ve):ne.removeAttribute("aria-label")}let fe=h("div","persona-flex-1 persona-min-h-0 persona-relative"),X=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let $e=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Cs($e,k==null?void 0:k.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Ht=we(l,"14px","currentColor",2);Ht&&$e.appendChild(Ht);let he=h("span","");he.textContent=p,$e.appendChild(he);let pe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");pe.style.display="none",fe.appendChild(X),fe.appendChild(pe),fe.appendChild($e),P.setAttribute("tabindex","0"),P.appendChild(me),P.appendChild(Ze),P.appendChild(fe);function Pn(){let re=t.getAll(),ve={};for(let kt of re)ve[kt.type]=(ve[kt.type]||0)+1;let Et=Object.keys(ve).sort(),Jt=Et.length!==D.length||!Et.every((kt,wt)=>kt===D[wt]),nn=!Jt&&Et.some(kt=>ve[kt]!==R[kt]),Cn=re.length!==Object.values(R).reduce((kt,wt)=>kt+wt,0);if(!Jt&&!nn&&!Cn||(D=Et,R=ve,!le))return;let Wt=le.value;if(le.options[0].textContent="All events",Jt){for(;le.options.length>1;)le.remove(1);for(let kt of Et){let wt=h("option","");wt.value=kt,wt.textContent=`${kt} (${ve[kt]||0})`,le.appendChild(wt)}Wt&&Et.includes(Wt)?le.value=Wt:Wt&&(le.value="",S="")}else for(let kt=1;kt<le.options.length;kt++){let wt=le.options[kt];wt.textContent=`${wt.value} (${ve[wt.value]||0})`}}function Ut(){let re=t.getAll();if(S&&(re=re.filter(ve=>ve.type===S)),I){let ve=I.toLowerCase();re=re.filter(Et=>Et.type.toLowerCase().includes(ve)||Et.payload.toLowerCase().includes(ve))}return re}function gn(){return S!==""||I!==""}function Bn(){q=0,se=0,K.resume(),$e.style.display="none"}function er(re){Be.has(re)?Be.delete(re):Be.add(re),V=re;let ve=X.scrollTop,Et=K.isFollowing();He=!0,K.pause(),F(),X.scrollTop=ve,Et&&K.resume(),He=!1}function Ue(){return ta(X,50)}function F(){Re=Date.now(),Ge=!1,We(),Pn();let re=t.getEvictedCount();re>0?(Ze.textContent=`${re.toLocaleString()} older events truncated`,Ze.style.display=""):Ze.style.display="none",W=Ut();let ve=W.length,Et=t.getSize()>0;de&&(de.textContent=String(t.getSize())),ve===0&&Et&&gn()?(pe.textContent=I?`No events matching '${I}'`:"No events matching filter",pe.style.display="",X.style.display="none"):(pe.style.display="none",X.style.display=""),ae&&(ae.title=gn()?`Copy Filtered (${ve})`:"Copy All"),d&&!K.isFollowing()&&ve>q&&(se+=ve-q,he.textContent=p?`${p}${se>0?` (${se})`:""}`:"",$e.style.display=""),q=ve;let Jt=t.getAll(),nn=Jt.length>0?Jt[0].timestamp:0,Cn=new Set(W.map(wt=>wt.id));for(let wt of Be)Cn.has(wt)||Be.delete(wt);let Wt=S!==J||I!==ue,kt=Pe.size===0&&W.length>0;if(Wt||kt||W.length===0){X.innerHTML="",Pe.clear();let wt=document.createDocumentFragment();for(let At=0;At<W.length;At++){let Gt=Il(W[At],At,nn,u,Be,er,o,s);Pe.set(W[At].id,Gt),wt.appendChild(Gt)}X.appendChild(wt),J=S,ue=I,V=null}else{if(V!==null){let At=Pe.get(V);if(At&&At.parentNode===X){let Gt=W.findIndex(ot=>ot.id===V);if(Gt>=0){let ot=Il(W[Gt],Gt,nn,u,Be,er,o,s);X.insertBefore(ot,At),At.remove(),Pe.set(V,ot)}}V=null}let wt=new Set(W.map(At=>At.id));for(let[At,Gt]of Pe)wt.has(At)||(Gt.remove(),Pe.delete(At));for(let At=0;At<W.length;At++){let Gt=W[At];if(!Pe.has(Gt.id)){let ot=Il(Gt,At,nn,u,Be,er,o,s);Pe.set(Gt.id,ot),X.appendChild(ot)}}}K.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Ee(){if(Date.now()-Re>=Ah){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),F();return}Ge||(Ge=!0,Ce=requestAnimationFrame(()=>{Ce=null,F()}))}let De=(re,ve)=>{if(!ae)return;ae.innerHTML="";let Et=we(re,"12px","currentColor",1.5);Et&&ae.appendChild(Et);let Jt=h("span","persona-text-xs");Jt.textContent="Copy All",ae.appendChild(Jt),setTimeout(()=>{ae.innerHTML="";let nn=we("clipboard-copy","12px","currentColor",1.5);nn&&ae.appendChild(nn);let Cn=h("span","persona-text-xs");Cn.textContent="Copy All",ae.appendChild(Cn),ae.disabled=!1},ve)},Ne=async()=>{if(ae){ae.disabled=!0;try{let re;gn()?re=W:n?(re=await n(),re.length===0&&(re=t.getAll())):re=t.getAll();let ve=re.map(Et=>{try{return JSON.parse(Et.payload)}catch{return Et.payload}});await navigator.clipboard.writeText(JSON.stringify(ve,null,2)),De("check",1500)}catch{De("x",1500)}}},_e=()=>{le&&(S=le.value,Bn(),F())},mt=()=>{!Se||!ze||(ze.style.display=Se.value?"":"none",$&&clearTimeout($),$=setTimeout(()=>{I=Se.value,Bn(),F()},150))},at=()=>{!Se||!ze||(Se.value="",I="",ze.style.display="none",$&&clearTimeout($),Bn(),F())},It=()=>{if(He)return;let re=X.scrollTop,{action:ve,nextLastScrollTop:Et}=di({following:K.isFollowing(),currentScrollTop:re,lastScrollTop:be,nearBottom:Ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=Et,ve==="resume"?(K.resume(),se=0,$e.style.display="none"):ve==="pause"&&(K.pause(),d&&(he.textContent=p,$e.style.display=""))},Kt=re=>{let ve=pi({following:K.isFollowing(),deltaY:re.deltaY,nearBottom:Ue(),resumeWhenNearBottom:!0});ve==="pause"?(K.pause(),d&&(he.textContent=p,$e.style.display="")):ve==="resume"&&(K.resume(),se=0,$e.style.display="none")},z=()=>{d&&(X.scrollTop=X.scrollHeight,K.resume(),se=0,$e.style.display="none")},qt=re=>{let ve=re.target;if(!ve||ve.closest("button"))return;let Et=ve.closest("[data-event-id]");if(!Et)return;let Jt=Et.getAttribute("data-event-id");Jt&&er(Jt)},et=re=>{if((re.metaKey||re.ctrlKey)&&re.key==="f"){re.preventDefault(),Se==null||Se.focus(),Se==null||Se.select();return}re.key==="Escape"&&(Se&&document.activeElement===Se?(at(),Se.blur(),P.focus()):r&&r())};ae&&ae.addEventListener("click",Ne),le&&le.addEventListener("change",_e),Se&&Se.addEventListener("input",mt),ze&&ze.addEventListener("click",at),X.addEventListener("scroll",It),X.addEventListener("wheel",Kt,{passive:!0}),X.addEventListener("click",qt),$e.addEventListener("click",z),P.addEventListener("keydown",et);function _t(){$&&clearTimeout($),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ge=!1,Pe.clear(),ae&&ae.removeEventListener("click",Ne),le&&le.removeEventListener("change",_e),Se&&Se.removeEventListener("input",mt),ze&&ze.removeEventListener("click",at),X.removeEventListener("scroll",It),X.removeEventListener("wheel",Kt),X.removeEventListener("click",qt),$e.removeEventListener("click",z),P.removeEventListener("keydown",et)}return{element:P,update:Ee,destroy:_t}}}function Cm(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 p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.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",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(p,u),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 Am=(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",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Cm(e,t)});if(p)return p}return Cm(e,t)};var Wl=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)})}},Kr=new Wl;Kr.register("PersonaArtifactCard",Am);function Rh(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 Sm(e,t){var le,ae,Se,ze;let n=(ae=(le=e.features)==null?void 0:le.artifacts)==null?void 0:ae.layout,s=((Se=n==null?void 0:n.toolbarPreset)!=null?Se:"default")==="document",o=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?Bo(e.markdown):null,i=as(e.sanitize),d=Y=>{let ne=a?a(Y):Do(Y);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,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),q==null||q.hide()};l&&l.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let u=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");u.setAttribute("data-persona-theme-zone","artifact-pane"),s&&u.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 Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let x="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=s?Vt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Vt({icon:"eye",label:"Rendered view"}),B=s?Vt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Vt({icon:"code-2",label:"Source"}),k=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),P=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(W&&S&&S.length>0),$=null,D,R=null,q=null;if(s&&(P||W)&&!I){if(D=P?ca({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Y=we("chevron-down",14,"currentColor",2);Y&&D.appendChild(Y)}}else s&&I?($=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=P?ca({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Vt({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,R)):s?D=Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=Vt({icon:"copy",label:"Copy"});let K=s?Vt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Vt({icon:"refresh-cw",label:"Refresh"}),se=s?Vt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Vt({icon:"x",label:"Close"}),Re=()=>{var me,oe,Ze;let Y=(me=Pe.find(We=>We.id===J))!=null?me:Pe[Pe.length-1],ne=(oe=Y==null?void 0:Y.id)!=null?oe:null,ce=(Y==null?void 0:Y.artifactType)==="markdown"&&(Ze=Y.markdown)!=null?Ze:"",xe=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:ce,jsonPayload:xe,id:ne}},Ge=async()=>{var me;let{markdown:Y,jsonPayload:ne}=Re(),ce=(me=Pe.find(oe=>oe.id===J))!=null?me:Pe[Pe.length-1],xe=(ce==null?void 0:ce.artifactType)==="markdown"?Y:ce?ne:"";try{await navigator.clipboard.writeText(xe)}catch{}};if(D.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&I){let{markdown:ne,jsonPayload:ce,id:xe}=Re();try{await Y({actionId:"primary",artifactId:xe,markdown:ne,jsonPayload:ce})}catch{}return}await Ge()}),R&&(S!=null&&S.length)){let Y=()=>{var ce;return(ce=u.closest("[data-persona-root]"))!=null?ce:document.body},ne=()=>{q=ho({items:S.map(ce=>({id:ce.id,label:ce.label})),onSelect:async ce=>{let{markdown:xe,jsonPayload:me,id:oe}=Re(),Ze=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ze?await Ze({actionId:ce,artifactId:oe,markdown:xe,jsonPayload:me}):ce==="markdown"||ce==="md"?await navigator.clipboard.writeText(xe):ce==="json"||ce==="source"?await navigator.clipboard.writeText(me):await navigator.clipboard.writeText(xe||me)}catch{}},anchor:$!=null?$:R,position:"bottom-right",portal:Y()})};u.isConnected?ne():requestAnimationFrame(ne),R.addEventListener("click",ce=>{ce.stopPropagation(),q==null||q.toggle()})}K.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}V()}),se.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let Ce=()=>{s&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),B.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Ce(),V()}),B.addEventListener("click",()=>{x="source",Ce(),V()});let He=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),w.append(T,B),$?k.append($,K,se):k.append(D,K,se),f.append(w,He,k),Ce()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let be=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"),Be=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(be.style.paddingLeft=o,be.style.paddingRight=o,Be.style.padding=o),u.appendChild(f),u.appendChild(be),u.appendChild(Be);let Pe=[],J=null,ue=!1,V=()=>{var xe,me,oe,Ze;let Y=s&&Pe.length<=1;be.classList.toggle("persona-hidden",Y),be.replaceChildren();for(let We of Pe){let fe=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");fe.type="button",fe.textContent=We.title||We.id.slice(0,8),We.id===J&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(We.id)),be.appendChild(fe)}Be.replaceChildren();let ne=J&&Pe.find(We=>We.id===J)||Pe[Pe.length-1];if(!ne)return;if(s){let We=ne.artifactType==="markdown"?"MD":(xe=ne.component)!=null?xe:"Component",X=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";He.textContent=`${X} \xB7 ${We}`}else m.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&x==="source"){let fe=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(me=ne.markdown)!=null?me:"",Be.appendChild(fe);return}let We=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((oe=ne.markdown)!=null?oe:""),Be.appendChild(We);return}let ce=ne.component?Kr.get(ne.component):void 0;if(ce){let fe={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ce((Ze=ne.props)!=null?Ze:{},fe);if(X){Be.appendChild(X);return}}catch{}}Be.appendChild(Rh(ne))},de=()=>{var ne;let Y=Pe.length>0;if(u.classList.toggle("persona-hidden",!Y),l){let ce=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,me=((ne=ce==null?void 0:ce.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&me&&ue?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(Y){var ne,ce,xe;Pe=Y.artifacts,J=(xe=(ce=Y.selectedId)!=null?ce:(ne=Y.artifacts[Y.artifacts.length-1])==null?void 0:ne.id)!=null?xe:null,Pe.length>0&&(ue=!0),V(),de()},setMobileOpen(Y){ue=Y,!Y&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):de()}}}function fr(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 Tm(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"),!fr(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 Wi(e,t){var d,l,p,u,f,m,v,x,w,T;if(!fr(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),Tm(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",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"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=(w=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Tm(e,t)}var Em=["panel","seamless"];function Ri(e,t){var i,d,l,p,u,f;for(let m of Em)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"),!fr(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=Em.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.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||!fr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Bh(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 Dh(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 Nh(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Oh(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function km(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 Lm(e,t,n,r,s,o){let a=Bh(s,200),i=Oh(t,n,r,200);i=Math.max(a,i);let d=Dh(o);return d!==null&&(i=Math.min(i,d)),Nh(e,a,i)}var Pm={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"}},Rl=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,w;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=Pm[a])!=null?x:Pm.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 T=h("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var S,I;let B=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${t.id}-${a}-${T.name}`;let k=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,B.appendChild(k);let P=(S=T.type)!=null?S:"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),W.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",W.id=`${t.id}-${a}-${T.name}`,W.name=T.name,W.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(W.required=!0),B.appendChild(W),p.appendChild(B)});let u=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=(w=i.submitLabel)!=null?w:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),o.replaceChildren(d,p),p.addEventListener("submit",async T=>{var W,S;T.preventDefault();let B=(W=n.formEndpoint)!=null?W:"/form",k=new FormData(p),P={};k.forEach((I,$)=>{P[$]=I}),P.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let I=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let $=await I.json();f.textContent=(S=$.message)!=null?S:"Thanks! We'll be in touch soon.",$.success&&$.nextPrompt&&await r.sendMessage(String($.nextPrompt))}catch(I){f.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Hl=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()}},fa=new Hl;var Im=()=>{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 Fh=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},$h=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},ha=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Fh(e),n=$h(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}},Bl=e=>typeof e=="string"?e:e==null?"":String(e),Ko={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=Bl(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:Bl(n.text)}}},Wm=e=>Array.isArray(e)?e.map(t=>String(t)):[],ba=e=>{let t=new Set(Wm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Wm(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,p)=>l||(p==null?void 0:p({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 p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var _h=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}},jh=e=>e.map(t=>({...t,streaming:!1})),Uh=e=>e.map(t=>({...t,status:"complete"})),Hi=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?_h(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?jh(n.messages):void 0,artifacts:n.artifacts?Uh(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 As=require("partial-json");function qh(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function zh(e,t){if(!qh(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 Bi(){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,As.parse)(n,As.STR|As.OBJ),o=zh(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Rm(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Di(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=Kr.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 Hm(){let e=Bi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Bm(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 Ni(e){let t=Bm(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 Oi(e){let t=Bm(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 Vh=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fi(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=Vh}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=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 w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let S=1;S<=5;S++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),I.title=l[S-1],I.dataset.rating=String(S),I.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
29
29
  </svg>
30
- `,W.addEventListener("click",()=>{m=S,E.forEach(($,N)=>{let H=N<S;$.classList.toggle("selected",H),$.setAttribute("aria-checked",N===S-1?"true":"false")})}),E.push(W),w.appendChild(W)}g.appendChild(w);let B=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),S.appendChild(B),g.appendChild(S)}let L=document.createElement("div");L.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{n==null||n(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(m===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let S=(B==null?void 0:B.value.trim())||void 0;await t(m,S),p.remove()}catch(S){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),L.appendChild(I),L.appendChild(R),g.appendChild(L),p.appendChild(g),p}function Ni(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:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.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 w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=s,v.appendChild(w),u.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let B=document.createElement("div");B.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=l;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=p,B.appendChild(L),B.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let S=[];for(let j=0;j<=10;j++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${j} out of 10`),V.textContent=String(j),V.dataset.rating=String(j),j<=6?V.classList.add("persona-feedback-detractor"):j<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{g=j,S.forEach((se,He)=>{se.classList.toggle("selected",He===j),se.setAttribute("aria-checked",He===j?"true":"false")})}),S.push(V),R.appendChild(V)}E.appendChild(B),E.appendChild(R),u.appendChild(E);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=o,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),u.appendChild(j)}let $=document.createElement("div");$.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{n==null||n(),m.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await t(g,j),m.remove()}catch(j){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),$.appendChild(N),$.appendChild(H),u.appendChild($),m.appendChild(u),m}var xs="persona-chat-history",Nh=30*1e3,Fh={"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 Oh(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=Fh[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 Fi(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 $h(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 _h(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Rl=e=>!e||typeof e!="object"?{}:{...e},Mm=e=>e.map(t=>({...t,streaming:!1})),km=(e,t,n)=>{let r=e!=null&&e.markdown?Io(e.markdown):null,s=ts(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,p,m;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(m=i!=null?i:o.text)!=null?m:""}):r?d=r(a):d=Wo(a),s?s(d):d}};function Lm(e){var i,d,l,p;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=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=be(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=h("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Oi=(e,t,n)=>{var rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc;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=ni(t),s=pa.getForInstance(r.plugins);r.components&&Ur.registerAll(r.components);let o=wm(),i=r.persistState===!1?null:(rc=r.storageAdapter)!=null?rc:Ii(),d={},l=null,p=!1,m=c=>{if(r.onStateLoaded)try{let f=r.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:y,open:b}=f;return b&&(p=!0),y}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let y=f!=null?f:{messages:[],metadata:{}};return m(y)});else{let f=c!=null?c:{messages:[],metadata:{}},y=m(f);y.metadata&&(d=Rl(y.metadata)),(oc=y.messages)!=null&&oc.length&&(r={...r,initialMessages:y.messages}),(sc=y.artifacts)!=null&&sc.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(ac=y.selectedArtifactId)!=null?ac:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=m({messages:[],metadata:{}});(ic=c.messages)!=null&&ic.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,u=c=>{var y;d=(y=c({...d}))!=null?y:{},Ko()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ua],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Uo.message,Uo.messageAndClick],w=ma({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let E=(cc=(lc=r.launcher)==null?void 0:lc.enabled)!=null?cc:!0,B=(pc=(dc=r.launcher)==null?void 0:dc.autoExpand)!=null?pc:!1,L=(uc=r.autoFocusInput)!=null?uc:!1,I=B,R=E,S=(gc=(mc=r.layout)==null?void 0:mc.header)==null?void 0:gc.layout,W=!1,$=()=>po(r),N=()=>E||$(),H=$()?!1:E?B:!0,j=!1,V=null,se=()=>{j=!0,V&&clearTimeout(V),V=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},He=km(r,w,se),qe=(hc=(fc=r.features)==null?void 0:fc.showReasoning)!=null?hc:!0,Oe=(bc=(yc=r.features)==null?void 0:yc.showToolCalls)!=null?bc:!0,fe=(vc=(xc=r.features)==null?void 0:xc.showEventStreamToggle)!=null?vc:!1,xe=(wc=(Cc=r.features)==null?void 0:Cc.scrollToBottom)!=null?wc:{},De=`${(Sc=typeof r.persistState=="object"?(Ac=r.persistState)==null?void 0:Ac.keyPrefix:void 0)!=null?Sc:"persona-"}event-stream`,te=fe?new ca(De):null,Ie=(Mc=(Ec=(Tc=r.features)==null?void 0:Tc.eventStream)==null?void 0:Ec.maxEvents)!=null?Mc:2e3,K=fe?new la(Ie,te):null,ce=fe?new da:null,Ce=null,he=!1,we=null,Ke=0;te==null||te.open().then(()=>K==null?void 0:K.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Q={onCopy:c=>{var f,y;o.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onCopy)==null||y.call(f,c)},onFeedback:c=>{var f,y;o.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onFeedback)==null||y.call(f,c)}},ne=(kc=r.statusIndicator)!=null?kc:{},ae=c=>{var f,y,b,k;return c==="idle"?(f=ne.idleText)!=null?f:fn.idle:c==="connecting"?(y=ne.connectingText)!=null?y:fn.connecting:c==="connected"?(b=ne.connectedText)!=null?b:fn.connected:c==="error"?(k=ne.errorText)!=null?k:fn.error:fn[c]};function me(c,f,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=f,k.style.color="inherit",k.style.textDecoration="none",c.appendChild(k)}else c.textContent=f}let{wrapper:le,panel:oe,pillRoot:Ye}=ju(r),We=Uu(r,N()),{container:de,body:G,messagesWrapper:je,suggestions:Mt,textarea:pe,sendButton:ie,sendButtonWrapper:kn,composerForm:$t,statusText:cn,introTitle:Bn,introSubtitle:Yn,closeButton:ze,iconHolder:O,headerTitle:Se,headerSubtitle:Ne,header:Fe,footer:Ue,actionsRow:pt,leftActions:ot,rightActions:St}=We,Ut=We.setSendButtonMode,z=We.micButton,_t=We.micButtonWrapper,Ze=We.attachmentButton,Ft=We.attachmentButtonWrapper,re=We.attachmentInput,ge=We.attachmentPreviewsContainer;de.classList.add("persona-relative"),G.classList.add("persona-relative");let Ct=12,qt=()=>{var c;return(c=xe.label)!=null?c:""},en=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},yn=()=>xe.enabled!==!1,Tt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let wt=h("span","persona-flex persona-items-center"),ht=h("span","");Tt.append(wt,ht),de.appendChild(Tt);let bt=()=>{let f=Ue.style.display==="none"?0:Ue.offsetHeight;Tt.style.bottom=`${f+Ct}px`};bt();let Vt=()=>{let c=!!qt();Tt.setAttribute("aria-label",qt()||"Jump to latest"),Tt.title=qt(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let f=be(en(),"14px","currentColor",2);f?(wt.appendChild(f),wt.style.display=""):wt.style.display="none",ht.textContent=qt(),ht.style.display=c?"":"none"};Vt();let nt=null,Dn=null,Zn=s.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:r,defaultRenderer:()=>{let f=$r({config:r,showClose:N()});return Oo(de,f,r),f.header},onClose:()=>Ht(!1,"user")});if(c){let f=de.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Fe=c)}}let bn=()=>{var f,y,b,k;if(!K)return;if(he=!0,!Ce&&K&&(Ce=um({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Nn(),config:r,plugins:s,getThroughput:()=>{var F;return(F=ce==null?void 0:ce.getMetric())!=null?F:{status:"idle"}}})),Ce&&(G.style.display="none",(f=Ue.parentNode)==null||f.insertBefore(Ce.element,Ue),Ce.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let F=(k=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:k.toggleButtonActive;F&&F.split(/\s+/).forEach(_=>_&&mt.classList.add(_))}let c=()=>{if(!he)return;let F=Date.now();F-Ke>=200&&(Ce==null||Ce.update(),Ke=F),we=requestAnimationFrame(c)};Ke=0,we=requestAnimationFrame(c),Rr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,f,y;if(he){if(he=!1,Ce&&Ce.element.remove(),G.style.display="",mt){mt.style.boxShadow="";let b=(y=(f=(c=r.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(k=>k&&mt.classList.remove(k))}we!==null&&(cancelAnimationFrame(we),we=null),Rr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(fe){let c=(Pc=(Lc=r.features)==null?void 0:Lc.eventStream)==null?void 0:Pc.classNames,f="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",f),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=We.clearChatButtonWrapper,k=We.closeButtonWrapper,F=b||k;F&&F.parentNode===Fe?Fe.insertBefore(mt,F):Fe.appendChild(mt),mt.addEventListener("click",()=>{he?Nn():bn()})}let vr=c=>{var b,k,F;let f=r.attachments;if(!(f!=null&&f.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 _=c.querySelector("[data-persona-composer-form]");_!=null&&_.parentNode?_.parentNode.insertBefore(y,_):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let _=h("input");_.type="file",_.accept=((b=f.allowedTypes)!=null?b:Or).join(","),_.multiple=((k=f.maxFiles)!=null?k:4)>1,_.style.display="none",_.setAttribute("aria-label",(F=f.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(_)}},Fn=s.find(c=>c.renderComposer);if(Fn!=null&&Fn.renderComposer){let c=r.composer,f=Fn.renderComposer({config:r,defaultRenderer:()=>ds({config:r}).footer,onSubmit:y=>{var _;if(!T||T.isStreaming())return;let b=y.trim(),k=(_=nt==null?void 0:nt.hasAttachments())!=null?_:!1;if(!b&&!k)return;Ls();let F;k&&(F=[],F.push(...nt.getContentParts()),b&&F.push(qs(b))),T.sendMessage(b,{contentParts:F}),k&&nt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{re==null||re.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Ic=r.voiceRecognition)==null?void 0:Ic.enabled)===!0?()=>{Dn==null||Dn()}:void 0});f&&(Ue.replaceWith(f),Ue=f)}let bo=c=>{let f=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),k=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");f&&($t=f),y&&(pe=y),b&&(ie=b),k&&(z=k,_t=k.parentElement),F&&(cn=F);let _=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Mt=_);let q=c.querySelector(".persona-attachment-button");q&&(Ze=q,Ft=q.parentElement),re=c.querySelector('input[type="file"]'),ge=c.querySelector(".persona-attachment-previews");let D=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");D&&(pt=D)};vr(Ue),bo(Ue);let Ln=(Dc=(Wc=r.layout)==null?void 0:Wc.contentMaxWidth)!=null?Dc:$()?(Bc=(Hc=(Rc=r.launcher)==null?void 0:Rc.composerBar)==null?void 0:Hc.contentMaxWidth)!=null?Bc:"720px":void 0;if(Ln&&(je.style.maxWidth=Ln,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%"),Ln&&$t&&!$()&&($t.style.maxWidth=Ln,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Ln&&Mt&&!$()&&(Mt.style.maxWidth=Ln,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),Ln&&ge&&!$()&&(ge.style.maxWidth=Ln,ge.style.marginLeft="auto",ge.style.marginRight="auto"),(Nc=r.attachments)!=null&&Nc.enabled&&re&&ge){nt=Fo.fromConfig(r.attachments),nt.setPreviewsContainer(ge),re.addEventListener("change",y=>{let b=y.target;nt==null||nt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,f=Lm(c);de.appendChild(f)}(()=>{var b,k;let c=(k=(b=r.layout)==null?void 0:b.slots)!=null?k:{},f=F=>{switch(F){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return je;case"footer-top":return Mt;case"composer":return $t;case"footer-bottom":return cn;default:return null}},y=(F,_)=>{var q;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")Fe.insertBefore(_,Fe.firstChild);else if(F==="header-right")Fe.appendChild(_);else{let D=Fe.querySelector(".persona-flex-col");D?(q=D.parentNode)==null||q.insertBefore(_,D.nextSibling):Fe.appendChild(_)}break;case"body-top":{let D=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(_):G.insertBefore(_,G.firstChild);break}case"body-bottom":G.appendChild(_);break;case"footer-top":Mt.replaceWith(_);break;case"footer-bottom":cn.replaceWith(_);break;default:break}};for(let[F,_]of Object.entries(c))if(_)try{let q=_({config:r,defaultContent:()=>f(F)});q&&y(F,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,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 k=b.getAttribute("data-message-id");if(!k)return;let F=y.getAttribute("data-bubble-type");F==="reasoning"?(us.has(k)?us.delete(k):us.add(k),Ku(k,b)):F==="tool"&&(ms.has(k)?ms.delete(k):ms.add(k),Ju(k,b,r)),ur.delete(k)};je.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))}),je.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))});let Mr=new Map;je.addEventListener("click",c=>{var _;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let k=b.getAttribute("data-actions-for");if(!k)return;let F=y.getAttribute("data-action");if(F==="copy"){let D=T.getMessages().find(Ae=>Ae.id===k);if(D&&Q.onCopy){let Ae=D.content||"";navigator.clipboard.writeText(Ae).then(()=>{y.classList.add("persona-message-action-success");let ue=be("check",14,"currentColor",2);ue&&(y.innerHTML="",y.appendChild(ue)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Z=be("copy",14,"currentColor",2);Z&&(y.innerHTML="",y.appendChild(Z))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),Q.onCopy(D)}}else if(F==="upvote"||F==="downvote"){let D=((_=Mr.get(k))!=null?_:null)===F,Ae=F==="upvote"?"thumbs-up":"thumbs-down";if(D){Mr.delete(k),y.classList.remove("persona-message-action-active");let ue=be(Ae,14,"currentColor",2);ue&&(y.innerHTML="",y.appendChild(ue))}else{let ue=F==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${ue}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Qe=be(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Qe&&(Z.innerHTML="",Z.appendChild(Qe))}Mr.set(k,F),y.classList.add("persona-message-action-active");let ye=be(Ae,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 $e=T.getMessages().find(rt=>rt.id===k);$e&&Q.onFeedback&&Q.onFeedback({type:F,messageId:$e.id,message:$e})}}}),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 k=b.getAttribute("data-message-id");if(!k)return;let F=y.getAttribute("data-approval-action");if(!F)return;let _=F==="approve"?"approved":"denied",D=T.getMessages().find(ue=>ue.id===k);if(!(D!=null&&D.approval))return;let Ae=b.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?T.resolveWebMcpApproval(k,_):T.resolveApproval(D.approval,_)});let xt=null,On=null,$n={artifacts:[],selectedId:null},xn=!1,Pt={current:null};je.addEventListener("click",c=>{var Z,ye,Te,$e,rt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Te=(ye=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Te.call(ye,{type:"download",artifactId:b}))===!0)return;let F=T.getArtifactById(b),_=F==null?void 0:F.markdown,q=(F==null?void 0:F.title)||"artifact";if(!_){let Qe=y.closest("[data-open-artifact]"),it=Qe==null?void 0:Qe.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let ke=T.getMessages().find(Ve=>Ve.id===lt);if(ke!=null&&ke.rawContent)try{let Ve=JSON.parse(ke.rawContent);_=($e=Ve==null?void 0:Ve.props)==null?void 0:$e.markdown,q=((rt=Ve==null?void 0:Ve.props)==null?void 0:rt.title)||q}catch{}}}if(!_)return;let D=new Blob([_],{type:"text/markdown"}),Ae=URL.createObjectURL(D),ue=document.createElement("a");ue.href=Ae,ue.download=`${q}.md`,ue.click(),URL.revokeObjectURL(Ae)}),je.addEventListener("click",c=>{var F,_,q;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((q=(_=(F=r.features)==null?void 0:F.artifacts)==null?void 0:_.onArtifactAction)==null?void 0:q.call(_,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,T.selectArtifact(b),Un())}),je.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let er=We.composerOverlay,tr=(c,f,y)=>{var q,D,Ae,ue;let b=f.trim();if(!b||!Pt.current)return;let k=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",F=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:b,answers:y.structured,values:(D=y.values)!=null?D:y.source==="multi"?b.split(", "):[b],isFreeText:F,source:y.source},bubbles:!0,composed:!0})),fo(er,k);let _=Pt.current.getMessages().find(Z=>{var ye;return((ye=Z.toolCall)==null?void 0:ye.id)===k});(Ae=_==null?void 0:_.agentMetadata)!=null&&Ae.awaitingLocalTool?Pt.current.resolveAskUserQuestion(_,(ue=y.structured)!=null?ue:b):Pt.current.sendMessage(b)},_n=c=>{var k;let f=Pt.current;if(!f)return;let y=(k=c.getAttribute("data-tool-call-id"))!=null?k:"",b=f.getMessages().find(F=>{var _;return((_=F.toolCall)==null?void 0:_.id)===y});b&&f.persistAskUserQuestionProgress(b,{answers:Ei(c,b),currentIndex:lr(c)})},Vr=c=>Object.entries(c).map(([f,y])=>`${f}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),kr=c=>{var k,F,_;if(((F=(k=r.features)==null?void 0:k.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let f=lr(c),y=fs(c);if(f>=y-1)return;let b=(_=Pt.current)==null?void 0:_.getMessages().find(q=>{var D;return((D=q.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});b&&(Mi(c,b,r,f+1),_n(c))};er.addEventListener("click",c=>{var F,_,q,D,Ae,ue,Z,ye,Te,$e,rt,Qe,it,lt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let k=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),k==="dismiss"){let Le=(F=b.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),fo(er,Le);let ke=(_=Pt.current)==null?void 0:_.getMessages().find(Ve=>{var M;return((M=Ve.toolCall)==null?void 0:M.id)===Le});(q=ke==null?void 0:ke.agentMetadata)!=null&&q.awaitingLocalTool&&((D=Pt.current)==null||D.markAskUserQuestionResolved(ke),(Ae=Pt.current)==null||Ae.resolveAskUserQuestion(ke,"(dismissed)"));return}if(k==="pick"){let Le=y.getAttribute("data-option-label");if(!Le)return;let ke=b.getAttribute("data-multi-select")==="true",Ve=go(b);if(Ve&&ke){let M=_o(b)[lr(b)],Ee=new Set(Array.isArray(M)?M:[]);Ee.has(Le)?Ee.delete(Le):Ee.add(Le),ho(b,Array.from(Ee)),_n(b);return}if(Ve){ho(b,Le),_n(b),kr(b);return}if(ke){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=Tl(b).length===0);return}tr(b,Le,{source:"pick",values:[Le]});return}if(k==="submit-multi"){let Le=Tl(b);if(Le.length===0)return;tr(b,Le.join(", "),{source:"multi",values:Le});return}if(k==="open-free-text"){let Le=b.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let ke=Le.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(k==="focus-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(k==="submit-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]'),ke=(ue=Le==null?void 0:Le.value)!=null?ue:"";if(!ke.trim())return;if(go(b)){ho(b,ke.trim()),_n(b),kr(b);return}tr(b,ke,{source:"free-text"});return}if(k==="next"||k==="back"){if(!Pt.current)return;let Le=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",ke=Pt.current.getMessages().find(Ge=>{var ve;return((ve=Ge.toolCall)==null?void 0:ve.id)===Le});if(!ke)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),M=(Te=(ye=Ve==null?void 0:Ve.value)==null?void 0:ye.trim())!=null?Te:"";if(M){let Ge=_o(b)[lr(b)];(typeof Ge!="string"||Ge!==M)&&ho(b,M)}let Ee=k==="next"?1:-1,Be=lr(b)+Ee;Mi(b,ke,r,Be),_n(b);return}if(k==="submit-all"){if(!Pt.current)return;let Le=($e=b.getAttribute("data-tool-call-id"))!=null?$e:"",ke=Pt.current.getMessages().find(Ge=>{var ve;return((ve=Ge.toolCall)==null?void 0:ve.id)===Le});if(!ke)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),M=(Qe=(rt=Ve==null?void 0:Ve.value)==null?void 0:rt.trim())!=null?Qe:"";M&&ho(b,M);let Ee=Ei(b,ke);Pt.current.persistAskUserQuestionProgress(ke,{answers:Ee,currentIndex:lr(b)});let Be=Vr(Ee);tr(b,Be||"(submitted)",{source:"submit-all",structured:Ee});return}if(k==="skip"){if(!Pt.current)return;let Le=(it=b.getAttribute("data-tool-call-id"))!=null?it:"",ke=Pt.current.getMessages().find(ve=>{var Lt;return((Lt=ve.toolCall)==null?void 0:Lt.id)===Le});if(!ke)return;let Ve=go(b),M=lr(b),Ee=fs(b),Be=M>=Ee-1;if(!Ve){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),fo(er,Le),(lt=ke.agentMetadata)!=null&&lt.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(ke),Pt.current.resolveAskUserQuestion(ke,"(dismissed)"));return}ho(b,"");let Ge=b.querySelector('[data-ask-free-text-input="true"]');if(Ge&&(Ge.value=""),Be){let ve=Ei(b,ke),Lt=Vr(ve);tr(b,Lt||"(skipped)",{source:"submit-all",structured:ve});return}Mi(b,ke,r,M+1),_n(b);return}}),er.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let y=c.target;if(!((F=y.matches)!=null&&F.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let k=y.value;if(k.trim()){if(go(b)){ho(b,k.trim()),_n(b),kr(b);return}tr(b,k,{source:"free-text"})}});let Kr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.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),F=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];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",Kr);let jn=null,Rt=null,vn=null,nr=null,Jr=()=>{};function Lr(){nr==null||nr(),nr=null}let Gr=()=>{var _;if(!jn||!Rt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((_=e.ownerDocument.defaultView)!=null?_: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 k=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${k}px`,Rt.style.zIndex="5";let F=b.offsetWidth-k/2;Rt.style.left=`${Math.max(0,F)}px`},Cr=()=>{},Un=()=>{var y,b,k,F,_;if(!xt||!cr(r))return;Li(e,r),Pi(e,r),Cr();let c=(F=(k=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:k.narrowHostMaxWidth)!=null?F:520,f=oe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),xt.update($n),xn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(_=xt.backdrop)==null||_.classList.add("persona-hidden")):$n.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),Jr()};if(cr(r)){oe.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(de),xt=fm(r,{onSelect:y=>{var b;return(b=Pt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{xn=!0,Un()}}),xt.element.classList.add("persona-hidden"),jn=f,f.appendChild(c),f.appendChild(xt.element),xt.backdrop&&oe.appendChild(xt.backdrop),oe.appendChild(f),Jr=()=>{var b,k,F,_;if(!jn||!xt)return;if(!(((F=(k=(b=r.features)==null?void 0:b.artifacts)==null?void 0:k.layout)==null?void 0:F.resizable)===!0)){vn==null||vn(),vn=null,Lr(),Rt&&(Rt.remove(),Rt=null),xt.element.style.removeProperty("width"),xt.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 D=e.ownerDocument,Ae=(_=D.defaultView)!=null?_:window,ue=Z=>{var it,lt;if(!xt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;Z.preventDefault(),Lr();let ye=Z.clientX,Te=xt.element.getBoundingClientRect().width,$e=(lt=(it=r.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,rt=Le=>{let ke=jn.getBoundingClientRect().width,Ve=e.classList.contains("persona-artifact-appearance-seamless"),M=Ve?0:xm(jn,Ae),Ee=Ve?0:q.getBoundingClientRect().width||6,Be=Te-(Le.clientX-ye),Ge=vm(Be,ke,M,Ee,$e==null?void 0:$e.resizableMinWidth,$e==null?void 0:$e.resizableMaxWidth);xt.element.style.width=`${Ge}px`,xt.element.style.maxWidth="none",Gr()},Qe=()=>{D.removeEventListener("pointermove",rt),D.removeEventListener("pointerup",Qe),D.removeEventListener("pointercancel",Qe),nr=null;try{q.releasePointerCapture(Z.pointerId)}catch{}};nr=Qe,D.addEventListener("pointermove",rt),D.addEventListener("pointerup",Qe),D.addEventListener("pointercancel",Qe);try{q.setPointerCapture(Z.pointerId)}catch{}};q.addEventListener("pointerdown",ue),Rt=q,jn.insertBefore(q,xt.element),vn=()=>{q.removeEventListener("pointerdown",ue)}}if(Rt){let q=$n.artifacts.length>0&&!xn;Rt.classList.toggle("persona-hidden",!q),Gr()}},Cr=()=>{var Ae,ue,Z,ye,Te,$e,rt,Qe,it,lt,Le,ke,Ve,M;if(!E||!xt||((ue=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||rn(r)&&ir(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,k=(Te=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Te:!0,F=(rt=($e=r.launcher)==null?void 0:$e.mobileBreakpoint)!=null?rt:640;if(k&&b.innerWidth<=F||!bm(r,E))return;let _=(lt=(it=(Qe=r.launcher)==null?void 0:Qe.width)!=null?it:r.launcherWidth)!=null?lt:Xn,q=(M=(Ve=(ke=(Le=r.features)==null?void 0:Le.artifacts)==null?void 0:ke.layout)==null?void 0:Ve.expandedPanelWidth)!=null?M:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!xn?(oe.style.width=q,oe.style.maxWidth=q):(oe.style.width=_,oe.style.maxWidth=_)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{Un()}),On.observe(oe))}else oe.appendChild(de),$()&&Ye&&(We.peekBanner&&Ye.appendChild(We.peekBanner),Ye.appendChild(Ue));e.appendChild(le),Ye&&e.appendChild(Ye);let dr=()=>{var Ge,ve,Lt,at,Yt,dn,Wt,An,pn,et,ct,Sn,mn,So,To,Eo,Zo,es,Kt,Mo,so,yt,In,Dr,Tn,Wn,Bt,zt;if($()){oe.style.width="100%",oe.style.maxWidth="100%";let Dt=(ve=(Ge=r.launcher)==null?void 0:Ge.composerBar)!=null?ve:{},Jt=le.dataset.state==="expanded",Rn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(Jt&&Rn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let nn=(Yt=(at=r.theme)==null?void 0:at.components)==null?void 0:Yt.panel,Sr=ls(r),Nr=(ko,Da)=>{var Ns;return ko==null||ko===""?Da:(Ns=as(Sr,ko))!=null?Ns:ko},Ra="1px solid var(--persona-border)",Ha="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ba="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=Nr(nn==null?void 0:nn.border,Ra),de.style.borderRadius=Nr(nn==null?void 0:nn.borderRadius,Ba),de.style.boxShadow=Nr(nn==null?void 0:nn.shadow,Ha),de.style.overflow="hidden";return}let c=rn(r),f=(Wt=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?Wt:!1,y=c||f||((pn=(An=r.launcher)==null?void 0:An.fullHeight)!=null?pn:!1),b=((et=r.launcher)==null?void 0:et.enabled)===!1,k=(Sn=(ct=r.theme)==null?void 0:ct.components)==null?void 0:Sn.panel,F=ls(r),_=(Dt,Jt)=>{var Rn;return Dt==null||Dt===""?Jt:(Rn=as(F,Dt))!=null?Rn:Dt},q=(mn=e.ownerDocument.defaultView)!=null?mn:window,D=(To=(So=r.launcher)==null?void 0:So.mobileFullscreen)!=null?To:!0,Ae=(Zo=(Eo=r.launcher)==null?void 0:Eo.mobileBreakpoint)!=null?Zo:640,ue=q.innerWidth<=Ae,Z=D&&ue&&E,ye=(Kt=(es=r.launcher)==null?void 0:es.position)!=null?Kt:"bottom-left",Te=ye==="bottom-left"||ye==="top-left",$e=(so=(Mo=r.launcher)==null?void 0:Mo.zIndex)!=null?so:hn,rt=f||Z?"none":"1px solid var(--persona-border)",Qe=Z?"none":f?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(Qe="none",rt="none");let it=f||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=_(k==null?void 0:k.border,rt),Le=_(k==null?void 0:k.shadow,Qe),ke=_(k==null?void 0:k.borderRadius,it),Ve=G.scrollTop;e.style.cssText="",le.style.cssText="",oe.style.cssText="",de.style.cssText="",G.style.cssText="",Ue.style.cssText="";let M=()=>{var Jt;if(Ve<=0)return;((Jt=G.ownerDocument.defaultView)!=null?Jt:window).requestAnimationFrame(()=>{if(G.scrollTop===Ve)return;let Rn=G.scrollHeight-G.clientHeight;Rn<=0||(G.scrollTop=Math.min(Ve,Rn))})};if(Z){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
+ `,I.addEventListener("click",()=>{u=S,T.forEach(($,D)=>{let R=D<S;$.classList.toggle("selected",R),$.setAttribute("aria-checked",D===S-1?"true":"false")})}),T.push(I),w.appendChild(I)}f.appendChild(w);let B=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),S.appendChild(B),f.appendChild(S)}let k=document.createElement("div");k.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{n==null||n(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let S=(B==null?void 0:B.value.trim())||void 0;await t(u,S),p.remove()}catch(S){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),k.appendChild(P),k.appendChild(W),f.appendChild(k),p.appendChild(f),p}function $i(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:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.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 w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=s,v.appendChild(w),m.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let B=document.createElement("div");B.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=p,B.appendChild(k),B.appendChild(P);let W=document.createElement("div");W.className="persona-feedback-numbers";let S=[];for(let q=0;q<=10;q++){let K=document.createElement("button");K.type="button",K.className="persona-feedback-rating-btn persona-feedback-number-btn",K.setAttribute("role","radio"),K.setAttribute("aria-checked","false"),K.setAttribute("aria-label",`Rating ${q} out of 10`),K.textContent=String(q),K.dataset.rating=String(q),q<=6?K.classList.add("persona-feedback-detractor"):q<=8?K.classList.add("persona-feedback-passive"):K.classList.add("persona-feedback-promoter"),K.addEventListener("click",()=>{f=q,S.forEach((se,Re)=>{se.classList.toggle("selected",Re===q),se.setAttribute("aria-checked",Re===q?"true":"false")})}),S.push(K),W.appendChild(K)}T.appendChild(B),T.appendChild(W),m.appendChild(T);let I=null;if(d){let q=document.createElement("div");q.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),q.appendChild(I),m.appendChild(q)}let $=document.createElement("div");$.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let q=(I==null?void 0:I.value.trim())||void 0;await t(f,q),u.remove()}catch(q){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",q)}}),$.appendChild(D),$.appendChild(R),m.appendChild($),u.appendChild(m),u}var Ss="persona-chat-history",Kh=30*1e3,Jh={"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 Gh(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=Jh[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 _i(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 Xh(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 Qh(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Dl=e=>!e||typeof e!="object"?{}:{...e},Dm=e=>e.map(t=>({...t,streaming:!1})),Nm=(e,t,n)=>{let r=e!=null&&e.markdown?Bo(e.markdown):null,s=as(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,p,u;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p: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:(u=i!=null?i:o.text)!=null?u:""}):r?d=r(a):d=Do(a),s?s(d):d}};function Om(e){var i,d,l,p;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=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=we(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let u=h("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var ji=(e,t,n)=>{var 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,Gc,Xc,Qc,Yc,Zc,ed;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=ri(t),s=fa.getForInstance(r.plugins);r.components&&Kr.registerAll(r.components);let o=Im(),i=r.persistState===!1?null:(ic=r.storageAdapter)!=null?ic:Hi(),d={},l=null,p=!1,u=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&&(p=!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 u(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=u(g);b.metadata&&(d=Dl(b.metadata)),(lc=b.messages)!=null&&lc.length&&(r={...r,initialMessages:b.messages}),(cc=b.artifacts)!=null&&cc.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(dc=b.selectedArtifactId)!=null?dc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=u({messages:[],metadata:{}});(pc=c.messages)!=null&&pc.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:{},Qo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ha],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ko.message,Ko.messageAndClick],w=ba({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let T=(mc=(uc=r.launcher)==null?void 0:uc.enabled)!=null?mc:!0,B=(fc=(gc=r.launcher)==null?void 0:gc.autoExpand)!=null?fc:!1,k=(hc=r.autoFocusInput)!=null?hc:!1,P=B,W=T,S=(yc=(bc=r.layout)==null?void 0:bc.header)==null?void 0:yc.layout,I=!1,$=()=>fo(r),D=()=>T||$(),R=$()?!1:T?B:!0,q=!1,K=null,se=()=>{q=!0,K&&clearTimeout(K),K=setTimeout(()=>{q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),q=!1)},1e4)},Re=Nm(r,w,se),Ge=(vc=(xc=r.features)==null?void 0:xc.showReasoning)!=null?vc:!0,Ce=(Cc=(wc=r.features)==null?void 0:wc.showToolCalls)!=null?Cc:!0,He=(Sc=(Ac=r.features)==null?void 0:Ac.showEventStreamToggle)!=null?Sc:!1,be=(Ec=(Tc=r.features)==null?void 0:Tc.scrollToBottom)!=null?Ec:{},Pe=`${(kc=typeof r.persistState=="object"?(Mc=r.persistState)==null?void 0:Mc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,J=He?new ma(Pe):null,ue=(Ic=(Pc=(Lc=r.features)==null?void 0:Lc.eventStream)==null?void 0:Pc.maxEvents)!=null?Ic:2e3,V=He?new ua(ue,J):null,de=He?new ga:null,le=null,ae=!1,Se=null,ze=0;J==null||J.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Y={onCopy:c=>{var g,b;o.emit("message:copy",c),_!=null&&_.isClientTokenMode()&&_.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),_!=null&&_.isClientTokenMode()&&_.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=(Wc=r.statusIndicator)!=null?Wc:{},ce=c=>{var g,b,y,E;return c==="idle"?(g=ne.idleText)!=null?g:vn.idle:c==="connecting"?(b=ne.connectingText)!=null?b:vn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:vn.connected:c==="error"?(E=ne.errorText)!=null?E:vn.error:vn[c]};function xe(c,g,b,y){if(y==="idle"&&b.idleLink){c.textContent="";let E=document.createElement("a");E.href=b.idleLink,E.target="_blank",E.rel="noopener noreferrer",E.textContent=g,E.style.color="inherit",E.style.textDecoration="none",c.appendChild(E)}else c.textContent=g}let{wrapper:me,panel:oe,pillRoot:Ze}=Ku(r),We=Ju(r,D()),{container:fe,body:X,messagesWrapper:$e,suggestions:Ht,textarea:he,sendButton:pe,sendButtonWrapper:Pn,composerForm:Ut,statusText:gn,introTitle:Bn,introSubtitle:er,closeButton:Ue,iconHolder:F,headerTitle:Ee,headerSubtitle:De,header:Ne,footer:_e,actionsRow:mt,leftActions:at,rightActions:It}=We,Kt=We.setSendButtonMode,z=We.micButton,qt=We.micButtonWrapper,et=We.attachmentButton,_t=We.attachmentButtonWrapper,re=We.attachmentInput,ve=We.attachmentPreviewsContainer;fe.classList.add("persona-relative"),X.classList.add("persona-relative");let Et=12,Jt=()=>{var c;return(c=be.label)!=null?c:""},nn=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},Cn=()=>be.enabled!==!1,Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let kt=h("span","persona-flex persona-items-center"),wt=h("span","");Wt.append(kt,wt),fe.appendChild(Wt);let At=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;Wt.style.bottom=`${g+Et}px`};At();let Gt=()=>{let c=!!Jt();Wt.setAttribute("aria-label",Jt()||"Jump to latest"),Wt.title=Jt(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),kt.innerHTML="";let g=we(nn(),"14px","currentColor",2);g?(kt.appendChild(g),kt.style.display=""):kt.style.display="none",wt.textContent=Jt(),wt.style.display=c?"":"none"};Gt();let ot=null,Dn=null,tr=s.find(c=>c.renderHeader);if(tr!=null&&tr.renderHeader){let c=tr.renderHeader({config:r,defaultRenderer:()=>{let g=qr({config:r,showClose:D()});return Uo(fe,g,r),g.header},onClose:()=>Nt(!1,"user")});if(c){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ne=c)}}let An=()=>{var g,b,y,E;if(!V)return;if(ae=!0,!le&&V&&(le=wm({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>Nn(),config:r,plugins:s,getThroughput:()=>{var N;return(N=de==null?void 0:de.getMetric())!=null?N:{status:"idle"}}})),le&&(X.style.display="none",(g=_e.parentNode)==null||g.insertBefore(le.element,_e),le.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let N=(E=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:E.toggleButtonActive;N&&N.split(/\s+/).forEach(O=>O&&bt.classList.add(O))}let c=()=>{if(!ae)return;let N=Date.now();N-ze>=200&&(le==null||le.update(),ze=N),Se=requestAnimationFrame(c)};ze=0,Se=requestAnimationFrame(c),Nr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,g,b;if(ae){if(ae=!1,le&&le.element.remove(),X.style.display="",bt){bt.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(E=>E&&bt.classList.remove(E))}Se!==null&&(cancelAnimationFrame(Se),Se=null),Nr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(He){let c=(Hc=(Rc=r.features)==null?void 0:Rc.eventStream)==null?void 0:Hc.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:"");bt=h("button",g),bt.style.width="28px",bt.style.height="28px",bt.style.color=Ln.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let b=we("activity","18px","currentColor",1.5);b&&bt.appendChild(b);let y=We.clearChatButtonWrapper,E=We.closeButtonWrapper,N=y||E;N&&N.parentNode===Ne?Ne.insertBefore(bt,N):Ne.appendChild(bt),bt.addEventListener("click",()=>{ae?Nn():An()})}let Er=c=>{var y,E,N;let g=r.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(b,O):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((y=g.allowedTypes)!=null?y:Ur).join(","),O.multiple=((E=g.maxFiles)!=null?E:4)>1,O.style.display="none",O.setAttribute("aria-label",(N=g.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(O)}},On=s.find(c=>c.renderComposer);if(On!=null&&On.renderComposer){let c=r.composer,g=On.renderComposer({config:r,defaultRenderer:()=>fs({config:r}).footer,onSubmit:b=>{var O;if(!_||_.isStreaming())return;let y=b.trim(),E=(O=ot==null?void 0:ot.hasAttachments())!=null?O:!1;if(!y&&!E)return;Hs();let N;E&&(N=[],N.push(...ot.getContentParts()),y&&N.push(Js(y))),_.sendMessage(y,{contentParts:N}),E&&ot.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{re==null||re.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:((Bc=r.voiceRecognition)==null?void 0:Bc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});g&&(_e.replaceWith(g),_e=g)}let Co=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),E=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");g&&(Ut=g),b&&(he=b),y&&(pe=y),E&&(z=E,qt=E.parentElement),N&&(gn=N);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ht=O);let U=c.querySelector(".persona-attachment-button");U&&(et=U,_t=U.parentElement),re=c.querySelector('input[type="file"]'),ve=c.querySelector(".persona-attachment-previews");let H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(mt=H)};Er(_e),Co(_e);let In=($c=(Dc=r.layout)==null?void 0:Dc.contentMaxWidth)!=null?$c:$()?(Fc=(Oc=(Nc=r.launcher)==null?void 0:Nc.composerBar)==null?void 0:Oc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&($e.style.maxWidth=In,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),In&&Ut&&!$()&&(Ut.style.maxWidth=In,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),In&&Ht&&!$()&&(Ht.style.maxWidth=In,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),In&&ve&&!$()&&(ve.style.maxWidth=In,ve.style.marginLeft="auto",ve.style.marginRight="auto"),(_c=r.attachments)!=null&&_c.enabled&&re&&ve){ot=jo.fromConfig(r.attachments),ot.setPreviewsContainer(ve),re.addEventListener("change",b=>{let y=b.target;ot==null||ot.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=Om(c);fe.appendChild(g)}(()=>{var y,E;let c=(E=(y=r.layout)==null?void 0:y.slots)!=null?E:{},g=N=>{switch(N){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return Ht;case"composer":return Ut;case"footer-bottom":return gn;default:return null}},b=(N,O)=>{var U;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Ne.insertBefore(O,Ne.firstChild);else if(N==="header-right")Ne.appendChild(O);else{let H=Ne.querySelector(".persona-flex-col");H?(U=H.parentNode)==null||U.insertBefore(O,H.nextSibling):Ne.appendChild(O)}break;case"body-top":{let H=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(O):X.insertBefore(O,X.firstChild);break}case"body-bottom":X.appendChild(O);break;case"footer-top":Ht.replaceWith(O);break;case"footer-bottom":gn.replaceWith(O);break;default:break}};for(let[N,O]of Object.entries(c))if(O)try{let U=O({config:r,defaultContent:()=>g(N)});U&&b(N,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,U)}})();let Gr=c=>{var O,U;let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let y=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let E=y.getAttribute("data-message-id");if(!E)return;let N=b.getAttribute("data-bubble-type");if(N==="reasoning")bs.has(E)?bs.delete(E):bs.add(E),Yu(E,y);else if(N==="tool")ys.has(E)?ys.delete(E):ys.add(E),Zu(E,y,r);else if(N==="approval"){let H=r.approval!==!1?r.approval:void 0,Te=((O=H==null?void 0:H.detailsDisplay)!=null?O:"collapsed")==="expanded",ge=(U=Li.get(E))!=null?U:Te;Li.set(E,!ge),hm(E,y,r)}ye.delete(E)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Gr(c))}),$e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Gr(c))});let Wr=new Map;$e.addEventListener("click",c=>{var O;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest("[data-actions-for]");if(!y)return;let E=y.getAttribute("data-actions-for");if(!E)return;let N=b.getAttribute("data-action");if(N==="copy"){let H=_.getMessages().find(Te=>Te.id===E);if(H&&Y.onCopy){let Te=H.content||"";navigator.clipboard.writeText(Te).then(()=>{b.classList.add("persona-message-action-success");let ge=we("check",14,"currentColor",2);ge&&(b.innerHTML="",b.appendChild(ge)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ee=we("copy",14,"currentColor",2);ee&&(b.innerHTML="",b.appendChild(ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),Y.onCopy(H)}}else if(N==="upvote"||N==="downvote"){let H=((O=Wr.get(E))!=null?O:null)===N,Te=N==="upvote"?"thumbs-up":"thumbs-down";if(H){Wr.delete(E),b.classList.remove("persona-message-action-active");let ge=we(Te,14,"currentColor",2);ge&&(b.innerHTML="",b.appendChild(ge))}else{let ge=N==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ge}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ve=we(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ve&&(ee.innerHTML="",ee.appendChild(Ve))}Wr.set(E,N),b.classList.add("persona-message-action-active");let Ae=we(Te,14,"currentColor",2);Ae&&(Ae.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Ae)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let je=_.getMessages().find(st=>st.id===E);je&&Y.onFeedback&&Y.onFeedback({type:N,messageId:je.id,message:je})}}}),$e.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest(".persona-approval-bubble");if(!y)return;let E=y.getAttribute("data-message-id");if(!E)return;let N=b.getAttribute("data-approval-action");if(!N)return;let O=N==="approve"?"approved":"denied",H=_.getMessages().find(ge=>ge.id===E);if(!(H!=null&&H.approval))return;let Te=y.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?_.resolveWebMcpApproval(E,O):_.resolveApproval(H.approval,O)});let St=null,Fn=null,$n={artifacts:[],selectedId:null},Sn=!1,Lt={current:null};$e.addEventListener("click",c=>{var ee,Ae,Me,je,st;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((Me=(Ae=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:Ae.onArtifactAction)==null?void 0:Me.call(Ae,{type:"download",artifactId:y}))===!0)return;let N=_.getArtifactById(y),O=N==null?void 0:N.markdown,U=(N==null?void 0:N.title)||"artifact";if(!O){let Ve=b.closest("[data-open-artifact]"),gt=Ve==null?void 0:Ve.closest("[data-message-id]"),pt=gt==null?void 0:gt.getAttribute("data-message-id");if(pt){let Le=_.getMessages().find(qe=>qe.id===pt);if(Le!=null&&Le.rawContent)try{let qe=JSON.parse(Le.rawContent);O=(je=qe==null?void 0:qe.props)==null?void 0:je.markdown,U=((st=qe==null?void 0:qe.props)==null?void 0:st.title)||U}catch{}}}if(!O)return;let H=new Blob([O],{type:"text/markdown"}),Te=URL.createObjectURL(H),ge=document.createElement("a");ge.href=Te,ge.download=`${U}.md`,ge.click(),URL.revokeObjectURL(Te)}),$e.addEventListener("click",c=>{var N,O,U;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((U=(O=(N=r.features)==null?void 0:N.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:U.call(O,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Sn=!1,_.selectArtifact(y),Un())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let nr=We.composerOverlay,rr=(c,g,b)=>{var U,H,Te,ge;let y=g.trim();if(!y||!Lt.current)return;let E=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",N=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:E,answer:y,answers:b.structured,values:(H=b.values)!=null?H:b.source==="multi"?y.split(", "):[y],isFreeText:N,source:b.source},bubbles:!0,composed:!0})),xo(nr,E);let O=Lt.current.getMessages().find(ee=>{var Ae;return((Ae=ee.toolCall)==null?void 0:Ae.id)===E});(Te=O==null?void 0:O.agentMetadata)!=null&&Te.awaitingLocalTool?Lt.current.resolveAskUserQuestion(O,(ge=b.structured)!=null?ge:y):Lt.current.sendMessage(y)},_n=c=>{var E;let g=Lt.current;if(!g)return;let b=(E=c.getAttribute("data-tool-call-id"))!=null?E:"",y=g.getMessages().find(N=>{var O;return((O=N.toolCall)==null?void 0:O.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:Mi(c,y),currentIndex:gr(c)})},Xr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Rr=c=>{var E,N,O;if(((N=(E=r.features)==null?void 0:E.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=gr(c),b=vs(c);if(g>=b-1)return;let y=(O=Lt.current)==null?void 0:O.getMessages().find(U=>{var H;return((H=U.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});y&&(ki(c,y,r,g+1),_n(c))};nr.addEventListener("click",c=>{var N,O,U,H,Te,ge,ee,Ae,Me,je,st,Ve,gt,pt;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 E=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),E==="dismiss"){let Ie=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),xo(nr,Ie);let Le=(O=Lt.current)==null?void 0:O.getMessages().find(qe=>{var Ye;return((Ye=qe.toolCall)==null?void 0:Ye.id)===Ie});(U=Le==null?void 0:Le.agentMetadata)!=null&&U.awaitingLocalTool&&((H=Lt.current)==null||H.markAskUserQuestionResolved(Le),(Te=Lt.current)==null||Te.resolveAskUserQuestion(Le,"(dismissed)"));return}if(E==="pick"){let Ie=b.getAttribute("data-option-label");if(!Ie)return;let Le=y.getAttribute("data-multi-select")==="true",qe=yo(y);if(qe&&Le){let Ye=zo(y)[gr(y)],vt=new Set(Array.isArray(Ye)?Ye:[]);vt.has(Ie)?vt.delete(Ie):vt.add(Ie),vo(y,Array.from(vt)),_n(y);return}if(qe){vo(y,Ie),_n(y),Rr(y);return}if(Le){let Ye=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",Ye?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!Ye);let vt=y.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=Ll(y).length===0);return}rr(y,Ie,{source:"pick",values:[Ie]});return}if(E==="submit-multi"){let Ie=Ll(y);if(Ie.length===0)return;rr(y,Ie.join(", "),{source:"multi",values:Ie});return}if(E==="open-free-text"){let Ie=y.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(E==="focus-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(E==="submit-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]'),Le=(ge=Ie==null?void 0:Ie.value)!=null?ge:"";if(!Le.trim())return;if(yo(y)){vo(y,Le.trim()),_n(y),Rr(y);return}rr(y,Le,{source:"free-text"});return}if(E==="next"||E==="back"){if(!Lt.current)return;let Ie=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Le=Lt.current.getMessages().find(Oe=>{var te;return((te=Oe.toolCall)==null?void 0:te.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(Me=(Ae=qe==null?void 0:qe.value)==null?void 0:Ae.trim())!=null?Me:"";if(Ye){let Oe=zo(y)[gr(y)];(typeof Oe!="string"||Oe!==Ye)&&vo(y,Ye)}let vt=E==="next"?1:-1,L=gr(y)+vt;ki(y,Le,r,L),_n(y);return}if(E==="submit-all"){if(!Lt.current)return;let Ie=(je=y.getAttribute("data-tool-call-id"))!=null?je:"",Le=Lt.current.getMessages().find(Oe=>{var te;return((te=Oe.toolCall)==null?void 0:te.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(Ve=(st=qe==null?void 0:qe.value)==null?void 0:st.trim())!=null?Ve:"";Ye&&vo(y,Ye);let vt=Mi(y,Le);Lt.current.persistAskUserQuestionProgress(Le,{answers:vt,currentIndex:gr(y)});let L=Xr(vt);rr(y,L||"(submitted)",{source:"submit-all",structured:vt});return}if(E==="skip"){if(!Lt.current)return;let Ie=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",Le=Lt.current.getMessages().find(te=>{var nt;return((nt=te.toolCall)==null?void 0:nt.id)===Ie});if(!Le)return;let qe=yo(y),Ye=gr(y),vt=vs(y),L=Ye>=vt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),xo(nr,Ie),(pt=Le.agentMetadata)!=null&&pt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Le),Lt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}vo(y,"");let Oe=y.querySelector('[data-ask-free-text-input="true"]');if(Oe&&(Oe.value=""),L){let te=Mi(y,Le),nt=Xr(te);rr(y,nt||"(skipped)",{source:"submit-all",structured:te});return}ki(y,Le,r,Ye+1),_n(y);return}}),nr.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let b=c.target;if(!((N=b.matches)!=null&&N.call(b,'[data-ask-free-text-input="true"]')))return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let E=b.value;if(E.trim()){if(yo(y)){vo(y,E.trim()),_n(y),Rr(y);return}rr(y,E,{source:"free-text"})}});let Qr=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=nr.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),N=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",Qr);let jn=null,Dt=null,Tn=null,or=null,Yr=()=>{};function Hr(){or==null||or(),or=null}let Zr=()=>{var O;if(!jn||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){Dt.style.removeProperty("position"),Dt.style.removeProperty("left"),Dt.style.removeProperty("top"),Dt.style.removeProperty("bottom"),Dt.style.removeProperty("width"),Dt.style.removeProperty("z-index");return}let y=jn.firstElementChild;if(!y||y===Dt)return;let E=10;Dt.style.position="absolute",Dt.style.top="0",Dt.style.bottom="0",Dt.style.width=`${E}px`,Dt.style.zIndex="5";let N=y.offsetWidth-E/2;Dt.style.left=`${Math.max(0,N)}px`},Mr=()=>{},Un=()=>{var b,y,E,N,O;if(!St||!fr(r))return;Wi(e,r),Ri(e,r),Mr();let c=(N=(E=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:E.narrowHostMaxWidth)!=null?N:520,g=oe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),St.update($n),Sn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(O=St.backdrop)==null||O.classList.add("persona-hidden")):$n.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),Yr()};if(fr(r)){oe.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(fe),St=Sm(r,{onSelect:b=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{Sn=!0,Un()}}),St.element.classList.add("persona-hidden"),jn=g,g.appendChild(c),g.appendChild(St.element),St.backdrop&&oe.appendChild(St.backdrop),oe.appendChild(g),Yr=()=>{var y,E,N,O;if(!jn||!St)return;if(!(((N=(E=(y=r.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:N.resizable)===!0)){Tn==null||Tn(),Tn=null,Hr(),Dt&&(Dt.remove(),Dt=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Dt){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let H=e.ownerDocument,Te=(O=H.defaultView)!=null?O:window,ge=ee=>{var gt,pt;if(!St||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;ee.preventDefault(),Hr();let Ae=ee.clientX,Me=St.element.getBoundingClientRect().width,je=(pt=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:pt.layout,st=Ie=>{let Le=jn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Ye=qe?0:km(jn,Te),vt=qe?0:U.getBoundingClientRect().width||6,L=Me-(Ie.clientX-Ae),Oe=Lm(L,Le,Ye,vt,je==null?void 0:je.resizableMinWidth,je==null?void 0:je.resizableMaxWidth);St.element.style.width=`${Oe}px`,St.element.style.maxWidth="none",Zr()},Ve=()=>{H.removeEventListener("pointermove",st),H.removeEventListener("pointerup",Ve),H.removeEventListener("pointercancel",Ve),or=null;try{U.releasePointerCapture(ee.pointerId)}catch{}};or=Ve,H.addEventListener("pointermove",st),H.addEventListener("pointerup",Ve),H.addEventListener("pointercancel",Ve);try{U.setPointerCapture(ee.pointerId)}catch{}};U.addEventListener("pointerdown",ge),Dt=U,jn.insertBefore(U,St.element),Tn=()=>{U.removeEventListener("pointerdown",ge)}}if(Dt){let U=$n.artifacts.length>0&&!Sn;Dt.classList.toggle("persona-hidden",!U),Zr()}},Mr=()=>{var Te,ge,ee,Ae,Me,je,st,Ve,gt,pt,Ie,Le,qe,Ye;if(!T||!St||((ge=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?ge:!1)||ln(r)&&mr(r).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,E=(Me=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Me:!0,N=(st=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?st:640;if(E&&y.innerWidth<=N||!Mm(r,T))return;let O=(pt=(gt=(Ve=r.launcher)==null?void 0:Ve.width)!=null?gt:r.launcherWidth)!=null?pt:Yn,U=(Ye=(qe=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ye:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!Sn?(oe.style.width=U,oe.style.maxWidth=U):(oe.style.width=O,oe.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Un()}),Fn.observe(oe))}else oe.appendChild(fe),$()&&Ze&&(We.peekBanner&&Ze.appendChild(We.peekBanner),Ze.appendChild(_e));e.appendChild(me),Ze&&e.appendChild(Ze);let hr=()=>{var Oe,te,nt,Ft,Ot,zt,it,dn,Jn,Ke,Ct,Gn,sn,pr,Xn,ko,os,ss,Xt,Lo,lo,co,$r,Po,rt,yn,fn,pn;if($()){oe.style.width="100%",oe.style.maxWidth="100%";let ft=(te=(Oe=r.launcher)==null?void 0:Oe.composerBar)!=null?te:{},lt=me.dataset.state==="expanded",Mt=(nt=ft.expandedSize)!=null?nt:"anchored";if(!(lt&&Mt!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let tn=(Ot=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Ot.panel,Lr=ms(r),an=(Wo,Da)=>{var js;return Wo==null||Wo===""?Da:(js=ps(Lr,Wo))!=null?js:Wo},Mn="1px solid var(--persona-border)",ur="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=an(tn==null?void 0:tn.border,Mn),fe.style.borderRadius=an(tn==null?void 0:tn.borderRadius,Io),fe.style.boxShadow=an(tn==null?void 0:tn.shadow,ur),fe.style.overflow="hidden";return}let c=ln(r),g=(it=(zt=r.launcher)==null?void 0:zt.sidebarMode)!=null?it:!1,b=c||g||((Jn=(dn=r.launcher)==null?void 0:dn.fullHeight)!=null?Jn:!1),y=((Ke=r.launcher)==null?void 0:Ke.enabled)===!1,E=(Gn=(Ct=r.theme)==null?void 0:Ct.components)==null?void 0:Gn.panel,N=ms(r),O=(ft,lt)=>{var Mt;return ft==null||ft===""?lt:(Mt=ps(N,ft))!=null?Mt:ft},U=(sn=e.ownerDocument.defaultView)!=null?sn:window,H=(Xn=(pr=r.launcher)==null?void 0:pr.mobileFullscreen)!=null?Xn:!0,Te=(os=(ko=r.launcher)==null?void 0:ko.mobileBreakpoint)!=null?os:640,ge=U.innerWidth<=Te,ee=H&&ge&&T,Ae=(Xt=(ss=r.launcher)==null?void 0:ss.position)!=null?Xt:"bottom-left",Me=Ae==="bottom-left"||Ae==="top-left",je=(lo=(Lo=r.launcher)==null?void 0:Lo.zIndex)!=null?lo:wn,st=g||ee?"none":"1px solid var(--persona-border)",Ve=ee?"none":g?Me?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ve="none",st="none");let gt=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=O(E==null?void 0:E.border,st),Ie=O(E==null?void 0:E.shadow,Ve),Le=O(E==null?void 0:E.borderRadius,gt),qe=X.scrollTop;e.style.cssText="",me.style.cssText="",oe.style.cssText="",fe.style.cssText="",X.style.cssText="",_e.style.cssText="";let Ye=()=>{var lt;if(qe<=0)return;((lt=X.ownerDocument.defaultView)!=null?lt:window).requestAnimationFrame(()=>{if(X.scrollTop===qe)return;let Mt=X.scrollHeight-X.clientHeight;Mt<=0||(X.scrollTop=Math.min(qe,Mt))})};if(ee){me.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"),me.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -37,7 +37,7 @@ _Details: ${n.message}_`:r}var Ks=e=>({isError:!0,content:[{type:"text",text:e}]
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${$e} !important;
40
+ z-index: ${je} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
42
  `,oe.style.cssText=`
43
43
  position: relative !important;
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:r}var Ks=e=>({isError:!0,content:[{type:"text",text:e}]
52
52
  padding: 0 !important;
53
53
  box-shadow: none !important;
54
54
  border-radius: 0 !important;
55
- `,de.style.cssText=`
55
+ `,fe.style.cssText=`
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
58
  flex: 1 1 0% !important;
@@ -63,19 +63,19 @@ _Details: ${n.message}_`:r}var Ks=e=>({isError:!0,content:[{type:"text",text:e}]
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Ue.style.flexShrink="0",W=!0,M();return}let Ee=(In=(yt=r==null?void 0:r.launcher)==null?void 0:yt.width)!=null?In:r==null?void 0:r.launcherWidth,Be=Ee!=null?Ee:Xn;if(!f&&!c)b&&y?(oe.style.width="100%",oe.style.maxWidth="100%"):(oe.style.width=Be,oe.style.maxWidth=Be);else if(c)if(ir(r).reveal==="emerge"){let Jt=ir(r).width;oe.style.width=Jt,oe.style.maxWidth=Jt}else oe.style.width="100%",oe.style.maxWidth="100%";if(Cr(),oe.style.boxShadow=Le,oe.style.borderRadius=ke,de.style.border=lt,de.style.borderRadius=ke,c&&!Z&&(k==null?void 0:k.border)===void 0&&(de.style.border="none",ir(r).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),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"),oe.style.display="flex",oe.style.flexDirection="column",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.maxHeight="100%",oe.style.height="100%",oe.style.overflow="hidden",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Ue.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"),!f&&!b&&!c&&((Dr=xr[ye])!=null?Dr:xr["bottom-right"]).split(" ").forEach(Jt=>le.classList.add(Jt)),f){let Dt=(Wn=(Tn=r.launcher)==null?void 0:Tn.sidebarWidth)!=null?Wn:"420px";le.style.cssText=`
66
+ `,X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0",I=!0,Ye();return}let vt=($r=(co=r==null?void 0:r.launcher)==null?void 0:co.width)!=null?$r:r==null?void 0:r.launcherWidth,L=vt!=null?vt:Yn;if(!g&&!c)y&&b?(oe.style.width="100%",oe.style.maxWidth="100%"):(oe.style.width=L,oe.style.maxWidth=L);else if(c)if(mr(r).reveal==="emerge"){let lt=mr(r).width;oe.style.width=lt,oe.style.maxWidth=lt}else oe.style.width="100%",oe.style.maxWidth="100%";if(Mr(),oe.style.boxShadow=Ie,oe.style.borderRadius=Le,fe.style.border=pt,fe.style.borderRadius=Le,c&&!ee&&(E==null?void 0:E.border)===void 0&&(fe.style.border="none",mr(r).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.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%"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",y&&(me.style.overflow="hidden"),oe.style.display="flex",oe.style.flexDirection="column",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.maxHeight="100%",oe.style.height="100%",oe.style.overflow="hidden",fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.overflow="hidden",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0"),me.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&&((Po=Tr[Ae])!=null?Po:Tr["bottom-right"]).split(" ").forEach(lt=>me.classList.add(lt)),g){let ft=(yn=(rt=r.launcher)==null?void 0:rt.sidebarWidth)!=null?yn:"420px";me.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${Dt} !important;
70
+ width: ${ft} !important;
71
71
  height: 100vh !important;
72
72
  max-height: 100vh !important;
73
73
  margin: 0 !important;
74
74
  padding: 0 !important;
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
- z-index: ${$e} !important;
78
- ${Te?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
77
+ z-index: ${je} !important;
78
+ ${Me?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
79
  `,oe.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
@@ -87,9 +87,9 @@ _Details: ${n.message}_`:r}var Ks=e=>({isError:!0,content:[{type:"text",text:e}]
87
87
  min-height: 0 !important;
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
- box-shadow: ${Le} !important;
91
- border-radius: ${ke} !important;
92
- `,oe.style.setProperty("width","100%","important"),oe.style.setProperty("max-width","100%","important"),de.style.cssText=`
90
+ box-shadow: ${Ie} !important;
91
+ border-radius: ${Le} !important;
92
+ `,oe.style.setProperty("width","100%","important"),oe.style.setProperty("max-width","100%","important"),fe.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
95
  flex: 1 1 0% !important;
@@ -98,29 +98,29 @@ _Details: ${n.message}_`:r}var Ks=e=>({isError:!0,content:[{type:"text",text:e}]
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${ke} !important;
102
- border: ${lt} !important;
103
- `,Ue.style.cssText=`
101
+ border-radius: ${Le} !important;
102
+ border: ${pt} !important;
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;",Jt=f?"":"padding-top: 1.25em !important;",Rn=f?"":`z-index: ${(zt=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?zt:hn} !important;`;le.style.cssText+=Dt+Jt+Rn}M()};dr(),io(e,r),Li(e,r),Pi(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",Kr)});let Gt=null,Xt=null;ft.push(()=>{Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null}),On&&ft.push(()=>{On==null||On.disconnect(),On=null}),ft.push(()=>{vn==null||vn(),vn=null,Lr(),Rt&&(Rt.remove(),Rt=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),fe&&ft.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),Ce==null||Ce.destroy(),Ce=null,K==null||K.destroy(),K=null,te=null});let qn=null,Xr=()=>{qn&&(qn(),qn=null),r.colorScheme==="auto"&&(qn=si(()=>{io(e,r)}))};Xr(),ft.push(()=>{qn&&(qn(),qn=null)});let rr=(Fc=r.features)==null?void 0:Fc.streamAnimation;if(rr!=null&&rr.type&&rr.type!=="none"){let c=ea(rr.type,rr.plugins);c&&(il(c,e),ft.push(()=>Ou(e)))}let pr=lm(Mt),zn=null,T,Vn=!1,ur=Pu(),Pr=new Map,wr=new Map,vs=0,mr=li(),gr=0,fr=null,Ir=!1,xo=!1,ha=4,Cs=24,ya=80,Vo=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ws=($c=(Oc=r.voiceRecognition)==null?void 0:Oc.autoResume)!=null?$c:!1,or=c=>{o.emit("voice:state",{active:gt.active,source:c,timestamp:Date.now()})},Pn=()=>{u(c=>({...c,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},ba=()=>{var b,k;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Rl(d.voiceState),f=!!c.active,y=Number((k=c.timestamp)!=null?k:0);gt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-y<Nh&&setTimeout(()=>{var F,_;gt.active||(gt.manuallyDeactivated=!1,((_=(F=r.voiceRecognition)==null?void 0:F.provider)==null?void 0:_.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("restore"),T.isVoiceActive()&&U()}):Ao("restore"))},1e3)},xa=()=>T?Mm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Ko(c){if(!(i!=null&&i.save))return;let y={messages:c?Mm(c):T?xa():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Wr=null,va=()=>le.querySelector("#persona-scroll-container")||G,vo=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),Ir=!1},As=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),xo=!1,vo()},Rr=()=>{if(!yn()||he){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==de&&de.appendChild(Tt),bt();let c=Xs(G)>0;Tt.style.display=mr.isFollowing()||!c?"none":""},Ss=()=>{mr.pause()&&(As(),Rr())},Qr=()=>{mr.resume(),Rr()},Yr=(c=!1)=>{mr.isFollowing()&&(!c&&!Vn||(fr!==null&&(cancelAnimationFrame(fr),fr=null),xo=!0,fr=requestAnimationFrame(()=>{fr=null,xo=!1,mr.isFollowing()&&Ca(va(),c?220:140)})))},Ca=(c,f=500)=>{let y=c.scrollTop,b=Xs(c),k=b-y;if(Math.abs(k)<1){gr=c.scrollTop;return}if(Math.abs(k)>=ya){vo(),Ir=!0,c.scrollTop=b,gr=c.scrollTop,Ir=!1;return}vo();let F=performance.now();Ir=!0;let _=D=>1-Math.pow(1-D,3),q=D=>{if(!mr.isFollowing()){vo();return}let Ae=Xs(c);Ae!==b&&(b=Ae,k=b-y);let ue=D-F,Z=Math.min(ue/f,1),ye=_(Z),Te=y+k*ye;c.scrollTop=Te,gr=c.scrollTop,Z<1?Wr=requestAnimationFrame(q):(c.scrollTop=b,gr=c.scrollTop,Wr=null,Ir=!1)};Wr=requestAnimationFrame(q)},wa=c=>{let f=new Map;c.forEach(y=>{let b=Vo.get(y.id);f.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}))}),Vo.clear(),f.forEach((y,b)=>{Vo.set(b,y)})},Co=(c,f,y)=>{var Qe,it,lt,Le,ke,Ve;let b=document.createElement("div"),F=(()=>{var Ee;let M=s.find(Be=>Be.renderLoadingIndicator);if(M!=null&&M.renderLoadingIndicator)return M.renderLoadingIndicator;if((Ee=r.loadingIndicator)!=null&&Ee.render)return r.loadingIndicator.render})(),_=(M,Ee)=>Ee==null?!1:typeof Ee=="string"?(M.textContent=Ee,!0):(M.appendChild(Ee),!0),q=new Set,D=new Set,Ae=s.some(M=>M.renderAskUserQuestion),ue=[],Z=[],ye=r.enableComponentStreaming!==!1;if(f.forEach(M=>{var An,pn,et,ct,Sn,mn,So,To,Eo,Zo,es,Kt,Mo,so;q.add(M.id);let Ee=Ae&&_r(M),Be=!Ee&&M.role==="assistant"&&!M.variant&&ye&&Hi(M);if(!Be&&wr.has(M.id)){let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),wr.delete(M.id)}let Ge=_r(M)?`:${(An=M.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(pn=M.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",ve=Lu(M,vs)+Ge,Lt=Ee||Be?null:Iu(ur,M.id,ve);if(Lt){b.appendChild(Lt.cloneNode(!0)),_r(M)&&((et=M.toolCall)!=null&&et.id)&&((ct=M.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((Sn=M.agentMetadata)!=null&&Sn.askUserQuestionAnswered)&&(D.add(M.toolCall.id),hs(M,r,We.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)),dn=(mn=r.layout)==null?void 0:mn.messages;if(_r(M)&&((So=M.agentMetadata)==null?void 0:So.askUserQuestionAnswered)===!0){Pr.delete(M.id);let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if(_r(M)&&((Eo=(To=r.features)==null?void 0:To.askUserQuestion)==null?void 0:Eo.enabled)!==!1){let yt=s.find(In=>typeof In.renderAskUserQuestion=="function");if(yt&&Pt.current){let In=Pr.get(M.id),Dr=In!==ve,Tn=null;if(Dr){let{payload:zt,complete:Dt}=jr(M),Jt=M.id,Rn=()=>{var Jn;return(Jn=Pt.current)==null?void 0:Jn.getMessages().find(nn=>nn.id===Jt)};Tn=yt.renderAskUserQuestion({message:M,payload:zt,complete:Dt,resolve:Jn=>{var Sr;let nn=Rn();nn&&((Sr=Pt.current)==null||Sr.resolveAskUserQuestion(nn,Jn))},dismiss:()=>{var nn,Sr,Nr;let Jn=Rn();(nn=Jn==null?void 0:Jn.agentMetadata)!=null&&nn.awaitingLocalTool&&((Sr=Pt.current)==null||Sr.markAskUserQuestionResolved(Jn),(Nr=Pt.current)==null||Nr.resolveAskUserQuestion(Jn,"(dismissed)"))},config:r})}let Wn=In!=null;if(Dr&&Tn===null&&!Wn){((Zo=M.agentMetadata)==null?void 0:Zo.awaitingLocalTool)===!0&&!((es=M.agentMetadata)!=null&&es.askUserQuestionAnswered)&&(D.add(M.toolCall.id),hs(M,r,We.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),ue.push({messageId:M.id,fingerprint:ve,bubble:Tn});return}else{((Kt=M.agentMetadata)==null?void 0:Kt.awaitingLocalTool)===!0&&!((Mo=M.agentMetadata)!=null&&Mo.askUserQuestionAnswered)&&(D.add(M.toolCall.id),hs(M,r,We.composerOverlay));return}}else if(Yt)if(M.variant==="reasoning"&&M.reasoning&&Yt.renderReasoning){if(!qe)return;at=Yt.renderReasoning({message:M,defaultRenderer:()=>yl(M,r),config:r})}else if(M.variant==="tool"&&M.toolCall&&Yt.renderToolCall){if(!Oe)return;at=Yt.renderToolCall({message:M,defaultRenderer:()=>bl(M,r),config:r})}else if(M.variant==="approval"&&M.approval&&Yt.renderApproval){if(r.approval===!1)return;at=Yt.renderApproval({message:M,defaultRenderer:()=>El(M,r),config:r})}else Yt.renderMessage&&(at=Yt.renderMessage({message:M,defaultRenderer:()=>{let yt=ps(M,y,dn,r.messageActions,Q,{loadingIndicatorRenderer:F,widgetConfig:r});return M.role!=="user"&&Pl(yt,M,r,T),yt},config:r}));if(!at&&Be){let yt=Bi(M);if(yt){let In=wr.get(M.id),Dr=In!==ve,Tn=r.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Dr){let Bt=Ri(yt,{config:r,message:M,transform:y});if(Bt)if(Tn){let zt=document.createElement("div");if(zt.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(" "),zt.id=`bubble-${M.id}`,zt.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}),zt.appendChild(Dt)}zt.appendChild(Bt),Wn=zt}else{let zt=document.createElement("div");if(zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",zt.id=`bubble-${M.id}`,zt.setAttribute("data-message-id",M.id),zt.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}),zt.appendChild(Dt)}zt.appendChild(Bt),Wn=zt}}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"),b.appendChild(Bt),Z.push({messageId:M.id,fingerprint:ve,bubble:Wn});return}}}if(!at)if(M.variant==="reasoning"&&M.reasoning){if(!qe)return;at=yl(M,r)}else if(M.variant==="tool"&&M.toolCall){if(!Oe)return;at=bl(M,r)}else if(M.variant==="approval"&&M.approval){if(r.approval===!1)return;at=El(M,r)}else{let yt=(so=r.layout)==null?void 0:so.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=ps(M,y,yt,r.messageActions,Q,{loadingIndicatorRenderer:F,widgetConfig:r}),M.role!=="user"&&at&&Pl(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),Wu(ur,M.id,ve,Wt),b.appendChild(Wt)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let Be=Ee.getAttribute("data-persona-ask-sheet-for");Be&&!D.has(Be)&&fo(We.composerOverlay,Be)}),(it=(Qe=r.features)==null?void 0:Qe.toolCallDisplay)!=null&&it.grouped){let M=[],Ee=[];f.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&Oe){Ee.push(Be);return}Ee.length>1&&M.push(Ee),Ee=[]}),Ee.length>1&&M.push(Ee),M.forEach((Be,Ge)=>{var pn,et;let ve=Be.map(ct=>Array.from(b.children).find(Sn=>Sn instanceof HTMLElement&&Sn.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(ve.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Ge}-${Be[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Ge}-${Be[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 dn=`Called ${Be.length} tools`,Wt=(et=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:et.call(pn,{messages:Be,toolCalls:Be.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:r});_(Yt,Wt)||(Yt.textContent=dn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Yt,An),Lt.appendChild(at),ve[0].before(Lt),ve.forEach((ct,Sn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Sn<ve.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(ct),An.appendChild(mn)})})}Ru(ur,q);let Te=f.some(M=>M.role==="assistant"&&M.streaming),$e=f[f.length-1],rt=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Vn&&f.some(M=>M.role==="user")&&!Te&&!rt){let M={config:r,streaming:!0,location:"standalone",defaultRenderer:$o},Ee=s.find(Ge=>Ge.renderLoadingIndicator),Be=null;if(Ee!=null&&Ee.renderLoadingIndicator&&(Be=Ee.renderLoadingIndicator(M)),Be===null&&((lt=r.loadingIndicator)!=null&&lt.render)&&(Be=r.loadingIndicator.render(M)),Be===null&&(Be=$o()),Be){let Ge=document.createElement("div"),ve=((Le=r.loadingIndicator)==null?void 0:Le.showBubble)!==!1;Ge.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(" "),Ge.setAttribute("data-typing-indicator","true"),Ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ge.appendChild(Be);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Ge),b.appendChild(Lt)}}if(!Vn&&f.length>0){let M=f[f.length-1],Ee={config:r,lastMessage:M,messageCount:f.length},Be=s.find(ve=>ve.renderIdleIndicator),Ge=null;if(Be!=null&&Be.renderIdleIndicator&&(Ge=Be.renderIdleIndicator(Ee)),Ge===null&&((ke=r.loadingIndicator)!=null&&ke.renderIdle)&&(Ge=r.loadingIndicator.renderIdle(Ee)),Ge){let ve=document.createElement("div"),Lt=((Ve=r.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;ve.className=Lt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ve.setAttribute("data-idle-indicator","true"),ve.appendChild(Ge);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(ai(c,b),ue.length>0)for(let{messageId:M,fingerprint:Ee,bubble:Be}of ue){let Ge=c.querySelector(`#wrapper-${M}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.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(Z.length>0)for(let{messageId:M,fingerprint:Ee,bubble:Be}of Z){let Ge=c.querySelector(`#wrapper-${M}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.setAttribute("data-bubble-fp",Ee),wr.set(M,Ee))}if(wr.size>0)for(let M of wr.keys())q.has(M)||wr.delete(M)},Zr=null,Aa=()=>{var y;if(Zr)return;let c=b=>{let k=b.composedPath();k.includes(le)||Ye&&k.includes(Ye)||Ht(!1,"user")};Zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},Ts=()=>{var f;if(!Zr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Zr,!0),Zr=null};ft.push(()=>Ts());let eo=null,Sa=()=>{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 f;if(!eo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",eo,!0),eo=null};ft.push(()=>Es());let to=!1,Ms=new Set,Ta=()=>{var f,y,b,k;let c=(b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((k=r.features)==null?void 0:k.streamAnimation)},Hr=()=>{var it,lt,Le,ke;if(!$())return;let c=We.peekBanner,f=We.peekTextNode;if(!c||!f)return;if(H){c.classList.remove("persona-pill-peek--visible");return}let y=(it=T==null?void 0:T.getMessages())!=null?it:[],b;for(let Ve=y.length-1;Ve>=0;Ve--){let M=y[Ve];if(M.role==="assistant"&&M.content){b=M;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let k=b.content,F=!!b.streaming,_=Ta(),q=pi(_),D=q.type!=="none"?ea(q.type,_==null?void 0:_.plugins):null,Ae=((lt=D==null?void 0:D.isAnimating)==null?void 0:lt.call(D,b))===!0,ue=D!==null&&(F||Ae);ue&&D&&!Ms.has(D.name)&&(il(D,e),Ms.add(D.name));let Z=ue&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Le=f.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==Z&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),Z&&ye!==Z&&(f.classList.add(Z),f.dataset.personaPeekStreamClass=Z),ue?(f.style.setProperty("--persona-stream-step",`${q.speed}ms`),f.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Te=ue?ui(k,q.buffer,D,b,F):k;if(ue&&q.placeholder==="skeleton"&&F&&(!Te||!Te.trim())){let Ve=document.createElement("div"),M=na();M.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(M),ai(f,Ve)}else{let Ve=Math.max(0,Te.length-100),M=Te.length>100?Te.slice(-100):Te,Ee=Wo(M);if(!ue||!D){let Be=Te.length>100?`\u2026${M}`:M;f.textContent!==Be&&(f.textContent=Be)}else{let Be=Ee;(D.wrap==="char"||D.wrap==="word")&&(Be=ta(Ee,D.wrap,`peek-${b.id}`,{skipTags:D.skipTags,startIndex:Ve}));let Ge=document.createElement("div");if(Ge.innerHTML=Be,D.useCaret&&M.length>0){let ve=mi(),Lt=Ge.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=Lt[Lt.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(ve,at.nextSibling):Ge.appendChild(ve)}ai(f,Ge),(ke=D.onAfterRender)==null||ke.call(D,{container:f,bubble:c,messageId:b.id,message:b,speed:q.speed,duration:q.duration})}}let Qe=Vn||to;c.classList.toggle("persona-pill-peek--visible",Qe)};if($()){let c=We.peekBanner;if(c){let b=k=>{k.preventDefault(),k.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let f=()=>{to||(to=!0,Hr())},y=()=>{to&&(to=!1,Hr())};oe.addEventListener("pointerenter",f),oe.addEventListener("pointerleave",y),ft.push(()=>{oe.removeEventListener("pointerenter",f),oe.removeEventListener("pointerleave",y)}),Ye&&(Ye.addEventListener("pointerenter",f),Ye.addEventListener("pointerleave",y),ft.push(()=>{Ye.removeEventListener("pointerenter",f),Ye.removeEventListener("pointerleave",y)}))}let Ea=c=>{var ye,Te,$e,rt,Qe,it,lt,Le;let f=(Te=(ye=r.launcher)==null?void 0:ye.composerBar)!=null?Te:{},y=($e=f.expandedSize)!=null?$e:"anchored",b=(rt=f.bottomOffset)!=null?rt:"16px",k=f.collapsedMaxWidth,F=(Qe=f.expandedMaxWidth)!=null?Qe:"880px",_=(it=f.expandedTopOffset)!=null?it:"5vh",q=(lt=f.modalMaxWidth)!=null?lt:"880px",D=(Le=f.modalMaxHeight)!=null?Le:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",Z=le.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Ye){let ke=Ye.style;ke.bottom=b,ke.width=k!=null?k:""}if(c&&y!=="fullscreen"){if(y==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=q,Z.maxWidth=Ae,Z.maxHeight=D,Z.height=D;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${ue})`,Z.top=_,Z.width=F,Z.maxWidth=Ae}},no=()=>{var D,Ae,ue,Z,ye,Te,$e,rt;if(!N())return;if($()){let it=(ue=((Ae=(D=r.launcher)==null?void 0:D.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",lt=H?"expanded":"collapsed";le.dataset.state=lt,le.dataset.expandedSize=it,Ye&&(Ye.dataset.state=lt,Ye.dataset.expandedSize=it),le.style.removeProperty("display"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ea(H),de.style.display=H?"flex":"none",dr(),H?(Aa(),Sa()):(Ts(),Es()),Hr();return}let c=rn(r),f=(Z=e.ownerDocument.defaultView)!=null?Z:window,y=(Te=(ye=r.launcher)==null?void 0:ye.mobileBreakpoint)!=null?Te:640,b=(rt=($e=r.launcher)==null?void 0:$e.mobileFullscreen)!=null?rt:!0,k=f.innerWidth<=y,F=b&&k&&E,_=ir(r).reveal;H?(le.style.removeProperty("display"),le.style.display=c?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0"),oe.classList.add("persona-scale-100","persona-opacity-100"),Me?Me.element.style.display="none":Xe&&(Xe.style.display="none")):(c?c&&(_==="overlay"||_==="push")&&!F?(le.style.removeProperty("display"),le.style.display="flex",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.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"),oe.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"),oe.classList.remove("persona-scale-100","persona-opacity-100"),oe.classList.add("persona-scale-95","persona-opacity-0")),Me?Me.element.style.display=c?"none":"":Xe&&(Xe.style.display=c?"none":""))},Ht=(c,f="user")=>{var F,_;if(!N()||H===c)return;let y=H;H=c,no();let b=(()=>{var $e,rt,Qe,it,lt,Le,ke,Ve,M,Ee;let q=(rt=($e=r.launcher)==null?void 0:$e.sidebarMode)!=null?rt:!1,D=(Qe=e.ownerDocument.defaultView)!=null?Qe:window,Ae=(lt=(it=r.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,ue=(ke=(Le=r.launcher)==null?void 0:Le.mobileBreakpoint)!=null?ke:640,Z=D.innerWidth<=ue,ye=rn(r)&&Ae&&Z,Te=$()&&((Ee=(M=(Ve=r.launcher)==null?void 0:Ve.composerBar)==null?void 0:M.expandedSize)!=null?Ee:"fullscreen")==="fullscreen";return q||Ae&&Z&&E||ye||Te})();if(H&&b){if(!Gt){let q=e.getRootNode(),D=q instanceof ShadowRoot?q.host:e.closest(".persona-host");D&&(Gt=ll(D,(_=(F=r.launcher)==null?void 0:F.zIndex)!=null?_:hn))}Xt||(Xt=cl(e.ownerDocument))}else H||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null);H&&(It(),Yr(!0));let k={open:H,source:f,timestamp:Date.now()};H&&!y?o.emit("widget:opened",k):!H&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:H,launcherEnabled:E,voiceActive:gt.active,streaming:T.isStreaming()})},Jo=c=>{Ut(c?"stop":"send"),z&&(z.disabled=c),pr.buttons.forEach(f=>{f.disabled=c}),Ue.dataset.personaComposerStreaming=c?"true":"false",Ue.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Go=()=>{gt.active||pe&&pe.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Go(),200)});let ks=()=>{var y,b,k,F,_,q,D,Ae,ue,Z,ye;Bn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Yn.textContent=(F=(k=r.copy)==null?void 0:k.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",pe.placeholder=(q=(_=r.copy)==null?void 0:_.inputPlaceholder)!=null?q:"How can I help...";let c=G.querySelector("[data-persona-intro-card]");if(c){let Te=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Te?"":"none",Te?(G.classList.remove("persona-gap-3"),G.classList.add("persona-gap-6")):(G.classList.remove("persona-gap-6"),G.classList.add("persona-gap-3"))}!((ue=(Ae=r.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(T!=null&&T.isStreaming())&&(ie.textContent=(ye=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?ye:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(f=>({...f,sessionId:c}))}});let Ar=null,Ma=()=>{Ar==null&&(Ar=setInterval(()=>{let c=je.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ar),Ar=null;return}let f=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=$a(f-b))})},100))};if(T=new ss(r,{onMessagesChanged(c){Co(je,c,He),Ma(),T&&(c.some(k=>k.role==="user")?pr.render([],T,pe,c):pr.render(r.suggestionChips,T,pe,c,r.suggestionChipsConfig)),Yr(!Vn),wa(c);let f=[...c].reverse().find(b=>b.role==="user"),y=gt.lastUserMessageId;f&&f.id!==y&&(gt.lastUserMessageId=f.id,o.emit("user:message",f)),gt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Ko(c),Hr()},onStatusChanged(c){var b;let f=(b=r.statusIndicator)!=null?b:{};me(cn,(k=>{var F,_,q,D;return k==="idle"?(F=f.idleText)!=null?F:fn.idle:k==="connecting"?(_=f.connectingText)!=null?_:fn.connecting:k==="connected"?(q=f.connectedText)!=null?q:fn.connected:k==="error"?(D=f.errorText)!=null?D:fn.error:fn[k]})(c),f,c)},onStreamingChanged(c){Vn=c,Jo(c),T&&Co(je,T.getMessages(),He),c||Yr(!0),Hr()},onVoiceStatusChanged(c){var f,y;if(((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":ee(),P();break;case"speaking":ee(),Y();break;default:c==="idle"&&T.isBargeInActive()?(ee(),U(),z==null||z.setAttribute("aria-label","End voice session")):(gt.active=!1,ee(),or("system"),Pn());break}},onArtifactsState(c){$n=c,Un(),Ko()}}),Pt.current=T,((jc=(_c=r.voiceRecognition)==null?void 0:_c.provider)==null?void 0:jc.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,f)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,f),ce==null||ce.processEvent(c,f),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,y,b;c&&(c.metadata&&(d=Rl(c.metadata),w.syncFromMetadata()),(f=c.messages)!=null&&f.length&&T.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&T.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Ls=()=>{var f,y,b;!$()||H||!((b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Ht(!0,"auto")},Ps=c=>{var k;if(c.preventDefault(),T.isStreaming()){T.cancel(),ce==null||ce.reset(),Ce==null||Ce.update();return}let f=pe.value.trim(),y=(k=nt==null?void 0:nt.hasAttachments())!=null?k:!1;if(!f&&!y)return;Ls();let b;y&&(b=[],b.push(...nt.getContentParts()),f&&b.push(qs(f))),pe.value="",pe.style.height="auto",wo(),T.sendMessage(f,{contentParts:b}),y&&nt.clearAttachments()},ka=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Xo={...ii},Qo=!1,wo=()=>{Xo={...ii}},La=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),Pa=c=>{if(!pe)return;Qo=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Qo=!1;let f=pe.value.length;pe.setSelectionRange(f,f)},Is=()=>{Qo||wo()},Ws=c=>{if(pe){if(ka()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=pe.selectionStart===0&&pe.selectionEnd===0,y=ku({direction:c.key==="ArrowUp"?"up":"down",history:La(),currentValue:pe.value,atStart:f,state:Xo});if(Xo=y.state,y.handled){c.preventDefault(),y.value!==void 0&&Pa(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}wo(),c.preventDefault(),ie.click()}}},Rs=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(de)&&(T.cancel(),ce==null||ce.reset(),Ce==null||Ce.update(),wo(),c.preventDefault(),c.stopImmediatePropagation())},Hs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!nt)return;let f=Oh(c.clipboardData);f.length!==0&&(c.preventDefault(),await nt.handleFiles(f))},Cn=null,Kn=!1,Br=null,st=null,Bs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ao=(c="user")=>{var F,_,q,D,Ae,ue,Z;if(Kn||T.isStreaming())return;let f=Bs();if(!f)return;Cn=new f;let b=(_=((F=r.voiceRecognition)!=null?F:{}).pauseDuration)!=null?_:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let k=pe.value;Cn.onresult=ye=>{let Te="",$e="";for(let Qe=0;Qe<ye.results.length;Qe++){let it=ye.results[Qe],lt=it[0].transcript;it.isFinal?Te+=lt+" ":$e=lt}let rt=k+Te+$e;pe.value=rt,Br&&clearTimeout(Br),(Te||$e)&&(Br=window.setTimeout(()=>{let Qe=pe.value.trim();Qe&&Cn&&Kn&&(hr(),pe.value="",pe.style.height="auto",T.sendMessage(Qe,{viaVoice:!0}))},b))},Cn.onerror=ye=>{ye.error!=="no-speech"&&hr()},Cn.onend=()=>{if(Kn){let ye=pe.value.trim();ye&&ye!==k.trim()&&(pe.value="",pe.style.height="auto",T.sendMessage(ye,{viaVoice:!0})),hr()}};try{if(Cn.start(),Kn=!0,gt.active=!0,c!=="system"&&(gt.manuallyDeactivated=!1),or(c),Pn(),z){let ye=(q=r.voiceRecognition)!=null?q:{};st={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((Z=(ue=ye.iconSize)!=null?ue:(Ae=r.sendButton)==null?void 0:Ae.size)!=null?Z:"40")||24};let Te=ye.recordingBackgroundColor,$e=ye.recordingIconColor,rt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=$e!=null?$e:"var(--persona-voice-recording-indicator, #ffffff)",$e){let Qe=z.querySelector("svg");Qe&&Qe.setAttribute("stroke",$e)}rt&&(z.style.borderColor=rt),z.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(),z){if(z.classList.remove("persona-voice-recording"),st){z.style.backgroundColor=st.backgroundColor,z.style.color=st.color,z.style.borderColor=st.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",st.color||"currentColor"),st=null}z.setAttribute("aria-label","Start voice recognition")}}},Ia=(c,f)=>{var it,lt,Le,ke,Ve,M,Ee,Be;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(y||b))return null;let F=h("div","persona-send-button-wrapper"),_=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let q=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",D=(Le=f==null?void 0:f.size)!=null?Le:"40px",Ae=(ke=c==null?void 0:c.iconSize)!=null?ke:D,ue=parseFloat(Ae)||24,Z=(Ve=c==null?void 0:c.backgroundColor)!=null?Ve:f==null?void 0:f.backgroundColor,ye=(M=c==null?void 0:c.iconColor)!=null?M:f==null?void 0:f.textColor;_.style.width=Ae,_.style.height=Ae,_.style.minWidth=Ae,_.style.minHeight=Ae,_.style.fontSize="18px",_.style.lineHeight="1",ye?_.style.color=ye:_.style.color="var(--persona-text, #111827)";let $e=be(q,ue,ye||"currentColor",1.5);$e?_.appendChild($e):_.textContent="\u{1F3A4}",Z?_.style.backgroundColor=Z:_.style.backgroundColor="",c!=null&&c.borderWidth&&(_.style.borderWidth=c.borderWidth,_.style.borderStyle="solid"),c!=null&&c.borderColor&&(_.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(_.style.paddingLeft=c.paddingX,_.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(_.style.paddingTop=c.paddingY,_.style.paddingBottom=c.paddingY),F.appendChild(_);let rt=(Ee=c==null?void 0:c.tooltipText)!=null?Ee:"Start voice recognition";if(((Be=c==null?void 0:c.showTooltip)!=null?Be:!1)&&rt){let Ge=h("div","persona-send-button-tooltip");Ge.textContent=rt,F.appendChild(Ge)}return{micButton:_,micButtonWrapper:F}},ro=()=>{var f,y,b,k,F;if(!z||st)return;let c=(f=r.voiceRecognition)!=null?f:{};st={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((F=(k=c.iconSize)!=null?k:(b=r.sendButton)==null?void 0:b.size)!=null?F:"40")||24}},Je=(c,f)=>{var F,_,q,D,Ae;if(!z)return;let y=z.querySelector("svg");y&&y.remove();let b=(Ae=st==null?void 0:st.iconSize)!=null?Ae:parseFloat((D=(q=(F=r.voiceRecognition)==null?void 0:F.iconSize)!=null?q:(_=r.sendButton)==null?void 0:_.size)!=null?D:"40")||24,k=be(c,b,f,1.5);k&&z.appendChild(k)},A=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},U=()=>{var k;if(!z)return;ro();let c=(k=r.voiceRecognition)!=null?k:{},f=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(A(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let F=z.querySelector("svg");F&&F.setAttribute("stroke",y)}b&&(z.style.borderColor=b),z.setAttribute("aria-label","Stop voice recognition")},P=()=>{var q,D,Ae,ue,Z,ye,Te,$e;if(!z)return;ro();let c=(q=r.voiceRecognition)!=null?q:{},f=T.getVoiceInterruptionMode(),y=(D=c.processingIconName)!=null?D:"loader",b=(ue=(Ae=c.processingIconColor)!=null?Ae:st==null?void 0:st.color)!=null?ue:"",k=(ye=(Z=c.processingBackgroundColor)!=null?Z:st==null?void 0:st.backgroundColor)!=null?ye:"",F=($e=(Te=c.processingBorderColor)!=null?Te:st==null?void 0:st.borderColor)!=null?$e:"";A(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=k,z.style.borderColor=F;let _=b||"currentColor";z.style.color=_,Je(y,_),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},Y=()=>{var Ae,ue,Z,ye,Te,$e,rt,Qe,it,lt,Le,ke;if(!z)return;ro();let c=(Ae=r.voiceRecognition)!=null?Ae:{},f=T.getVoiceInterruptionMode(),y=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=(ue=c.speakingIconName)!=null?ue:y,k=($e=c.speakingIconColor)!=null?$e:f==="barge-in"?(ye=(Z=c.recordingIconColor)!=null?Z:st==null?void 0:st.color)!=null?ye:"":(Te=st==null?void 0:st.color)!=null?Te:"",F=(it=c.speakingBackgroundColor)!=null?it:f==="barge-in"?(rt=c.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(Qe=st==null?void 0:st.backgroundColor)!=null?Qe:"",_=(ke=c.speakingBorderColor)!=null?ke:f==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Le=st==null?void 0:st.borderColor)!=null?Le:"";A(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=F,z.style.borderColor=_;let q=k||"currentColor";z.style.color=q,Je(b,q);let D=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",D),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},ee=()=>{var c,f,y;z&&(A(),st&&(z.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",z.style.color=(f=st.color)!=null?f:"",z.style.borderColor=(y=st.borderColor)!=null?y:"",Je(st.iconName,st.color||"currentColor"),st=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},J=()=>{var c,f;if(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let y=T.getVoiceStatus(),b=T.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),ee()});return}T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),gt.manuallyDeactivated=!T.isVoiceActive(),Pn(),or("user"),T.isVoiceActive()?U():ee()});return}if(Kn){let y=pe.value.trim();gt.manuallyDeactivated=!0,Pn(),hr("user"),y&&(pe.value="",pe.style.height="auto",T.sendMessage(y))}else gt.manuallyDeactivated=!1,Pn(),Ao("user")};Dn=J,z&&(z.addEventListener("click",J),ft.push(()=>{var c,f;((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),ee()):hr("system"),z&&z.removeEventListener("click",J)}));let Re=o.on("assistant:complete",()=>{ws&&(gt.active||gt.manuallyDeactivated||ws==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!gt.active&&!gt.manuallyDeactivated&&(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("auto"),T.isVoiceActive()&&U()}):Ao("auto"))},600))});ft.push(Re);let _e=o.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});ft.push(_e);let tt=()=>{Ht(!H,"user")},Me=null,Xe=null;if(E&&!$()){let c=s.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:r,defaultRenderer:()=>oa(r,tt).element,onToggle:tt});f&&(Xe=f)}Xe||(Me=oa(r,tt))}Me?e.appendChild(Me.element):Xe&&e.appendChild(Xe),no(),pr.render(r.suggestionChips,T,pe,void 0,r.suggestionChipsConfig),ks(),Jo(T.isStreaming()),Yr(!0),ba(),L&&(!E||$()?setTimeout(()=>Go(),0):H&&setTimeout(()=>Go(),200));let It=()=>{var D,Ae,ue,Z,ye,Te,$e,rt,Qe,it,lt,Le,ke,Ve,M,Ee,Be,Ge,ve,Lt,at,Yt;if($()){bt(),no();return}let c=rn(r),f=(Ae=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?Ae:!1,y=c||f||((Z=(ue=r.launcher)==null?void 0:ue.fullHeight)!=null?Z:!1),b=(ye=e.ownerDocument.defaultView)!=null?ye:window,k=($e=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?$e:!0,F=(Qe=(rt=r.launcher)==null?void 0:rt.mobileBreakpoint)!=null?Qe:640,_=b.innerWidth<=F,q=k&&_&&E;try{if(q){dr(),io(e,r);return}if(W&&(W=!1,dr(),io(e,r)),!E&&!c){oe.style.height="",oe.style.width="";return}if(!f&&!c){let dn=(lt=(it=r==null?void 0:r.launcher)==null?void 0:it.width)!=null?lt:r==null?void 0:r.launcherWidth,Wt=dn!=null?dn:Xn;oe.style.width=Wt,oe.style.maxWidth=Wt}if(Cr(),!y){let dn=b.innerHeight,Wt=64,An=(ke=(Le=r.launcher)==null?void 0:Le.heightOffset)!=null?ke:0,pn=Math.max(200,dn-Wt),et=Math.min(640,pn),ct=Math.max(200,et-An);oe.style.height=`${ct}px`}}finally{if(bt(),no(),H&&E){let Wt=((Ve=e.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((Ee=(M=r.launcher)==null?void 0:M.mobileBreakpoint)!=null?Ee:640),An=(Ge=(Be=r.launcher)==null?void 0:Be.sidebarMode)!=null?Ge:!1,pn=(Lt=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Lt:!0,et=rn(r)&&pn&&Wt,ct=An||pn&&Wt&&E||et;if(ct&&!Xt){let Sn=e.getRootNode(),mn=Sn instanceof ShadowRoot?Sn.host:e.closest(".persona-host");mn&&!Gt&&(Gt=ll(mn,(Yt=(at=r.launcher)==null?void 0:at.zIndex)!=null?Yt:hn)),Xt=cl(e.ownerDocument)}else ct||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null)}}};It();let on=(Uc=e.ownerDocument.defaultView)!=null?Uc:window;if(on.addEventListener("resize",It),ft.push(()=>on.removeEventListener("resize",It)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe(Ue),ft.push(()=>c.disconnect())}gr=G.scrollTop;let At=G.scrollHeight,kt=()=>{let c=G.scrollTop,f=G.scrollHeight,y=f<At;At=f;let{action:b,nextLastScrollTop:k}=ci({following:mr.isFollowing(),currentScrollTop:c,lastScrollTop:gr,nearBottom:Qs(G,Cs),userScrollThreshold:ha,isAutoScrolling:Ir||xo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gr=k,b==="resume"){Qr();return}b==="pause"&&Ss()};G.addEventListener("scroll",kt,{passive:!0}),ft.push(()=>G.removeEventListener("scroll",kt));let sn=c=>{let f=di({following:mr.isFollowing(),deltaY:c.deltaY,nearBottom:Qs(G,Cs),resumeWhenNearBottom:!0});f==="pause"?Ss():f==="resume"&&Qr()};G.addEventListener("wheel",sn,{passive:!0}),ft.push(()=>G.removeEventListener("wheel",sn)),Tt.addEventListener("click",()=>{G.scrollTop=G.scrollHeight,gr=G.scrollTop,Qr(),Yr(!0)}),ft.push(()=>Tt.remove()),ft.push(()=>{As()});let un=()=>{ze&&(zn&&(ze.removeEventListener("click",zn),zn=null),N()?(ze.style.display="",zn=()=>{Ht(!1,"user")},ze.addEventListener("click",zn)):ze.style.display="none")};un(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{T.clearMessages(),ur.clear(),Qr(),fo(We.composerOverlay);try{localStorage.removeItem(xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xs)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 f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),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={},w.syncFromMetadata(),K==null||K.clear(),ce==null||ce.reset(),Ce==null||Ce.update()})})(),$t&&$t.addEventListener("submit",Ps),pe==null||pe.addEventListener("keydown",Ws),pe==null||pe.addEventListener("input",Is),pe==null||pe.addEventListener("paste",Hs);let Qt=(qc=e.ownerDocument)!=null?qc:document;Qt.addEventListener("keydown",Rs,!0);let sr="persona-attachment-drop-active",Ds=0,Ji=()=>{Ds=0,de.classList.remove(sr)},Yo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&nt!==null},Ql=c=>{!Fi(c.dataTransfer)||!Yo()||(Ds++,Ds===1&&de.classList.add(sr))},Yl=c=>{!Fi(c.dataTransfer)||!Yo()||(Ds--,Ds<=0&&Ji())},Zl=c=>{!Fi(c.dataTransfer)||!Yo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},ec=c=>{var y;if(!Fi(c.dataTransfer)||!Yo())return;c.preventDefault(),c.stopPropagation(),Ji();let f=Array.from((y=c.dataTransfer.files)!=null?y:[]);f.length!==0&&nt.handleFiles(f)},oo=!0;de.addEventListener("dragenter",Ql,oo),de.addEventListener("dragleave",Yl,oo),e.addEventListener("dragover",Zl,oo),e.addEventListener("drop",ec,oo);let Wa=e.ownerDocument,tc=c=>{Yo()&&c.preventDefault()},nc=c=>{Yo()&&c.preventDefault()};Wa.addEventListener("dragover",tc),Wa.addEventListener("drop",nc),ft.push(()=>{$t&&$t.removeEventListener("submit",Ps),pe==null||pe.removeEventListener("keydown",Ws),pe==null||pe.removeEventListener("input",Is),pe==null||pe.removeEventListener("paste",Hs),Qt.removeEventListener("keydown",Rs,!0)}),ft.push(()=>{de.removeEventListener("dragenter",Ql,oo),de.removeEventListener("dragleave",Yl,oo),e.removeEventListener("dragover",Zl,oo),e.removeEventListener("drop",ec,oo),Wa.removeEventListener("dragover",tc),Wa.removeEventListener("drop",nc),Ji()}),ft.push(()=>{T.cancel()}),Me?ft.push(()=>{Me==null||Me.destroy()}):Xe&&ft.push(()=>{Xe==null||Xe.remove()});let tn={update(c){var nn,Sr,Nr,Ra,Ha,Ba,ko,Da,Ns,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,Cd,wd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$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,Cp,wp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp,Op,$p,_p,jp,Up,qp,zp,Vp;let f=r.toolCall,y=r.messageActions,b=(nn=r.layout)==null?void 0:nn.messages,k=r.colorScheme,F=r.loadingIndicator,_=r.iterationDisplay,q=(Sr=r.features)==null?void 0:Sr.showReasoning,D=(Nr=r.features)==null?void 0:Nr.showToolCalls,Ae=(Ra=r.features)==null?void 0:Ra.toolCallDisplay,ue=(Ha=r.features)==null?void 0:Ha.reasoningDisplay;r={...r,...c},dr(),io(e,r),Li(e,r),Pi(e,r),Un(),r.colorScheme!==k&&Xr();let Z=pa.getForInstance(r.plugins);s.length=0,s.push(...Z),E=(ko=(Ba=r.launcher)==null?void 0:Ba.enabled)!=null?ko:!0,B=(Ns=(Da=r.launcher)==null?void 0:Da.autoExpand)!=null?Ns:!1,qe=(Yc=(Qc=r.features)==null?void 0:Qc.showReasoning)!=null?Yc:!0,Oe=(ed=(Zc=r.features)==null?void 0:Zc.showToolCalls)!=null?ed:!0,xe=(nd=(td=r.features)==null?void 0:td.scrollToBottom)!=null?nd:{},Vt(),Rr();let ye=fe;if(fe=(od=(rd=r.features)==null?void 0:rd.showEventStreamToggle)!=null?od:!1,fe&&!ye){if(K||(te=new ca(De),K=new la(Ie,te),ce=ce!=null?ce:new da,te.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),T.setSSEEventCallback((X,vt)=>{var Ot;(Ot=r.onSSEEvent)==null||Ot.call(r,X,vt),ce==null||ce.processEvent(X,vt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!mt&&Fe){let X=(ad=(sd=r.features)==null?void 0:sd.eventStream)==null?void 0:ad.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");mt=h("button",vt),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 Ot=be("activity","18px","currentColor",1.5);Ot&&mt.appendChild(Ot);let dt=We.clearChatButtonWrapper,Et=We.closeButtonWrapper,an=dt||Et;an&&an.parentNode===Fe?Fe.insertBefore(mt,an):Fe.appendChild(mt),mt.addEventListener("click",()=>{he?Nn():bn()})}}else!fe&&ye&&(Nn(),mt&&(mt.remove(),mt=null),K==null||K.clear(),te==null||te.destroy(),K=null,te=null,ce==null||ce.reset(),ce=null);if(((id=r.launcher)==null?void 0:id.enabled)===!1&&Me&&(Me.destroy(),Me=null),((ld=r.launcher)==null?void 0:ld.enabled)===!1&&Xe&&(Xe.remove(),Xe=null),((cd=r.launcher)==null?void 0:cd.enabled)!==!1&&!Me&&!Xe){let X=s.find(vt=>vt.renderLauncher);if(X!=null&&X.renderLauncher){let vt=X.renderLauncher({config:r,defaultRenderer:()=>oa(r,tt).element,onToggle:tt});vt&&(Xe=vt,e.appendChild(Xe))}Xe||(Me=oa(r,tt),e.appendChild(Me.element))}Me&&Me.update(r),Se&&((dd=r.launcher)==null?void 0:dd.title)!==void 0&&(Se.textContent=r.launcher.title),Ne&&((pd=r.launcher)==null?void 0:pd.subtitle)!==void 0&&(Ne.textContent=r.launcher.subtitle);let Te=(ud=r.layout)==null?void 0:ud.header;if((Te==null?void 0:Te.layout)!==S&&Fe){let X=Te?cs(r,Te,{showClose:N(),onClose:()=>Ht(!1,"user")}):$r({config:r,showClose:N(),onClose:()=>Ht(!1,"user")});Fe.replaceWith(X.header),Fe=X.header,O=X.iconHolder,Se=X.headerTitle,Ne=X.headerSubtitle,ze=X.closeButton,S=Te==null?void 0:Te.layout}else if(Te&&(O&&(O.style.display=Te.showIcon===!1?"none":""),Se&&(Se.style.display=Te.showTitle===!1?"none":""),Ne&&(Ne.style.display=Te.showSubtitle===!1?"none":""),ze&&(ze.style.display=Te.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let X=Te.showClearChat;if(X!==void 0){We.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:vt}=We;vt&&!vt.classList.contains("persona-absolute")&&(X?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let rt=((md=r.layout)==null?void 0:md.showHeader)!==!1;Fe&&(Fe.style.display=rt?"":"none");let Qe=((gd=r.layout)==null?void 0:gd.showFooter)!==!1;Ue&&(Ue.style.display=Qe?"":"none"),bt(),Rr(),E!==R?E?Ht(B,"auto"):(H=!0,no()):B!==I&&Ht(B,"auto"),I=B,R=E,It(),un();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(f),ke=JSON.stringify(r.messageActions)!==JSON.stringify(y),Ve=JSON.stringify((fd=r.layout)==null?void 0:fd.messages)!==JSON.stringify(b),M=((hd=r.loadingIndicator)==null?void 0:hd.render)!==(F==null?void 0:F.render)||((yd=r.loadingIndicator)==null?void 0:yd.renderIdle)!==(F==null?void 0:F.renderIdle)||((bd=r.loadingIndicator)==null?void 0:bd.showBubble)!==(F==null?void 0:F.showBubble),Ee=r.iterationDisplay!==_,Be=((vd=(xd=r.features)==null?void 0:xd.showReasoning)!=null?vd:!0)!==(q!=null?q:!0)||((wd=(Cd=r.features)==null?void 0:Cd.showToolCalls)!=null?wd:!0)!==(D!=null?D:!0)||JSON.stringify((Ad=r.features)==null?void 0:Ad.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((Sd=r.features)==null?void 0:Sd.reasoningDisplay)!==JSON.stringify(ue);(Le||ke||Ve||M||Ee||Be)&&T&&(vs++,Co(je,T.getMessages(),He));let ve=(Td=r.launcher)!=null?Td:{},Lt=(Ed=ve.headerIconHidden)!=null?Ed:!1,at=(kd=(Md=r.layout)==null?void 0:Md.header)==null?void 0:kd.showIcon,Yt=Lt||at===!1,dn=ve.headerIconName,Wt=(Ld=ve.headerIconSize)!=null?Ld:"48px";if(O){let X=de.querySelector(".persona-border-b-persona-divider"),vt=X==null?void 0:X.querySelector(".persona-flex-col");if(Yt)O.style.display="none",X&&vt&&!X.contains(vt)&&X.insertBefore(vt,X.firstChild);else{if(O.style.display="",O.style.height=Wt,O.style.width=Wt,X&&vt&&(X.contains(O)?O.nextSibling!==vt&&(O.remove(),X.insertBefore(O,vt)):X.insertBefore(O,vt)),dn){let dt=parseFloat(Wt)||24,Et=be(dn,dt*.6,"#ffffff",2);Et?O.replaceChildren(Et):O.textContent=(Pd=ve.agentIconText)!=null?Pd:"\u{1F4AC}"}else if(ve.iconUrl){let dt=O.querySelector("img");if(dt)dt.src=ve.iconUrl,dt.style.height=Wt,dt.style.width=Wt;else{let Et=document.createElement("img");Et.src=ve.iconUrl,Et.alt="",Et.className="persona-rounded-xl persona-object-cover",Et.style.height=Wt,Et.style.width=Wt,O.replaceChildren(Et)}}else{let dt=O.querySelector("svg"),Et=O.querySelector("img");(dt||Et)&&O.replaceChildren(),O.textContent=(Id=ve.agentIconText)!=null?Id:"\u{1F4AC}"}let Ot=O.querySelector("img");Ot&&(Ot.style.height=Wt,Ot.style.width=Wt)}}let An=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showTitle,pn=(Bd=(Hd=r.layout)==null?void 0:Hd.header)==null?void 0:Bd.showSubtitle;if(Se&&(Se.style.display=An===!1?"none":""),Ne&&(Ne.style.display=pn===!1?"none":""),ze){((Nd=(Dd=r.layout)==null?void 0:Dd.header)==null?void 0:Nd.showCloseButton)===!1?ze.style.display="none":ze.style.display="";let vt=(Fd=ve.closeButtonSize)!=null?Fd:"32px",Ot=(Od=ve.closeButtonPlacement)!=null?Od:"inline";ze.style.height=vt,ze.style.width=vt;let{closeButtonWrapper:dt}=We,Et=Ot==="top-right",an=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Et!==an)if(dt.remove(),Et)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let ut=(_d=($d=ve.clearChat)==null?void 0:$d.placement)!=null?_d:"inline",ln=(Ud=(jd=ve.clearChat)==null?void 0:jd.enabled)!=null?Ud:!0;dt.className=ln&&ut==="inline"?"":"persona-ml-auto";let Hn=de.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(dt)}if(ze.style.color=ve.closeButtonColor||Mn.actionIconColor,ve.closeButtonBackgroundColor?(ze.style.backgroundColor=ve.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ut=ve.closeButtonBorderWidth||"0px",ln=ve.closeButtonBorderColor||"transparent";ze.style.border=`${ut} solid ${ln}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");ve.closeButtonBorderRadius?(ze.style.borderRadius=ve.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(ze.style.paddingLeft=ve.closeButtonPaddingX,ze.style.paddingRight=ve.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),ve.closeButtonPaddingY?(ze.style.paddingTop=ve.closeButtonPaddingY,ze.style.paddingBottom=ve.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let gn=(qd=ve.closeButtonIconName)!=null?qd:"x",yr=(zd=ve.closeButtonIconText)!=null?zd:"\xD7";ze.innerHTML="";let En=be(gn,"28px","currentColor",1);En?ze.appendChild(En):ze.textContent=yr;let Zt=(Vd=ve.closeButtonTooltipText)!=null?Vd:"Close chat",Gn=(Kd=ve.closeButtonShowTooltip)!=null?Kd:!0;if(ze.setAttribute("aria-label",Zt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!ze)return;let Lo=ze.ownerDocument,Fs=Lo.body;if(!Fs)return;ut=Tr(Lo,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Os=Tr(Lo,"div");Os.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Os);let Po=ze.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(lo),ut.style.left=`${Po.left+Po.width/2}px`,ut.style.top=`${Po.top-8}px`,ut.style.transform="translate(-50%, -100%)",Fs.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",ln),dt.addEventListener("mouseleave",Hn),ze.addEventListener("focus",ln),ze.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",ln),dt.removeEventListener("mouseleave",Hn)),ze&&(ze.removeEventListener("focus",ln),ze.removeEventListener("blur",Hn))}}}let{clearChatButton:et,clearChatButtonWrapper:ct}=We;if(et){let X=(Jd=ve.clearChat)!=null?Jd:{},vt=(Gd=X.enabled)!=null?Gd:!0,Ot=(Qd=(Xd=r.layout)==null?void 0:Xd.header)==null?void 0:Qd.showClearChat,dt=Ot!==void 0?Ot:vt,Et=(Yd=X.placement)!=null?Yd:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:an}=We;!$()&&an&&!an.classList.contains("persona-absolute")&&(dt?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let gn=Et==="top-right",yr=ct.classList.contains("persona-absolute");if(!$()&&gn!==yr&&dt){if(ct.remove(),gn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Zt=de.querySelector(".persona-border-b-persona-divider"),Gn=We.closeButtonWrapper;Zt&&Gn&&Gn.parentElement===Zt?Zt.insertBefore(ct,Gn):Zt&&Zt.appendChild(ct)}let En=We.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(dt){if(!$()){let ut=(Zd=X.size)!=null?Zd:"32px";et.style.height=ut,et.style.width=ut}let an=(ep=X.iconName)!=null?ep:"refresh-cw",gn=(tp=X.iconColor)!=null?tp:"";et.style.color=gn||Mn.actionIconColor,et.innerHTML="";let yr=$()?"14px":"20px",En=be(an,yr,"currentColor",2);if(En&&et.appendChild(En),X.backgroundColor?(et.style.backgroundColor=X.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let ut=X.borderWidth||"0px",ln=X.borderColor||"transparent";et.style.border=`${ut} solid ${ln}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");X.borderRadius?(et.style.borderRadius=X.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),X.paddingX?(et.style.paddingLeft=X.paddingX,et.style.paddingRight=X.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),X.paddingY?(et.style.paddingTop=X.paddingY,et.style.paddingBottom=X.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let Zt=(np=X.tooltipText)!=null?np:"Clear chat",Gn=(rp=X.showTooltip)!=null?rp:!0;if(et.setAttribute("aria-label",Zt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!et)return;let Lo=et.ownerDocument,Fs=Lo.body;if(!Fs)return;ut=Tr(Lo,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Os=Tr(Lo,"div");Os.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Os);let Po=et.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(lo),ut.style.left=`${Po.left+Po.width/2}px`,ut.style.top=`${Po.top-8}px`,ut.style.transform="translate(-50%, -100%)",Fs.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};ct.addEventListener("mouseenter",ln),ct.addEventListener("mouseleave",Hn),et.addEventListener("focus",ln),et.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",ln),ct.removeEventListener("mouseleave",Hn)),et&&(et.removeEventListener("focus",ln),et.removeEventListener("blur",Hn))}}}}let Sn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ua],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Uo.message,Uo.messageAndClick];w=ma({parsers:Sn,handlers:mn,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),He=km(r,w,se),T.updateConfig(r),Co(je,T.getMessages(),He),pr.render(r.suggestionChips,T,pe,void 0,r.suggestionChipsConfig),ks(),Jo(T.isStreaming());let So=((op=r.voiceRecognition)==null?void 0:op.enabled)===!0,To=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Eo=((ap=(sp=r.voiceRecognition)==null?void 0:sp.provider)==null?void 0:ap.type)==="runtype";if(So&&(To||Eo))if(!z||!_t){let X=Ia(r.voiceRecognition,r.sendButton);X&&(z=X.micButton,_t=X.micButtonWrapper,St.insertBefore(_t,kn),z.addEventListener("click",J),z.disabled=T.isStreaming())}else{let X=(ip=r.voiceRecognition)!=null?ip:{},vt=(lp=r.sendButton)!=null?lp:{},Ot=(cp=X.iconName)!=null?cp:"mic",dt=(dp=vt.size)!=null?dp:"40px",Et=(pp=X.iconSize)!=null?pp:dt,an=parseFloat(Et)||24;z.style.width=Et,z.style.height=Et,z.style.minWidth=Et,z.style.minHeight=Et;let gn=(mp=(up=X.iconColor)!=null?up:vt.textColor)!=null?mp:"currentColor";z.innerHTML="";let yr=be(Ot,an,gn,2);yr?z.appendChild(yr):z.textContent="\u{1F3A4}";let En=(gp=X.backgroundColor)!=null?gp:vt.backgroundColor;En?z.style.backgroundColor=En:z.style.backgroundColor="",gn?z.style.color=gn:z.style.color="var(--persona-text, #111827)",X.borderWidth?(z.style.borderWidth=X.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),X.borderColor?z.style.borderColor=X.borderColor:z.style.borderColor="",X.paddingX?(z.style.paddingLeft=X.paddingX,z.style.paddingRight=X.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),X.paddingY?(z.style.paddingTop=X.paddingY,z.style.paddingBottom=X.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let Zt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Gn=(fp=X.tooltipText)!=null?fp:"Start voice recognition";if(((hp=X.showTooltip)!=null?hp:!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,_t==null||_t.insertBefore(ln,z)}else Zt&&(Zt.style.display="none");_t.style.display="",z.disabled=T.isStreaming()}else z&&_t&&(_t.style.display="none",((bp=(yp=r.voiceRecognition)==null?void 0:yp.provider)==null?void 0:bp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Kn&&hr());if(((xp=r.attachments)==null?void 0:xp.enabled)===!0)if(!Ft||!Ze){let X=(vp=r.attachments)!=null?vp:{},Ot=(wp=((Cp=r.sendButton)!=null?Cp:{}).size)!=null?wp:"40px";ge||(ge=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",$t.insertBefore(ge,pe)),re||(re=document.createElement("input"),re.type="file",re.accept=((Ap=X.allowedTypes)!=null?Ap:Or).join(","),re.multiple=((Sp=X.maxFiles)!=null?Sp:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),$t.insertBefore(re,pe)),Ft=h("div","persona-send-button-wrapper"),Ze=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ze.type="button",Ze.setAttribute("aria-label",(Tp=X.buttonTooltipText)!=null?Tp:"Attach file");let dt=(Ep=X.buttonIconName)!=null?Ep:"paperclip",Et=Ot,an=parseFloat(Et)||40,gn=Math.round(an*.6);Ze.style.width=Et,Ze.style.height=Et,Ze.style.minWidth=Et,Ze.style.minHeight=Et,Ze.style.fontSize="18px",Ze.style.lineHeight="1",Ze.style.backgroundColor="transparent",Ze.style.color="var(--persona-primary, #111827)",Ze.style.border="none",Ze.style.borderRadius="6px",Ze.style.transition="background-color 0.15s ease",Ze.addEventListener("mouseenter",()=>{Ze.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ze.addEventListener("mouseleave",()=>{Ze.style.backgroundColor="transparent"});let yr=be(dt,gn,"currentColor",1.5);yr?Ze.appendChild(yr):Ze.textContent="\u{1F4CE}",Ze.addEventListener("click",Gn=>{Gn.preventDefault(),re==null||re.click()}),Ft.appendChild(Ze);let En=(Mp=X.buttonTooltipText)!=null?Mp:"Attach file",Zt=h("div","persona-send-button-tooltip");Zt.textContent=En,Ft.appendChild(Zt),ot.append(Ft),!nt&&re&&ge&&(nt=Fo.fromConfig(X),nt.setPreviewsContainer(ge),re.addEventListener("change",async()=>{nt&&(re!=null&&re.files)&&(await nt.handleFileSelect(re.files),re.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Lm(X.dropOverlay))}else{Ft.style.display="";let X=(kp=r.attachments)!=null?kp:{};re&&(re.accept=((Lp=X.allowedTypes)!=null?Lp:Or).join(","),re.multiple=((Pp=X.maxFiles)!=null?Pp:4)>1),nt&&nt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Ft&&(Ft.style.display="none"),nt&&nt.clearAttachments(),(Ip=de.querySelector(".persona-attachment-drop-overlay"))==null||Ip.remove();let Kt=(Wp=r.sendButton)!=null?Wp:{},Mo=(Rp=Kt.useIcon)!=null?Rp:!1,so=(Hp=Kt.iconText)!=null?Hp:"\u2191",yt=Kt.iconName,In=(Bp=Kt.tooltipText)!=null?Bp:"Send message",Dr=(Dp=Kt.showTooltip)!=null?Dp:!1,Tn=(Np=Kt.size)!=null?Np:"40px",Wn=Kt.backgroundColor,Bt=Kt.textColor;if(Mo){if(ie.style.width=Tn,ie.style.height=Tn,ie.style.minWidth=Tn,ie.style.minHeight=Tn,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.innerHTML="",Bt?ie.style.color=Bt:ie.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let X=parseFloat(Tn)||24,vt=(Bt==null?void 0:Bt.trim())||"currentColor",Ot=be(yt,X,vt,2);Ot?ie.appendChild(Ot):ie.textContent=so}else ie.textContent=so;ie.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ie.style.backgroundColor=Wn,ie.classList.remove("persona-bg-persona-primary")):(ie.style.backgroundColor="",ie.classList.add("persona-bg-persona-primary"))}else ie.textContent=(Op=(Fp=r.copy)==null?void 0:Fp.sendButtonLabel)!=null?Op:"Send",ie.style.width="",ie.style.height="",ie.style.minWidth="",ie.style.minHeight="",ie.style.fontSize="",ie.style.lineHeight="",ie.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ie.style.backgroundColor=Wn,ie.classList.remove("persona-bg-persona-accent")):ie.classList.add("persona-bg-persona-accent"),Bt?ie.style.color=Bt:ie.classList.add("persona-text-white");Kt.borderWidth?(ie.style.borderWidth=Kt.borderWidth,ie.style.borderStyle="solid"):(ie.style.borderWidth="",ie.style.borderStyle=""),Kt.borderColor?ie.style.borderColor=Kt.borderColor:ie.style.borderColor="",Kt.paddingX?(ie.style.paddingLeft=Kt.paddingX,ie.style.paddingRight=Kt.paddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),Kt.paddingY?(ie.style.paddingTop=Kt.paddingY,ie.style.paddingBottom=Kt.paddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let zt=kn==null?void 0:kn.querySelector(".persona-send-button-tooltip");if(Dr&&In)if(zt)zt.textContent=In,zt.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=In,kn==null||kn.insertBefore(X,ie)}else zt&&(zt.style.display="none");let Dt=(qp=($p=r.layout)==null?void 0:$p.contentMaxWidth)!=null?qp:$()?(Up=(jp=(_p=r.launcher)==null?void 0:_p.composerBar)==null?void 0:jp.contentMaxWidth)!=null?Up:"720px":void 0;Dt?(je.style.maxWidth=Dt,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%",$t&&($t.style.maxWidth=Dt,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=Dt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(je.style.maxWidth="",je.style.marginLeft="",je.style.marginRight="",je.style.width="",$t&&($t.style.maxWidth="",$t.style.marginLeft="",$t.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let Jt=(zp=r.statusIndicator)!=null?zp:{},Rn=(Vp=Jt.visible)!=null?Vp:!0;if(cn.style.display=Rn?"":"none",T){let X=T.getStatus();me(cn,(Ot=>{var dt,Et,an,gn;return Ot==="idle"?(dt=Jt.idleText)!=null?dt:fn.idle:Ot==="connecting"?(Et=Jt.connectingText)!=null?Et:fn.connecting:Ot==="connected"?(an=Jt.connectedText)!=null?an:fn.connected:Ot==="error"?(gn=Jt.errorText)!=null?gn:fn.error:fn[Ot]})(X),Jt,X)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Jn=Jt.align==="left"?"persona-text-left":Jt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Jn)},open(){N()&&Ht(!0,"api")},close(){N()&&Ht(!1,"api")},toggle(){N()&&Ht(!H,"api")},clearChat(){xn=!1,T.clearMessages(),ur.clear(),Qr();try{localStorage.removeItem(xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xs}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},w.syncFromMetadata(),K==null||K.clear(),ce==null||ce.reset(),Ce==null||Ce.update()},setMessage(c){return!pe||T.isStreaming()?!1:(!H&&N()&&Ht(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let f=(c==null?void 0:c.trim())||pe.value.trim();return f?(!H&&N()&&Ht(!0,"system"),pe.value="",pe.style.height="auto",T.sendMessage(f),!0):!1},startVoiceRecognition(){var f,y;return T.isStreaming()?!1:((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype"?(T.isVoiceActive()||(!H&&N()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("user"),T.isVoiceActive()&&U()})),!0):Kn?!0:Bs()?(!H&&N()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),Ao("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),ee()}),!0):!1:Kn?(gt.manuallyDeactivated=!0,Pn(),hr("user"),!0):!1},injectMessage(c){return!H&&N()&&Ht(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!H&&N()&&Ht(!0,"system");let f=T.injectAssistantMessage(c);return j&&(j=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),f},injectUserMessage(c){return!H&&N()&&Ht(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!H&&N()&&Ht(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!H&&N()&&Ht(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!H&&N()&&Ht(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!H&&N()&&Ht(!0,"system"),T.injectTestEvent(c)},async connectStream(c,f){return T.connectStream(c,f)},__pushEventStreamEvent(c){K&&(ce==null||ce.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(){!fe||!K||bn()},hideEventStream(){he&&Nn()},isEventStreamVisible(){return he},showArtifacts(){cr(r)&&(xn=!1,Un(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(xn=!0,Un())},upsertArtifact(c){return cr(r)?(xn=!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 E&&!H&&!$()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,f){let b=T.getMessages().find(k=>{var F;return k.variant==="approval"&&((F=k.approval)==null?void 0:F.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){T.resolveWebMcpApproval(b.id,f);return}return T.resolveApproval(b.approval,f)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,f){return o.on(c,f)},off(c,f){o.off(c,f)},isOpen(){return N()&&H},isVoiceActive(){return gt.active},getState(){return{open:N()&&H,launcherEnabled:E,voiceActive:gt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!H&&N()&&Ht(!0,"system");let f=je.querySelector(".persona-feedback-container");f&&f.remove();let y=Di({onSubmit:async(b,k)=>{var F;T.isClientTokenMode()&&await T.submitCSATFeedback(b,k),(F=c==null?void 0:c.onSubmit)==null||F.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});je.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!H&&N()&&Ht(!0,"system");let f=je.querySelector(".persona-feedback-container");f&&f.remove();let y=Ni({onSubmit:async(b,k)=>{var F;T.isClientTokenMode()&&await T.submitNPSFeedback(b,k),(F=c==null?void 0:c.onSubmit)==null||F.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});je.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return T.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return T.submitNPSFeedback(c,f)},destroy(){Ar!=null&&(clearInterval(Ar),Ar=null),ft.forEach(c=>c()),le.remove(),Ye==null||Ye.remove(),Me==null||Me.destroy(),Xe==null||Xe.remove(),zn&&ze.removeEventListener("click",zn)}};if((((zc=n==null?void 0:n.debugTools)!=null?zc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:y=>y?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=f,ft.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=q=>{let D=q.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",f),ft.push(()=>{window.removeEventListener("persona:focusInput",f)}),fe){let q=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.showEventStream()},D=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",D),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",D)})}let y=q=>{let D=q.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.showArtifacts()},b=q=>{let D=q.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.hideArtifacts()},k=q=>{let D=q.detail;D!=null&&D.instanceId&&D.instanceId!==c||D!=null&&D.artifact&&tn.upsertArtifact(D.artifact)},F=q=>{let D=q.detail;D!=null&&D.instanceId&&D.instanceId!==c||typeof(D==null?void 0:D.id)=="string"&&tn.selectArtifact(D.id)},_=q=>{let D=q.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",_),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",_)})}let ar=$h(r.persistState);if(ar&&N()){let c=_h(ar.storage),f=`${ar.keyPrefix}widget-open`,y=`${ar.keyPrefix}widget-voice`,b=`${ar.keyPrefix}widget-voice-mode`;if(c){let k=((Vc=ar.persist)==null?void 0:Vc.openState)&&c.getItem(f)==="true",F=((Kc=ar.persist)==null?void 0:Kc.voiceState)&&c.getItem(y)==="true",_=((Jc=ar.persist)==null?void 0:Jc.voiceState)&&c.getItem(b)==="true";if(k&&setTimeout(()=>{tn.open(),setTimeout(()=>{var q;if(F||_)tn.startVoiceRecognition();else if((q=ar.persist)!=null&&q.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(Gc=ar.persist)!=null&&Gc.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Xc=ar.persist)!=null&&Xc.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(f),c.removeItem(y),c.removeItem(b)},D=()=>q();window.addEventListener("persona:clear-chat",D),ft.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return p&&N()&&setTimeout(()=>{tn.open()},0),Hr(),tn};var jh=(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},Pm=(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"},Nl=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=""},Im=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Nl(e)},Hl=e=>{e.style.transition=""},Bl=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=""},Dl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},$i=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Uh=(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))},qh=(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)},Wm=(e,t,n,r,s,o,a)=>{var v,x,w,E,B,L;let i=ir(o),d=i.reveal==="push";Uh(e,t,n,r,d),qh(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,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,m=(E=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileBreakpoint)!=null?E:640,g=l!=null?l.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Bl(t),Hl(r),Im(r),Dl(n),$i(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((L=(B=o==null?void 0:o.launcher)==null?void 0:B.zIndex)!=null?L:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Im(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Bl(t),Hl(r),Dl(n),$i(s,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":R;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=I,r.style.transform=S,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",Hl(r),Nl(r),$i(s,r);let I=jh(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",W=i.side==="right"?a?`translateX(-${I}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${I}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=`${R+I}px`,t.style.transition=S,t.style.transform=W,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}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="",Bl(t),Nl(r),Dl(n),$i(s,r);let I=i.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",r.style.position="relative",r.style.overflow=I||W?"hidden":"visible",r.style.transition=S,I&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},zh=(e,t)=>{let n=e.ownerDocument.createElement("div");return Pm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Pm(n,r)},destroy(){n.remove()}}},Vh=(e,t)=>{var B,L,I,R;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"),p=n.createElement("div"),m=(L=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||L?(R=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?R:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),ir(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Wm(a,i,d,l,p,t,m)}),g.observe(a))},x=()=>{Wm(a,i,d,l,p,t,m),v()},w=a.ownerDocument.defaultView,E=()=>{x()};return w==null||w.addEventListener("resize",E),ir(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(S){let W=S.launcherEnabled?S.open:!0;m!==W&&(m=W,x())},updateConfig(S){var W,$;t=S,(($=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)!=null?$:!0)===!1&&(m=!0),x()},destroy(){w==null||w.removeEventListener("resize",E),u(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ga=(e,t)=>rn(t)?Vh(e,t):zh(e,t);var Fl={},Rm=!1,Kh=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},Jh=()=>{try{if(typeof Fl!="undefined"&&Fl.url)return new URL("../widget.css",Fl.url).href}catch{}return null},Hm=(e,t)=>{let n=Jh(),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)}},Ol=e=>{let t=Kh(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=ga(t,s),a,i=[],d=(w,E)=>{var R,S;let L=!((S=(R=E==null?void 0:E.launcher)==null?void 0:R.enabled)!=null?S:!0)||rn(E),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),L&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let W=w.attachShadow({mode:"open"});W.appendChild(I),Hm(W,r)}else w.appendChild(I),Hm(w,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let w=d(o.host,s);a=Oi(w,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(w=>w()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(Rm||(Rm=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let u=w=>{g(),o.destroy(),o=ga(t,w),s=w,m()},v={update(w){var S,W,$,N,H,j;let E={...s,...w,launcher:{...(S=s==null?void 0:s.launcher)!=null?S:{},...(W=w==null?void 0:w.launcher)!=null?W:{},dock:{...(N=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?N:{},...(j=(H=w==null?void 0:w.launcher)==null?void 0:H.dock)!=null?j:{}}}},B=rn(s),L=rn(E),I=po(s),R=po(E);if(B!==L||I!==R){u(E);return}s=E,o.updateConfig(s),a.update(w),l()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,E,B){if(E==="host")return o.host;if(E in w)return Reflect.get(w,E,B);let L=a[E];return typeof L=="function"?L.bind(a):L}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Om=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Gh=new Set(["button","a","input","select","textarea","details","summary"]),Xh=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),$l=/\b(product|card|item|listing|result)\b/i,jl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Qh=3e3,Yh=100;function $m(e){let t=typeof e.className=="string"?e.className:"";if($l.test(t)||e.id&&$l.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&$l.test(r.value))return!0}return!1}function _m(e){var t;return jl.test(((t=e.textContent)!=null?t:"").trim())}function jm(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 Bm(e){let t=e.match(jl);return t?t[0]:null}function Dm(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 ey(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 ty="commerce-card",ny="result-card";function Nm(e){return!$m(e)||!_m(e)||!jm(e)&&!Zh(e)?0:5200}function Fm(e){var r;return!$m(e)||_m(e)||!jm(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 Ul=[{id:ty,scoreElement(e){return Nm(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||jl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Nm(e)===0)return null;let{title:n,href:r}=Dm(e),s=(p=(l=Bm(((d=e.textContent)!=null?d:"").trim()))!=null?l:Bm(t.text))!=null?p:"",o=ey(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:ny,scoreElement(e){return Fm(e)},formatSummary(e,t){if(Fm(e)===0)return null;let{title:n,href:r}=Dm(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
- `)}}];function ry(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function oy(e){var p,m,g,u,v,x,w,E,B,L,I,R,S;let t=(p=e.options)!=null?p:{},n=(g=(m=t.maxElements)!=null?m:e.maxElements)!=null?g:80,r=(v=(u=t.excludeSelector)!=null?u:e.excludeSelector)!=null?v:".persona-host",s=(w=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?w:200,o=(B=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?B:!0,a=(L=t.root)!=null?L:e.root,i=(I=t.mode)!=null?I:"structured",d=(R=t.maxCandidates)!=null?R:Math.max(500,n*10),l=(S=e.rules)!=null?S:Ul;return i==="simple"&&e.rules&&e.rules.length>0?(ry(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function _l(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var sy=["data-testid","data-product","data-action","data-id","data-name","data-type"];function ay(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"||Gh.has(t)||n&&Xh.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Um(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 iy(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 p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function ql(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${_l(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of sy){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${_l(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=>_l(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 ly(e){return e==="static"?Yh:Qh}function qm(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:ql(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:ay(e),attributes:iy(e)}}function cy(e,t,n,r){let s=ly(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 dy(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 py(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,p=l.tagName.toLowerCase();if(Om.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Um(l)){i=a.nextNode();continue}let m=qm(l,e.maxTextLength),g=m.text.length>0,u=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(w=>w==="role");if(!g&&!u){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:v,formattingRule:x}=cy(l,m,e.rules,n);s.push({el:l,domIndex:o,enriched:m,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;dy(d,l)||d.push(l)}return d.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:m===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let u=l.formattingRule.formatSummary(l.el,l.enriched,n);u&&(p=u)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function uy(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(Om.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Um(d)){o=s.nextNode();continue}let p=qm(d,e.maxTextLength),m=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(u=>u==="role");if(!m&&!g){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}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 zm(e={}){var r;let t=oy(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?uy(t,n):py(t,n):[]}var _i=100;function Vm(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 ft="max-height: -moz-available !important; max-height: stretch !important;",lt=g?"":"padding-top: 1.25em !important;",Mt=g?"":`z-index: ${(pn=(fn=r.launcher)==null?void 0:fn.zIndex)!=null?pn:wn} !important;`;me.style.cssText+=ft+lt+Mt}Ye()};hr(),uo(e,r),Wi(e,r),Ri(e,r);let xt=[];xt.push(()=>{document.removeEventListener("keydown",Qr)});let Qt=null,Yt=null;xt.push(()=>{Qt==null||Qt(),Qt=null,Yt==null||Yt(),Yt=null}),Fn&&xt.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),xt.push(()=>{Tn==null||Tn(),Tn=null,Hr(),Dt&&(Dt.remove(),Dt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),He&&xt.push(()=>{Se!==null&&(cancelAnimationFrame(Se),Se=null),le==null||le.destroy(),le=null,V==null||V.destroy(),V=null,J=null});let qn=null,eo=()=>{qn&&(qn(),qn=null),r.colorScheme==="auto"&&(qn=ai(()=>{uo(e,r)}))};eo(),xt.push(()=>{qn&&(qn(),qn=null)});let sr=(jc=r.features)==null?void 0:jc.streamAnimation;if(sr!=null&&sr.type&&sr.type!=="none"){let c=oa(sr.type,sr.plugins);c&&(pl(c,e),xt.push(()=>qu(e)))}let br=bm(Ht),zn=null,_,ar=!1,ye=Bu(),Vn=new Map,ir=new Map,yr=new Map,Ts=0,xr=ci(),vr=0,wr=null,Br=!1,Ao=!1,va=4,Es=24,wa=80,Xo=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ms=(qc=(Uc=r.voiceRecognition)==null?void 0:Uc.autoResume)!=null?qc:!1,lr=c=>{o.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},Wn=()=>{m(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Ca=()=>{var y,E;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Dl(d.voiceState),g=!!c.active,b=Number((E=c.timestamp)!=null?E:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<Kh&&setTimeout(()=>{var N,O;yt.active||(yt.manuallyDeactivated=!1,((O=(N=r.voiceRecognition)==null?void 0:N.provider)==null?void 0:O.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("restore"),_.isVoiceActive()&&M()}):Mo("restore"))},1e3)},Aa=()=>_?Dm(_.getMessages()).filter(c=>!c.__skipPersist):[];function Qo(c){if(!(i!=null&&i.save))return;let b={messages:c?Dm(c):_?Aa():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let y=i.save(b);y instanceof Promise&&y.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Dr=null,Sa=()=>me.querySelector("#persona-scroll-container")||X,So=()=>{Dr!==null&&(cancelAnimationFrame(Dr),Dr=null),Br=!1},ks=()=>{wr!==null&&(cancelAnimationFrame(wr),wr=null),Ao=!1,So()},Nr=()=>{if(!Cn()||ae){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==fe&&fe.appendChild(Wt),At();let c=ea(X)>0;Wt.style.display=xr.isFollowing()||!c?"none":""},Ls=()=>{xr.pause()&&(ks(),Nr())},to=()=>{xr.resume(),Nr()},no=(c=!1)=>{xr.isFollowing()&&(!c&&!ar||(wr!==null&&(cancelAnimationFrame(wr),wr=null),Ao=!0,wr=requestAnimationFrame(()=>{wr=null,Ao=!1,xr.isFollowing()&&Ta(Sa(),c?220:140)})))},Ta=(c,g=500)=>{let b=c.scrollTop,y=ea(c),E=y-b;if(Math.abs(E)<1){vr=c.scrollTop;return}if(Math.abs(E)>=wa){So(),Br=!0,c.scrollTop=y,vr=c.scrollTop,Br=!1;return}So();let N=performance.now();Br=!0;let O=H=>1-Math.pow(1-H,3),U=H=>{if(!xr.isFollowing()){So();return}let Te=ea(c);Te!==y&&(y=Te,E=y-b);let ge=H-N,ee=Math.min(ge/g,1),Ae=O(ee),Me=b+E*Ae;c.scrollTop=Me,vr=c.scrollTop,ee<1?Dr=requestAnimationFrame(U):(c.scrollTop=y,vr=c.scrollTop,Dr=null,Br=!1)};Dr=requestAnimationFrame(U)},Ea=c=>{let g=new Map;c.forEach(b=>{let y=Xo.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}))}),Xo.clear(),g.forEach((b,y)=>{Xo.set(y,b)})},To=(c,g,b)=>{var pt,Ie,Le,qe,Ye,vt;let y=document.createElement("div"),N=(()=>{var Oe;let L=s.find(te=>te.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((Oe=r.loadingIndicator)!=null&&Oe.render)return r.loadingIndicator.render})(),O=(L,Oe)=>Oe==null?!1:typeof Oe=="string"?(L.textContent=Oe,!0):(L.appendChild(Oe),!0),U=new Set,H=new Set,Te=s.some(L=>L.renderAskUserQuestion),ge=[],ee=[],Ae=r.enableComponentStreaming!==!1,Me=s.some(L=>L.renderApproval)&&r.approval!==!1,je=[];if(g.forEach(L=>{var Ct,Gn,sn,pr,Xn,ko,os,ss,Xt,Lo,lo,co,$r,Po;U.add(L.id);let Oe=Te&&zr(L),te=Me&&L.variant==="approval"&&!!L.approval,nt=!Oe&&L.role==="assistant"&&!L.variant&&Ae&&Ni(L);if(!te&&yr.has(L.id)){let rt=c.querySelector(`#wrapper-${L.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),yr.delete(L.id)}if(!nt&&ir.has(L.id)){let rt=c.querySelector(`#wrapper-${L.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),ir.delete(L.id)}let Ft=zr(L)?`:${(Ct=L.agentMetadata)!=null&&Ct.askUserQuestionAnswered?"a":"u"}:${(Gn=L.agentMetadata)!=null&&Gn.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Hu(L,Ts)+Ft,zt=Oe||te||nt?null:Du(ye,L.id,Ot);if(zt){y.appendChild(zt.cloneNode(!0)),zr(L)&&((sn=L.toolCall)!=null&&sn.id)&&((pr=L.agentMetadata)==null?void 0:pr.awaitingLocalTool)===!0&&!((Xn=L.agentMetadata)!=null&&Xn.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ws(L,r,We.composerOverlay));return}let it=null,dn=s.find(rt=>!!(L.variant==="reasoning"&&rt.renderReasoning||L.variant==="tool"&&rt.renderToolCall||!L.variant&&rt.renderMessage)),Jn=(ko=r.layout)==null?void 0:ko.messages;if(zr(L)&&((os=L.agentMetadata)==null?void 0:os.askUserQuestionAnswered)===!0){Vn.delete(L.id);let rt=c.querySelector(`#wrapper-${L.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(zr(L)&&((Xt=(ss=r.features)==null?void 0:ss.askUserQuestion)==null?void 0:Xt.enabled)!==!1){let rt=s.find(yn=>typeof yn.renderAskUserQuestion=="function");if(rt&&Lt.current){let yn=Vn.get(L.id),fn=yn!==Ot,pn=null;if(fn){let{payload:Mt,complete:Rn}=Vr(L),tn=L.id,Lr=()=>{var an;return(an=Lt.current)==null?void 0:an.getMessages().find(Mn=>Mn.id===tn)};pn=rt.renderAskUserQuestion({message:L,payload:Mt,complete:Rn,resolve:an=>{var ur;let Mn=Lr();Mn&&((ur=Lt.current)==null||ur.resolveAskUserQuestion(Mn,an))},dismiss:()=>{var Mn,ur,Io;let an=Lr();(Mn=an==null?void 0:an.agentMetadata)!=null&&Mn.awaitingLocalTool&&((ur=Lt.current)==null||ur.markAskUserQuestionResolved(an),(Io=Lt.current)==null||Io.resolveAskUserQuestion(an,"(dismissed)"))},config:r})}let ft=yn!=null;if(fn&&pn===null&&!ft){((Lo=L.agentMetadata)==null?void 0:Lo.awaitingLocalTool)===!0&&!((lo=L.agentMetadata)!=null&&lo.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ws(L,r,We.composerOverlay));return}let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${L.id}`,lt.setAttribute("data-wrapper-id",L.id),lt.setAttribute("data-ask-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),y.appendChild(lt),ge.push({messageId:L.id,fingerprint:Ot,bubble:pn});return}else{((co=L.agentMetadata)==null?void 0:co.awaitingLocalTool)===!0&&!(($r=L.agentMetadata)!=null&&$r.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ws(L,r,We.composerOverlay));return}}else if(te){let rt=s.find(ft=>typeof ft.renderApproval=="function"),fn=yr.get(L.id)!==Ot,pn=null;if(fn&&(rt!=null&&rt.renderApproval)){let ft=L.id,lt=(Mt,Rn)=>{var Lr,an,Mn;let tn=(Lr=Lt.current)==null?void 0:Lr.getMessages().find(ur=>ur.id===ft);tn!=null&&tn.approval&&(tn.approval.toolType==="webmcp"?(an=Lt.current)==null||an.resolveWebMcpApproval(tn.id,Mt):(Mn=Lt.current)==null||Mn.resolveApproval(tn.approval,Mt,Rn))};pn=rt.renderApproval({message:L,defaultRenderer:()=>Pi(L,r),config:r,approve:Mt=>lt("approved",Mt),deny:Mt=>lt("denied",Mt)})}if(fn&&pn===null){let ft=c.querySelector(`#wrapper-${L.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),yr.delete(L.id),it=Pi(L,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${L.id}`,ft.setAttribute("data-wrapper-id",L.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),je.push({messageId:L.id,fingerprint:Ot,bubble:pn});return}}else if(dn)if(L.variant==="reasoning"&&L.reasoning&&dn.renderReasoning){if(!Ge)return;it=dn.renderReasoning({message:L,defaultRenderer:()=>wl(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&dn.renderToolCall){if(!Ce)return;it=dn.renderToolCall({message:L,defaultRenderer:()=>Cl(L,r),config:r})}else dn.renderMessage&&(it=dn.renderMessage({message:L,defaultRenderer:()=>{let rt=hs(L,b,Jn,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r});return L.role!=="user"&&Rl(rt,L,r,_),rt},config:r}));if(!it&&nt){let rt=Oi(L);if(rt){let yn=ir.get(L.id),fn=yn!==Ot,pn=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(fn){let lt=Di(rt,{config:r,message:L,transform:b});if(lt)if(pn){let Mt=document.createElement("div");if(Mt.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(" "),Mt.id=`bubble-${L.id}`,Mt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Rn=document.createElement("div");Rn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Rn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Rn)}Mt.appendChild(lt),ft=Mt}else{let Mt=document.createElement("div");if(Mt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Mt.id=`bubble-${L.id}`,Mt.setAttribute("data-message-id",L.id),Mt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Rn=document.createElement("div");Rn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Rn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Rn)}Mt.appendChild(lt),ft=Mt}}if(ft||yn!=null){let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${L.id}`,lt.setAttribute("data-wrapper-id",L.id),lt.setAttribute("data-component-directive-stub","true"),lt.setAttribute("data-preserve-runtime","true"),pn||lt.classList.add("persona-w-full"),y.appendChild(lt),ee.push({messageId:L.id,fingerprint:Ot,bubble:ft});return}}}if(!it)if(L.variant==="reasoning"&&L.reasoning){if(!Ge)return;it=wl(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!Ce)return;it=Cl(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;it=Pi(L,r)}else{let rt=(Po=r.layout)==null?void 0:Po.messages;rt!=null&&rt.renderUserMessage&&L.role==="user"?it=rt.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):rt!=null&&rt.renderAssistantMessage&&L.role==="assistant"?it=rt.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):it=hs(L,b,rt,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r}),L.role!=="user"&&it&&Rl(it,L,r,_)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${L.id}`,Ke.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Ke.classList.add("persona-justify-end"),(it==null?void 0:it.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(it),Nu(ye,L.id,Ot,Ke),y.appendChild(Ke)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let te=Oe.getAttribute("data-persona-ask-sheet-for");te&&!H.has(te)&&xo(We.composerOverlay,te)}),(Ie=(pt=r.features)==null?void 0:pt.toolCallDisplay)!=null&&Ie.grouped){let L=[],Oe=[];g.forEach(te=>{if(te.variant==="tool"&&te.toolCall&&Ce){Oe.push(te);return}Oe.length>1&&L.push(Oe),Oe=[]}),Oe.length>1&&L.push(Oe),L.forEach((te,nt)=>{var Ct,Gn;let Ft=te.map(sn=>Array.from(y.children).find(pr=>pr instanceof HTMLElement&&pr.getAttribute("data-wrapper-id")===sn.id)).filter(sn=>!!sn);if(Ft.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${nt}-${te[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${nt}-${te[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.setAttribute("data-persona-tool-group","true");let it=document.createElement("div");it.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${te.length} tools`,Jn=(Gn=(Ct=r.toolCall)==null?void 0:Ct.renderGroupedSummary)==null?void 0:Gn.call(Ct,{messages:te,toolCalls:te.map(sn=>sn.toolCall).filter(sn=>!!sn),defaultSummary:dn,config:r});O(it,Jn)||(it.textContent=dn);let Ke=document.createElement("div");Ke.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(it,Ke),Ot.appendChild(zt),Ft[0].before(Ot),Ft.forEach((sn,pr)=>{let Xn=document.createElement("div");Xn.className="persona-tool-group-item persona-relative",Xn.setAttribute("data-persona-tool-group-item","true"),pr<Ft.length-1&&Xn.setAttribute("data-persona-tool-group-connector","true"),Xn.appendChild(sn),Ke.appendChild(Xn)})})}Ou(ye,U);let st=g.some(L=>L.role==="assistant"&&L.streaming),Ve=g[g.length-1],gt=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(ar&&g.some(L=>L.role==="user")&&!st&&!gt){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:qo},Oe=s.find(nt=>nt.renderLoadingIndicator),te=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(te=Oe.renderLoadingIndicator(L)),te===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(te=r.loadingIndicator.render(L)),te===null&&(te=qo()),te){let nt=document.createElement("div"),Ft=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;nt.className=Ft?["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(" "),nt.setAttribute("data-typing-indicator","true"),nt.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",nt.appendChild(te);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(nt),y.appendChild(Ot)}}if(!ar&&g.length>0){let L=g[g.length-1],Oe={config:r,lastMessage:L,messageCount:g.length},te=s.find(Ft=>Ft.renderIdleIndicator),nt=null;if(te!=null&&te.renderIdleIndicator&&(nt=te.renderIdleIndicator(Oe)),nt===null&&((Ye=r.loadingIndicator)!=null&&Ye.renderIdle)&&(nt=r.loadingIndicator.renderIdle(Oe)),nt){let Ft=document.createElement("div"),Ot=((vt=r.loadingIndicator)==null?void 0:vt.showBubble)!==!1;Ft.className=Ot?["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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(nt);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Ft),y.appendChild(zt)}}if(ii(c,y),ge.length>0)for(let{messageId:L,fingerprint:Oe,bubble:te}of ge){let nt=c.querySelector(`#wrapper-${L}`);nt&&te!==null&&(nt.replaceChildren(te),nt.setAttribute("data-bubble-fp",Oe),Vn.set(L,Oe))}if(Vn.size>0)for(let L of Vn.keys())U.has(L)||Vn.delete(L);if(ee.length>0)for(let{messageId:L,fingerprint:Oe,bubble:te}of ee){let nt=c.querySelector(`#wrapper-${L}`);nt&&te!==null&&(nt.replaceChildren(te),nt.setAttribute("data-bubble-fp",Oe),ir.set(L,Oe))}if(ir.size>0)for(let L of ir.keys())U.has(L)||ir.delete(L);if(je.length>0)for(let{messageId:L,fingerprint:Oe,bubble:te}of je){let nt=c.querySelector(`#wrapper-${L}`);nt&&te!==null&&(nt.replaceChildren(te),nt.setAttribute("data-bubble-fp",Oe),yr.set(L,Oe))}if(yr.size>0)for(let L of yr.keys())U.has(L)||yr.delete(L)},ro=null,Ma=()=>{var b;if(ro)return;let c=y=>{let E=y.composedPath();E.includes(me)||Ze&&E.includes(Ze)||Nt(!1,"user")};ro=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Ps=()=>{var g;if(!ro)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",ro,!0),ro=null};xt.push(()=>Ps());let oo=null,ka=()=>{var b;if(oo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Nt(!1,"user"))};oo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Is=()=>{var g;if(!oo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",oo,!0),oo=null};xt.push(()=>Is());let so=!1,Ws=new Set,La=()=>{var g,b,y,E;let c=(y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:y.streamAnimation;return c||((E=r.features)==null?void 0:E.streamAnimation)},Or=()=>{var gt,pt,Ie,Le;if(!$())return;let c=We.peekBanner,g=We.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let b=(gt=_==null?void 0:_.getMessages())!=null?gt:[],y;for(let qe=b.length-1;qe>=0;qe--){let Ye=b[qe];if(Ye.role==="assistant"&&Ye.content){y=Ye;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let E=y.content,N=!!y.streaming,O=La(),U=ui(O),H=U.type!=="none"?oa(U.type,O==null?void 0:O.plugins):null,Te=((pt=H==null?void 0:H.isAnimating)==null?void 0:pt.call(H,y))===!0,ge=H!==null&&(N||Te);ge&&H&&!Ws.has(H.name)&&(pl(H,e),Ws.add(H.name));let ee=ge&&(H!=null&&H.containerClass)?H.containerClass:null,Ae=(Ie=g.dataset.personaPeekStreamClass)!=null?Ie:null;Ae&&Ae!==ee&&(g.classList.remove(Ae),delete g.dataset.personaPeekStreamClass),ee&&Ae!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),ge?(g.style.setProperty("--persona-stream-step",`${U.speed}ms`),g.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Me=ge?mi(E,U.buffer,H,y,N):E;if(ge&&U.placeholder==="skeleton"&&N&&(!Me||!Me.trim())){let qe=document.createElement("div"),Ye=aa();Ye.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ye),ii(g,qe)}else{let qe=Math.max(0,Me.length-100),Ye=Me.length>100?Me.slice(-100):Me,vt=Do(Ye);if(!ge||!H){let L=Me.length>100?`\u2026${Ye}`:Ye;g.textContent!==L&&(g.textContent=L)}else{let L=vt;(H.wrap==="char"||H.wrap==="word")&&(L=sa(vt,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:qe}));let Oe=document.createElement("div");if(Oe.innerHTML=L,H.useCaret&&Ye.length>0){let te=gi(),nt=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=nt[nt.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(te,Ft.nextSibling):Oe.appendChild(te)}ii(g,Oe),(Le=H.onAfterRender)==null||Le.call(H,{container:g,bubble:c,messageId:y.id,message:y,speed:U.speed,duration:U.duration})}}let Ve=ar||so;c.classList.toggle("persona-pill-peek--visible",Ve)};if($()){let c=We.peekBanner;if(c){let y=E=>{E.preventDefault(),E.stopPropagation(),Nt(!0,"user")};c.addEventListener("pointerdown",y),xt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{so||(so=!0,Or())},b=()=>{so&&(so=!1,Or())};oe.addEventListener("pointerenter",g),oe.addEventListener("pointerleave",b),xt.push(()=>{oe.removeEventListener("pointerenter",g),oe.removeEventListener("pointerleave",b)}),Ze&&(Ze.addEventListener("pointerenter",g),Ze.addEventListener("pointerleave",b),xt.push(()=>{Ze.removeEventListener("pointerenter",g),Ze.removeEventListener("pointerleave",b)}))}let Pa=c=>{var Ae,Me,je,st,Ve,gt,pt,Ie;let g=(Me=(Ae=r.launcher)==null?void 0:Ae.composerBar)!=null?Me:{},b=(je=g.expandedSize)!=null?je:"anchored",y=(st=g.bottomOffset)!=null?st:"16px",E=g.collapsedMaxWidth,N=(Ve=g.expandedMaxWidth)!=null?Ve:"880px",O=(gt=g.expandedTopOffset)!=null?gt:"5vh",U=(pt=g.modalMaxWidth)!=null?pt:"880px",H=(Ie=g.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",Te="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ee=me.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ze){let Le=Ze.style;Le.bottom=y,Le.width=E!=null?E:""}if(c&&b!=="fullscreen"){if(b==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=U,ee.maxWidth=Te,ee.maxHeight=H,ee.height=H;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ge})`,ee.top=O,ee.width=N,ee.maxWidth=Te}},ao=()=>{var H,Te,ge,ee,Ae,Me,je,st;if(!D())return;if($()){let gt=(ge=((Te=(H=r.launcher)==null?void 0:H.composerBar)!=null?Te:{}).expandedSize)!=null?ge:"anchored",pt=R?"expanded":"collapsed";me.dataset.state=pt,me.dataset.expandedSize=gt,Ze&&(Ze.dataset.state=pt,Ze.dataset.expandedSize=gt),me.style.removeProperty("display"),me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pa(R),fe.style.display=R?"flex":"none",hr(),R?(Ma(),ka()):(Ps(),Is()),Or();return}let c=ln(r),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,b=(Me=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?Me:640,y=(st=(je=r.launcher)==null?void 0:je.mobileFullscreen)!=null?st:!0,E=g.innerWidth<=b,N=y&&E&&T,O=mr(r).reveal;R?(me.style.removeProperty("display"),me.style.display=c?"flex":"",me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0"),oe.classList.add("persona-scale-100","persona-opacity-100"),Qe?Qe.element.style.display="none":tt&&(tt.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!N?(me.style.removeProperty("display"),me.style.display="flex",me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(me.style.setProperty("display","none","important"),me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(me.style.display="",me.classList.add("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100"),oe.classList.add("persona-scale-95","persona-opacity-0")),Qe?Qe.element.style.display=c?"none":"":tt&&(tt.style.display=c?"none":""))},Nt=(c,g="user")=>{var N,O;if(!D()||R===c)return;let b=R;R=c,ao();let y=(()=>{var je,st,Ve,gt,pt,Ie,Le,qe,Ye,vt;let U=(st=(je=r.launcher)==null?void 0:je.sidebarMode)!=null?st:!1,H=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,Te=(pt=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?pt:!0,ge=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,ee=H.innerWidth<=ge,Ae=ln(r)&&Te&&ee,Me=$()&&((vt=(Ye=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ye.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return U||Te&&ee&&T||Ae||Me})();if(R&&y){if(!Qt){let U=e.getRootNode(),H=U instanceof ShadowRoot?U.host:e.closest(".persona-host");H&&(Qt=ul(H,(O=(N=r.launcher)==null?void 0:N.zIndex)!=null?O:wn))}Yt||(Yt=ml(e.ownerDocument))}else R||(Qt==null||Qt(),Qt=null,Yt==null||Yt(),Yt=null);R&&(Zt(),no(!0));let E={open:R,source:g,timestamp:Date.now()};R&&!b?o.emit("widget:opened",E):!R&&b&&o.emit("widget:closed",E),o.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:yt.active,streaming:_.isStreaming()})},Yo=c=>{Kt(c?"stop":"send"),z&&(z.disabled=c),br.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)})},Zo=()=>{yt.active||he&&he.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Zo(),200)});let Rs=()=>{var b,y,E,N,O,U,H,Te,ge,ee,Ae;Bn.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",er.textContent=(N=(E=r.copy)==null?void 0:E.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",he.placeholder=(U=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?U:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let Me=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=Me?"":"none",Me?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((ge=(Te=r.sendButton)==null?void 0:Te.useIcon)!=null&&ge)&&!(_!=null&&_.isStreaming())&&(pe.textContent=(Ae=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?Ae:"Send"),he.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',he.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 kr=null,Ia=()=>{kr==null&&(kr=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(kr),kr=null;return}let g=Date.now();c.forEach(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=_a(g-y))})},100))};if(_=new ds(r,{onMessagesChanged(c){To($e,c,Re),Ia(),_&&(c.some(E=>E.role==="user")?br.render([],_,he,c):br.render(r.suggestionChips,_,he,c,r.suggestionChipsConfig)),no(!ar),Ea(c);let g=[...c].reverse().find(y=>y.role==="user"),b=yt.lastUserMessageId;g&&g.id!==b&&(yt.lastUserMessageId=g.id,o.emit("user:message",g)),yt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Qo(c),Or()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};xe(gn,(E=>{var N,O,U,H;return E==="idle"?(N=g.idleText)!=null?N:vn.idle:E==="connecting"?(O=g.connectingText)!=null?O:vn.connecting:E==="connected"?(U=g.connectedText)!=null?U:vn.connected:E==="error"?(H=g.errorText)!=null?H:vn.error:vn[E]})(c),g,c)},onStreamingChanged(c){ar=c,Yo(c),_&&To($e,_.getMessages(),Re),c||no(!0),Or()},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(),ie();break;default:c==="idle"&&_.isBargeInActive()?(G(),M(),z==null||z.setAttribute("aria-label","End voice session")):(yt.active=!1,G(),lr("system"),Wn());break}},onArtifactsState(c){$n=c,Un(),Qo()}}),Lt.current=_,((Vc=(zc=r.voiceRecognition)==null?void 0:zc.provider)==null?void 0:Vc.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(V||r.onSSEEvent)&&_.setSSEEventCallback((c,g)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,g),de==null||de.processEvent(c,g),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,b,y;c&&(c.metadata&&(d=Dl(c.metadata),w.syncFromMetadata()),(g=c.messages)!=null&&g.length&&_.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&_.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Hs=()=>{var g,b,y;!$()||R||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||Nt(!0,"auto")},Bs=c=>{var E;if(c.preventDefault(),_.isStreaming()){_.cancel(),de==null||de.reset(),le==null||le.update();return}let g=he.value.trim(),b=(E=ot==null?void 0:ot.hasAttachments())!=null?E:!1;if(!g&&!b)return;Hs();let y;b&&(y=[],y.push(...ot.getContentParts()),g&&y.push(Js(g))),he.value="",he.style.height="auto",Eo(),_.sendMessage(g,{contentParts:y}),b&&ot.clearAttachments()},Wa=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},es={...li},ts=!1,Eo=()=>{es={...li}},Ra=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Ha=c=>{if(!he)return;ts=!0,he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),ts=!1;let g=he.value.length;he.setSelectionRange(g,g)},Ds=()=>{ts||Eo()},Ns=c=>{if(he){if(Wa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=he.selectionStart===0&&he.selectionEnd===0,b=Ru({direction:c.key==="ArrowUp"?"up":"down",history:Ra(),currentValue:he.value,atStart:g,state:es});if(es=b.state,b.handled){c.preventDefault(),b.value!==void 0&&Ha(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}Eo(),c.preventDefault(),pe.click()}}},Os=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(fe)&&(_.cancel(),de==null||de.reset(),le==null||le.update(),Eo(),c.preventDefault(),c.stopImmediatePropagation())},Fs=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!ot)return;let g=Gh(c.clipboardData);g.length!==0&&(c.preventDefault(),await ot.handleFiles(g))},En=null,Kn=!1,Fr=null,ct=null,$s=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Mo=(c="user")=>{var N,O,U,H,Te,ge,ee;if(Kn||_.isStreaming())return;let g=$s();if(!g)return;En=new g;let y=(O=((N=r.voiceRecognition)!=null?N:{}).pauseDuration)!=null?O:2e3;En.continuous=!0,En.interimResults=!0,En.lang="en-US";let E=he.value;En.onresult=Ae=>{let Me="",je="";for(let Ve=0;Ve<Ae.results.length;Ve++){let gt=Ae.results[Ve],pt=gt[0].transcript;gt.isFinal?Me+=pt+" ":je=pt}let st=E+Me+je;he.value=st,Fr&&clearTimeout(Fr),(Me||je)&&(Fr=window.setTimeout(()=>{let Ve=he.value.trim();Ve&&En&&Kn&&(Cr(),he.value="",he.style.height="auto",_.sendMessage(Ve,{viaVoice:!0}))},y))},En.onerror=Ae=>{Ae.error!=="no-speech"&&Cr()},En.onend=()=>{if(Kn){let Ae=he.value.trim();Ae&&Ae!==E.trim()&&(he.value="",he.style.height="auto",_.sendMessage(Ae,{viaVoice:!0})),Cr()}};try{if(En.start(),Kn=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),lr(c),Wn(),z){let Ae=(U=r.voiceRecognition)!=null?U:{};ct={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(H=Ae.iconName)!=null?H:"mic",iconSize:parseFloat((ee=(ge=Ae.iconSize)!=null?ge:(Te=r.sendButton)==null?void 0:Te.size)!=null?ee:"40")||24};let Me=Ae.recordingBackgroundColor,je=Ae.recordingIconColor,st=Ae.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=je!=null?je:"var(--persona-voice-recording-indicator, #ffffff)",je){let Ve=z.querySelector("svg");Ve&&Ve.setAttribute("stroke",je)}st&&(z.style.borderColor=st),z.setAttribute("aria-label","Stop voice recognition")}}catch{Cr("system")}},Cr=(c="user")=>{if(Kn){if(Kn=!1,Fr&&(clearTimeout(Fr),Fr=null),En){try{En.stop()}catch{}En=null}if(yt.active=!1,lr(c),Wn(),z){if(z.classList.remove("persona-voice-recording"),ct){z.style.backgroundColor=ct.backgroundColor,z.style.color=ct.color,z.style.borderColor=ct.borderColor;let g=z.querySelector("svg");g&&g.setAttribute("stroke",ct.color||"currentColor"),ct=null}z.setAttribute("aria-label","Start voice recognition")}}},ns=(c,g)=>{var gt,pt,Ie,Le,qe,Ye,vt,L;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((gt=c==null?void 0:c.provider)==null?void 0:gt.type)==="runtype";if(!(b||y))return null;let N=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let U=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",H=(Ie=g==null?void 0:g.size)!=null?Ie:"40px",Te=(Le=c==null?void 0:c.iconSize)!=null?Le:H,ge=parseFloat(Te)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,Ae=(Ye=c==null?void 0:c.iconColor)!=null?Ye:g==null?void 0:g.textColor;O.style.width=Te,O.style.height=Te,O.style.minWidth=Te,O.style.minHeight=Te,O.style.fontSize="18px",O.style.lineHeight="1",Ae?O.style.color=Ae:O.style.color="var(--persona-text, #111827)";let je=we(U,ge,Ae||"currentColor",1.5);je?O.appendChild(je):O.textContent="\u{1F3A4}",ee?O.style.backgroundColor=ee:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),N.appendChild(O);let st=(vt=c==null?void 0:c.tooltipText)!=null?vt:"Start voice recognition";if(((L=c==null?void 0:c.showTooltip)!=null?L:!1)&&st){let Oe=h("div","persona-send-button-tooltip");Oe.textContent=st,N.appendChild(Oe)}return{micButton:O,micButtonWrapper:N}},Je=()=>{var g,b,y,E,N;if(!z||ct)return;let c=(g=r.voiceRecognition)!=null?g:{};ct={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((N=(E=c.iconSize)!=null?E:(y=r.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},A=(c,g)=>{var N,O,U,H,Te;if(!z)return;let b=z.querySelector("svg");b&&b.remove();let y=(Te=ct==null?void 0:ct.iconSize)!=null?Te:parseFloat((H=(U=(N=r.voiceRecognition)==null?void 0:N.iconSize)!=null?U:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,E=we(c,y,g,1.5);E&&z.appendChild(E)},j=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},M=()=>{var E;if(!z)return;Je();let c=(E=r.voiceRecognition)!=null?E:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,y=c.recordingBorderColor;if(j(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let N=z.querySelector("svg");N&&N.setAttribute("stroke",b)}y&&(z.style.borderColor=y),z.setAttribute("aria-label","Stop voice recognition")},Z=()=>{var U,H,Te,ge,ee,Ae,Me,je;if(!z)return;Je();let c=(U=r.voiceRecognition)!=null?U:{},g=_.getVoiceInterruptionMode(),b=(H=c.processingIconName)!=null?H:"loader",y=(ge=(Te=c.processingIconColor)!=null?Te:ct==null?void 0:ct.color)!=null?ge:"",E=(Ae=(ee=c.processingBackgroundColor)!=null?ee:ct==null?void 0:ct.backgroundColor)!=null?Ae:"",N=(je=(Me=c.processingBorderColor)!=null?Me:ct==null?void 0:ct.borderColor)!=null?je:"";j(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=E,z.style.borderColor=N;let O=y||"currentColor";z.style.color=O,A(b,O),z.setAttribute("aria-label","Processing voice input"),g==="none"&&(z.style.cursor="default")},ie=()=>{var Te,ge,ee,Ae,Me,je,st,Ve,gt,pt,Ie,Le;if(!z)return;Je();let c=(Te=r.voiceRecognition)!=null?Te:{},g=_.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:b,E=(je=c.speakingIconColor)!=null?je:g==="barge-in"?(Ae=(ee=c.recordingIconColor)!=null?ee:ct==null?void 0:ct.color)!=null?Ae:"":(Me=ct==null?void 0:ct.color)!=null?Me:"",N=(gt=c.speakingBackgroundColor)!=null?gt:g==="barge-in"?(st=c.recordingBackgroundColor)!=null?st:"var(--persona-voice-recording-bg, #ef4444)":(Ve=ct==null?void 0:ct.backgroundColor)!=null?Ve:"",O=(Le=c.speakingBorderColor)!=null?Le:g==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(Ie=ct==null?void 0:ct.borderColor)!=null?Ie:"";j(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=N,z.style.borderColor=O;let U=E||"currentColor";z.style.color=U,A(y,U);let H=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",H),g==="none"&&(z.style.cursor="default"),g==="barge-in"&&z.classList.add("persona-voice-recording")},G=()=>{var c,g,b;z&&(j(),ct&&(z.style.backgroundColor=(c=ct.backgroundColor)!=null?c:"",z.style.color=(g=ct.color)!=null?g:"",z.style.borderColor=(b=ct.borderColor)!=null?b:"",A(ct.iconName,ct.color||"currentColor"),ct=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},ke=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=_.getVoiceStatus(),y=_.getVoiceInterruptionMode();if(y==="none"&&(b==="processing"||b==="speaking"))return;if(y==="cancel"&&(b==="processing"||b==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Wn(),lr("user"),G()});return}_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),yt.manuallyDeactivated=!_.isVoiceActive(),Wn(),lr("user"),_.isVoiceActive()?M():G()});return}if(Kn){let b=he.value.trim();yt.manuallyDeactivated=!0,Wn(),Cr("user"),b&&(he.value="",he.style.height="auto",_.sendMessage(b))}else yt.manuallyDeactivated=!1,Wn(),Mo("user")};Dn=ke,z&&(z.addEventListener("click",ke),xt.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),G()):Cr("system"),z&&z.removeEventListener("click",ke)}));let Fe=o.on("assistant:complete",()=>{Ms&&(yt.active||yt.manuallyDeactivated||Ms==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!yt.active&&!yt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("auto"),_.isVoiceActive()&&M()}):Mo("auto"))},600))});xt.push(Fe);let dt=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});xt.push(dt);let Xe=()=>{Nt(!R,"user")},Qe=null,tt=null;if(T&&!$()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>la(r,Xe).element,onToggle:Xe});g&&(tt=g)}tt||(Qe=la(r,Xe))}Qe?e.appendChild(Qe.element):tt&&e.appendChild(tt),ao(),br.render(r.suggestionChips,_,he,void 0,r.suggestionChipsConfig),Rs(),Yo(_.isStreaming()),no(!0),Ca(),k&&(!T||$()?setTimeout(()=>Zo(),0):R&&setTimeout(()=>Zo(),200));let Zt=()=>{var H,Te,ge,ee,Ae,Me,je,st,Ve,gt,pt,Ie,Le,qe,Ye,vt,L,Oe,te,nt,Ft,Ot;if($()){At(),ao();return}let c=ln(r),g=(Te=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?Te:!1,b=c||g||((ee=(ge=r.launcher)==null?void 0:ge.fullHeight)!=null?ee:!1),y=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,E=(je=(Me=r.launcher)==null?void 0:Me.mobileFullscreen)!=null?je:!0,N=(Ve=(st=r.launcher)==null?void 0:st.mobileBreakpoint)!=null?Ve:640,O=y.innerWidth<=N,U=E&&O&&T;try{if(U){hr(),uo(e,r);return}if(I&&(I=!1,hr(),uo(e,r)),!T&&!c){oe.style.height="",oe.style.width="";return}if(!g&&!c){let zt=(pt=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?pt:r==null?void 0:r.launcherWidth,it=zt!=null?zt:Yn;oe.style.width=it,oe.style.maxWidth=it}if(Mr(),!b){let zt=y.innerHeight,it=64,dn=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Jn=Math.max(200,zt-it),Ke=Math.min(640,Jn),Ct=Math.max(200,Ke-dn);oe.style.height=`${Ct}px`}}finally{if(At(),ao(),R&&T){let it=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((vt=(Ye=r.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?vt:640),dn=(Oe=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?Oe:!1,Jn=(nt=(te=r.launcher)==null?void 0:te.mobileFullscreen)!=null?nt:!0,Ke=ln(r)&&Jn&&it,Ct=dn||Jn&&it&&T||Ke;if(Ct&&!Yt){let Gn=e.getRootNode(),sn=Gn instanceof ShadowRoot?Gn.host:e.closest(".persona-host");sn&&!Qt&&(Qt=ul(sn,(Ot=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Ot:wn)),Yt=ml(e.ownerDocument)}else Ct||(Qt==null||Qt(),Qt=null,Yt==null||Yt(),Yt=null)}}};Zt();let Pt=(Kc=e.ownerDocument.defaultView)!=null?Kc:window;if(Pt.addEventListener("resize",Zt),xt.push(()=>Pt.removeEventListener("resize",Zt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{At()});c.observe(_e),xt.push(()=>c.disconnect())}vr=X.scrollTop;let Bt=X.scrollHeight,cn=()=>{let c=X.scrollTop,g=X.scrollHeight,b=g<Bt;Bt=g;let{action:y,nextLastScrollTop:E}=di({following:xr.isFollowing(),currentScrollTop:c,lastScrollTop:vr,nearBottom:ta(X,Es),userScrollThreshold:va,isAutoScrolling:Br||Ao||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(vr=E,y==="resume"){to();return}y==="pause"&&Ls()};X.addEventListener("scroll",cn,{passive:!0}),xt.push(()=>X.removeEventListener("scroll",cn));let bn=c=>{let g=pi({following:xr.isFollowing(),deltaY:c.deltaY,nearBottom:ta(X,Es),resumeWhenNearBottom:!0});g==="pause"?Ls():g==="resume"&&to()};X.addEventListener("wheel",bn,{passive:!0}),xt.push(()=>X.removeEventListener("wheel",bn)),Wt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,vr=X.scrollTop,to(),no(!0)}),xt.push(()=>Wt.remove()),xt.push(()=>{ks()});let hn=()=>{Ue&&(zn&&(Ue.removeEventListener("click",zn),zn=null),D()?(Ue.style.display="",zn=()=>{Nt(!1,"user")},Ue.addEventListener("click",zn)):Ue.style.display="none")};hn(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{_.clearMessages(),ye.clear(),to(),xo(We.composerOverlay);try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)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={},w.syncFromMetadata(),V==null||V.clear(),de==null||de.reset(),le==null||le.update()})})(),Ut&&Ut.addEventListener("submit",Bs),he==null||he.addEventListener("keydown",Ns),he==null||he.addEventListener("input",Ds),he==null||he.addEventListener("paste",Fs);let cr=(Jc=e.ownerDocument)!=null?Jc:document;cr.addEventListener("keydown",Os,!0);let ec="persona-attachment-drop-active",_s=0,Qi=()=>{_s=0,fe.classList.remove(ec)},rs=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&ot!==null},tc=c=>{!_i(c.dataTransfer)||!rs()||(_s++,_s===1&&fe.classList.add(ec))},nc=c=>{!_i(c.dataTransfer)||!rs()||(_s--,_s<=0&&Qi())},rc=c=>{!_i(c.dataTransfer)||!rs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},oc=c=>{var b;if(!_i(c.dataTransfer)||!rs())return;c.preventDefault(),c.stopPropagation(),Qi();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&ot.handleFiles(g)},io=!0;fe.addEventListener("dragenter",tc,io),fe.addEventListener("dragleave",nc,io),e.addEventListener("dragover",rc,io),e.addEventListener("drop",oc,io);let Ba=e.ownerDocument,sc=c=>{rs()&&c.preventDefault()},ac=c=>{rs()&&c.preventDefault()};Ba.addEventListener("dragover",sc),Ba.addEventListener("drop",ac),xt.push(()=>{Ut&&Ut.removeEventListener("submit",Bs),he==null||he.removeEventListener("keydown",Ns),he==null||he.removeEventListener("input",Ds),he==null||he.removeEventListener("paste",Fs),cr.removeEventListener("keydown",Os,!0)}),xt.push(()=>{fe.removeEventListener("dragenter",tc,io),fe.removeEventListener("dragleave",nc,io),e.removeEventListener("dragover",rc,io),e.removeEventListener("drop",oc,io),Ba.removeEventListener("dragover",sc),Ba.removeEventListener("drop",ac),Qi()}),xt.push(()=>{_.cancel()}),Qe?xt.push(()=>{Qe==null||Qe.destroy()}):tt&&xt.push(()=>{tt==null||tt.remove()});let on={update(c){var tn,Lr,an,Mn,ur,Io,Wo,Da,js,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,zp,Vp,Kp,Jp,Gp,Xp;let g=r.toolCall,b=r.messageActions,y=(tn=r.layout)==null?void 0:tn.messages,E=r.colorScheme,N=r.loadingIndicator,O=r.iterationDisplay,U=(Lr=r.features)==null?void 0:Lr.showReasoning,H=(an=r.features)==null?void 0:an.showToolCalls,Te=(Mn=r.features)==null?void 0:Mn.toolCallDisplay,ge=(ur=r.features)==null?void 0:ur.reasoningDisplay;r={...r,...c},hr(),uo(e,r),Wi(e,r),Ri(e,r),Un(),r.colorScheme!==E&&eo();let ee=fa.getForInstance(r.plugins);s.length=0,s.push(...ee),T=(Wo=(Io=r.launcher)==null?void 0:Io.enabled)!=null?Wo:!0,B=(js=(Da=r.launcher)==null?void 0:Da.autoExpand)!=null?js:!1,Ge=(nd=(td=r.features)==null?void 0:td.showReasoning)!=null?nd:!0,Ce=(od=(rd=r.features)==null?void 0:rd.showToolCalls)!=null?od:!0,be=(ad=(sd=r.features)==null?void 0:sd.scrollToBottom)!=null?ad:{},Gt(),Nr();let Ae=He;if(He=(ld=(id=r.features)==null?void 0:id.showEventStreamToggle)!=null?ld:!1,He&&!Ae){if(V||(J=new ma(Pe),V=new ua(ue,J),de=de!=null?de:new ga,J.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),_.setSSEEventCallback((Q,Tt)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,Q,Tt),de==null||de.processEvent(Q,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!bt&&Ne){let Q=(dd=(cd=r.features)==null?void 0:cd.eventStream)==null?void 0:dd.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");bt=h("button",Tt),bt.style.width="28px",bt.style.height="28px",bt.style.color=Ln.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let jt=we("activity","18px","currentColor",1.5);jt&&bt.appendChild(jt);let ut=We.clearChatButtonWrapper,Rt=We.closeButtonWrapper,un=ut||Rt;un&&un.parentNode===Ne?Ne.insertBefore(bt,un):Ne.appendChild(bt),bt.addEventListener("click",()=>{ae?Nn():An()})}}else!He&&Ae&&(Nn(),bt&&(bt.remove(),bt=null),V==null||V.clear(),J==null||J.destroy(),V=null,J=null,de==null||de.reset(),de=null);if(((pd=r.launcher)==null?void 0:pd.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((ud=r.launcher)==null?void 0:ud.enabled)===!1&&tt&&(tt.remove(),tt=null),((md=r.launcher)==null?void 0:md.enabled)!==!1&&!Qe&&!tt){let Q=s.find(Tt=>Tt.renderLauncher);if(Q!=null&&Q.renderLauncher){let Tt=Q.renderLauncher({config:r,defaultRenderer:()=>la(r,Xe).element,onToggle:Xe});Tt&&(tt=Tt,e.appendChild(tt))}tt||(Qe=la(r,Xe),e.appendChild(Qe.element))}Qe&&Qe.update(r),Ee&&((gd=r.launcher)==null?void 0:gd.title)!==void 0&&(Ee.textContent=r.launcher.title),De&&((fd=r.launcher)==null?void 0:fd.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Me=(hd=r.layout)==null?void 0:hd.header;if((Me==null?void 0:Me.layout)!==S&&Ne){let Q=Me?gs(r,Me,{showClose:D(),onClose:()=>Nt(!1,"user")}):qr({config:r,showClose:D(),onClose:()=>Nt(!1,"user")});Ne.replaceWith(Q.header),Ne=Q.header,F=Q.iconHolder,Ee=Q.headerTitle,De=Q.headerSubtitle,Ue=Q.closeButton,S=Me==null?void 0:Me.layout}else if(Me&&(F&&(F.style.display=Me.showIcon===!1?"none":""),Ee&&(Ee.style.display=Me.showTitle===!1?"none":""),De&&(De.style.display=Me.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=Me.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let Q=Me.showClearChat;if(Q!==void 0){We.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:Tt}=We;Tt&&!Tt.classList.contains("persona-absolute")&&(Q?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let st=((bd=r.layout)==null?void 0:bd.showHeader)!==!1;Ne&&(Ne.style.display=st?"":"none");let Ve=((yd=r.layout)==null?void 0:yd.showFooter)!==!1;_e&&(_e.style.display=Ve?"":"none"),At(),Nr(),T!==W?T?Nt(B,"auto"):(R=!0,ao()):B!==P&&Nt(B,"auto"),P=B,W=T,Zt(),hn();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(g),Le=JSON.stringify(r.messageActions)!==JSON.stringify(b),qe=JSON.stringify((xd=r.layout)==null?void 0:xd.messages)!==JSON.stringify(y),Ye=((vd=r.loadingIndicator)==null?void 0:vd.render)!==(N==null?void 0:N.render)||((wd=r.loadingIndicator)==null?void 0:wd.renderIdle)!==(N==null?void 0:N.renderIdle)||((Cd=r.loadingIndicator)==null?void 0:Cd.showBubble)!==(N==null?void 0:N.showBubble),vt=r.iterationDisplay!==O,L=((Sd=(Ad=r.features)==null?void 0:Ad.showReasoning)!=null?Sd:!0)!==(U!=null?U:!0)||((Ed=(Td=r.features)==null?void 0:Td.showToolCalls)!=null?Ed:!0)!==(H!=null?H:!0)||JSON.stringify((Md=r.features)==null?void 0:Md.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((kd=r.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(ge);(Ie||Le||qe||Ye||vt||L)&&_&&(Ts++,To($e,_.getMessages(),Re));let te=(Ld=r.launcher)!=null?Ld:{},nt=(Pd=te.headerIconHidden)!=null?Pd:!1,Ft=(Wd=(Id=r.layout)==null?void 0:Id.header)==null?void 0:Wd.showIcon,Ot=nt||Ft===!1,zt=te.headerIconName,it=(Rd=te.headerIconSize)!=null?Rd:"48px";if(F){let Q=fe.querySelector(".persona-border-b-persona-divider"),Tt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Ot)F.style.display="none",Q&&Tt&&!Q.contains(Tt)&&Q.insertBefore(Tt,Q.firstChild);else{if(F.style.display="",F.style.height=it,F.style.width=it,Q&&Tt&&(Q.contains(F)?F.nextSibling!==Tt&&(F.remove(),Q.insertBefore(F,Tt)):Q.insertBefore(F,Tt)),zt){let ut=parseFloat(it)||24,Rt=we(zt,ut*.6,"#ffffff",2);Rt?F.replaceChildren(Rt):F.textContent=(Hd=te.agentIconText)!=null?Hd:"\u{1F4AC}"}else if(te.iconUrl){let ut=F.querySelector("img");if(ut)ut.src=te.iconUrl,ut.style.height=it,ut.style.width=it;else{let Rt=document.createElement("img");Rt.src=te.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=it,Rt.style.width=it,F.replaceChildren(Rt)}}else{let ut=F.querySelector("svg"),Rt=F.querySelector("img");(ut||Rt)&&F.replaceChildren(),F.textContent=(Bd=te.agentIconText)!=null?Bd:"\u{1F4AC}"}let jt=F.querySelector("img");jt&&(jt.style.height=it,jt.style.width=it)}}let dn=(Nd=(Dd=r.layout)==null?void 0:Dd.header)==null?void 0:Nd.showTitle,Jn=(Fd=(Od=r.layout)==null?void 0:Od.header)==null?void 0:Fd.showSubtitle;if(Ee&&(Ee.style.display=dn===!1?"none":""),De&&(De.style.display=Jn===!1?"none":""),Ue){((_d=($d=r.layout)==null?void 0:$d.header)==null?void 0:_d.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(jd=te.closeButtonSize)!=null?jd:"32px",jt=(Ud=te.closeButtonPlacement)!=null?Ud:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:ut}=We,Rt=jt==="top-right",un=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Rt!==un)if(ut.remove(),Rt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(ut);else{let ht=(zd=(qd=te.clearChat)==null?void 0:qd.placement)!=null?zd:"inline",mn=(Kd=(Vd=te.clearChat)==null?void 0:Vd.enabled)!=null?Kd:!0;ut.className=mn&&ht==="inline"?"":"persona-ml-auto";let Hn=fe.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ut)}if(Ue.style.color=te.closeButtonColor||Ln.actionIconColor,te.closeButtonBackgroundColor?(Ue.style.backgroundColor=te.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),te.closeButtonBorderWidth||te.closeButtonBorderColor){let ht=te.closeButtonBorderWidth||"0px",mn=te.closeButtonBorderColor||"transparent";Ue.style.border=`${ht} solid ${mn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");te.closeButtonBorderRadius?(Ue.style.borderRadius=te.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),te.closeButtonPaddingX?(Ue.style.paddingLeft=te.closeButtonPaddingX,Ue.style.paddingRight=te.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),te.closeButtonPaddingY?(Ue.style.paddingTop=te.closeButtonPaddingY,Ue.style.paddingBottom=te.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let xn=(Jd=te.closeButtonIconName)!=null?Jd:"x",Ar=(Gd=te.closeButtonIconText)!=null?Gd:"\xD7";Ue.innerHTML="";let kn=we(xn,"28px","currentColor",1);kn?Ue.appendChild(kn):Ue.textContent=Ar;let en=(Xd=te.closeButtonTooltipText)!=null?Xd:"Close chat",Qn=(Qd=te.closeButtonShowTooltip)!=null?Qd:!0;if(Ue.setAttribute("aria-label",en),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),Qn&&en)){let ht=null,mn=()=>{if(ht||!Ue)return;let Ro=Ue.ownerDocument,Us=Ro.body;if(!Us)return;ht=Pr(Ro,"div","persona-clear-chat-tooltip"),ht.textContent=en;let qs=Pr(Ro,"div");qs.className="persona-clear-chat-tooltip-arrow",ht.appendChild(qs);let Ho=Ue.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(mo),ht.style.left=`${Ho.left+Ho.width/2}px`,ht.style.top=`${Ho.top-8}px`,ht.style.transform="translate(-50%, -100%)",Us.appendChild(ht)},Hn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ut.addEventListener("mouseenter",mn),ut.addEventListener("mouseleave",Hn),Ue.addEventListener("focus",mn),Ue.addEventListener("blur",Hn),ut._cleanupTooltip=()=>{Hn(),ut&&(ut.removeEventListener("mouseenter",mn),ut.removeEventListener("mouseleave",Hn)),Ue&&(Ue.removeEventListener("focus",mn),Ue.removeEventListener("blur",Hn))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Ct}=We;if(Ke){let Q=(Yd=te.clearChat)!=null?Yd:{},Tt=(Zd=Q.enabled)!=null?Zd:!0,jt=(tp=(ep=r.layout)==null?void 0:ep.header)==null?void 0:tp.showClearChat,ut=jt!==void 0?jt:Tt,Rt=(np=Q.placement)!=null?np:"inline";if(Ct){Ct.style.display=ut?"":"none";let{closeButtonWrapper:un}=We;!$()&&un&&!un.classList.contains("persona-absolute")&&(ut?un.classList.remove("persona-ml-auto"):un.classList.add("persona-ml-auto"));let xn=Rt==="top-right",Ar=Ct.classList.contains("persona-absolute");if(!$()&&xn!==Ar&&ut){if(Ct.remove(),xn)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",fe.style.position="relative",fe.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let en=fe.querySelector(".persona-border-b-persona-divider"),Qn=We.closeButtonWrapper;en&&Qn&&Qn.parentElement===en?en.insertBefore(Ct,Qn):en&&en.appendChild(Ct)}let kn=We.closeButtonWrapper;kn&&!kn.classList.contains("persona-absolute")&&(xn?kn.classList.add("persona-ml-auto"):kn.classList.remove("persona-ml-auto"))}}if(ut){if(!$()){let ht=(rp=Q.size)!=null?rp:"32px";Ke.style.height=ht,Ke.style.width=ht}let un=(op=Q.iconName)!=null?op:"refresh-cw",xn=(sp=Q.iconColor)!=null?sp:"";Ke.style.color=xn||Ln.actionIconColor,Ke.innerHTML="";let Ar=$()?"14px":"20px",kn=we(un,Ar,"currentColor",2);if(kn&&Ke.appendChild(kn),Q.backgroundColor?(Ke.style.backgroundColor=Q.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ht=Q.borderWidth||"0px",mn=Q.borderColor||"transparent";Ke.style.border=`${ht} solid ${mn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");Q.borderRadius?(Ke.style.borderRadius=Q.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),Q.paddingX?(Ke.style.paddingLeft=Q.paddingX,Ke.style.paddingRight=Q.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),Q.paddingY?(Ke.style.paddingTop=Q.paddingY,Ke.style.paddingBottom=Q.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let en=(ap=Q.tooltipText)!=null?ap:"Clear chat",Qn=(ip=Q.showTooltip)!=null?ip:!0;if(Ke.setAttribute("aria-label",en),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),Qn&&en)){let ht=null,mn=()=>{if(ht||!Ke)return;let Ro=Ke.ownerDocument,Us=Ro.body;if(!Us)return;ht=Pr(Ro,"div","persona-clear-chat-tooltip"),ht.textContent=en;let qs=Pr(Ro,"div");qs.className="persona-clear-chat-tooltip-arrow",ht.appendChild(qs);let Ho=Ke.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(mo),ht.style.left=`${Ho.left+Ho.width/2}px`,ht.style.top=`${Ho.top-8}px`,ht.style.transform="translate(-50%, -100%)",Us.appendChild(ht)},Hn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Ct.addEventListener("mouseenter",mn),Ct.addEventListener("mouseleave",Hn),Ke.addEventListener("focus",mn),Ke.addEventListener("blur",Hn),Ct._cleanupTooltip=()=>{Hn(),Ct&&(Ct.removeEventListener("mouseenter",mn),Ct.removeEventListener("mouseleave",Hn)),Ke&&(Ke.removeEventListener("focus",mn),Ke.removeEventListener("blur",Hn))}}}}let Gn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ha],sn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ko.message,Ko.messageAndClick];w=ba({parsers:Gn,handlers:sn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Re=Nm(r,w,se),_.updateConfig(r),To($e,_.getMessages(),Re),br.render(r.suggestionChips,_,he,void 0,r.suggestionChipsConfig),Rs(),Yo(_.isStreaming());let pr=((lp=r.voiceRecognition)==null?void 0:lp.enabled)===!0,Xn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ko=((dp=(cp=r.voiceRecognition)==null?void 0:cp.provider)==null?void 0:dp.type)==="runtype";if(pr&&(Xn||ko))if(!z||!qt){let Q=ns(r.voiceRecognition,r.sendButton);Q&&(z=Q.micButton,qt=Q.micButtonWrapper,It.insertBefore(qt,Pn),z.addEventListener("click",ke),z.disabled=_.isStreaming())}else{let Q=(pp=r.voiceRecognition)!=null?pp:{},Tt=(up=r.sendButton)!=null?up:{},jt=(mp=Q.iconName)!=null?mp:"mic",ut=(gp=Tt.size)!=null?gp:"40px",Rt=(fp=Q.iconSize)!=null?fp:ut,un=parseFloat(Rt)||24;z.style.width=Rt,z.style.height=Rt,z.style.minWidth=Rt,z.style.minHeight=Rt;let xn=(bp=(hp=Q.iconColor)!=null?hp:Tt.textColor)!=null?bp:"currentColor";z.innerHTML="";let Ar=we(jt,un,xn,2);Ar?z.appendChild(Ar):z.textContent="\u{1F3A4}";let kn=(yp=Q.backgroundColor)!=null?yp:Tt.backgroundColor;kn?z.style.backgroundColor=kn:z.style.backgroundColor="",xn?z.style.color=xn:z.style.color="var(--persona-text, #111827)",Q.borderWidth?(z.style.borderWidth=Q.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),Q.borderColor?z.style.borderColor=Q.borderColor:z.style.borderColor="",Q.paddingX?(z.style.paddingLeft=Q.paddingX,z.style.paddingRight=Q.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),Q.paddingY?(z.style.paddingTop=Q.paddingY,z.style.paddingBottom=Q.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let en=qt==null?void 0:qt.querySelector(".persona-send-button-tooltip"),Qn=(xp=Q.tooltipText)!=null?xp:"Start voice recognition";if(((vp=Q.showTooltip)!=null?vp:!1)&&Qn)if(en)en.textContent=Qn,en.style.display="";else{let mn=document.createElement("div");mn.className="persona-send-button-tooltip",mn.textContent=Qn,qt==null||qt.insertBefore(mn,z)}else en&&(en.style.display="none");qt.style.display="",z.disabled=_.isStreaming()}else z&&qt&&(qt.style.display="none",((Cp=(wp=r.voiceRecognition)==null?void 0:wp.provider)==null?void 0:Cp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Kn&&Cr());if(((Ap=r.attachments)==null?void 0:Ap.enabled)===!0)if(!_t||!et){let Q=(Sp=r.attachments)!=null?Sp:{},jt=(Ep=((Tp=r.sendButton)!=null?Tp:{}).size)!=null?Ep:"40px";ve||(ve=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ve.style.display="none",Ut.insertBefore(ve,he)),re||(re=document.createElement("input"),re.type="file",re.accept=((Mp=Q.allowedTypes)!=null?Mp:Ur).join(","),re.multiple=((kp=Q.maxFiles)!=null?kp:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),Ut.insertBefore(re,he)),_t=h("div","persona-send-button-wrapper"),et=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),et.type="button",et.setAttribute("aria-label",(Lp=Q.buttonTooltipText)!=null?Lp:"Attach file");let ut=(Pp=Q.buttonIconName)!=null?Pp:"paperclip",Rt=jt,un=parseFloat(Rt)||40,xn=Math.round(un*.6);et.style.width=Rt,et.style.height=Rt,et.style.minWidth=Rt,et.style.minHeight=Rt,et.style.fontSize="18px",et.style.lineHeight="1",et.style.backgroundColor="transparent",et.style.color="var(--persona-primary, #111827)",et.style.border="none",et.style.borderRadius="6px",et.style.transition="background-color 0.15s ease",et.addEventListener("mouseenter",()=>{et.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),et.addEventListener("mouseleave",()=>{et.style.backgroundColor="transparent"});let Ar=we(ut,xn,"currentColor",1.5);Ar?et.appendChild(Ar):et.textContent="\u{1F4CE}",et.addEventListener("click",Qn=>{Qn.preventDefault(),re==null||re.click()}),_t.appendChild(et);let kn=(Ip=Q.buttonTooltipText)!=null?Ip:"Attach file",en=h("div","persona-send-button-tooltip");en.textContent=kn,_t.appendChild(en),at.append(_t),!ot&&re&&ve&&(ot=jo.fromConfig(Q),ot.setPreviewsContainer(ve),re.addEventListener("change",async()=>{ot&&(re!=null&&re.files)&&(await ot.handleFileSelect(re.files),re.value="")})),fe.querySelector(".persona-attachment-drop-overlay")||fe.appendChild(Om(Q.dropOverlay))}else{_t.style.display="";let Q=(Wp=r.attachments)!=null?Wp:{};re&&(re.accept=((Rp=Q.allowedTypes)!=null?Rp:Ur).join(","),re.multiple=((Hp=Q.maxFiles)!=null?Hp:4)>1),ot&&ot.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else _t&&(_t.style.display="none"),ot&&ot.clearAttachments(),(Bp=fe.querySelector(".persona-attachment-drop-overlay"))==null||Bp.remove();let Xt=(Dp=r.sendButton)!=null?Dp:{},Lo=(Np=Xt.useIcon)!=null?Np:!1,lo=(Op=Xt.iconText)!=null?Op:"\u2191",co=Xt.iconName,$r=(Fp=Xt.tooltipText)!=null?Fp:"Send message",Po=($p=Xt.showTooltip)!=null?$p:!1,rt=(_p=Xt.size)!=null?_p:"40px",yn=Xt.backgroundColor,fn=Xt.textColor;if(Lo){if(pe.style.width=rt,pe.style.height=rt,pe.style.minWidth=rt,pe.style.minHeight=rt,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",fn?pe.style.color=fn:pe.style.color="var(--persona-button-primary-fg, #ffffff)",co){let Q=parseFloat(rt)||24,Tt=(fn==null?void 0:fn.trim())||"currentColor",jt=we(co,Q,Tt,2);jt?pe.appendChild(jt):pe.textContent=lo}else pe.textContent=lo;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",yn?(pe.style.backgroundColor=yn,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(Up=(jp=r.copy)==null?void 0:jp.sendButtonLabel)!=null?Up:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",yn?(pe.style.backgroundColor=yn,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),fn?pe.style.color=fn:pe.classList.add("persona-text-white");Xt.borderWidth?(pe.style.borderWidth=Xt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Xt.borderColor?pe.style.borderColor=Xt.borderColor:pe.style.borderColor="",Xt.paddingX?(pe.style.paddingLeft=Xt.paddingX,pe.style.paddingRight=Xt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Xt.paddingY?(pe.style.paddingTop=Xt.paddingY,pe.style.paddingBottom=Xt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let pn=Pn==null?void 0:Pn.querySelector(".persona-send-button-tooltip");if(Po&&$r)if(pn)pn.textContent=$r,pn.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=$r,Pn==null||Pn.insertBefore(Q,pe)}else pn&&(pn.style.display="none");let ft=(Jp=(qp=r.layout)==null?void 0:qp.contentMaxWidth)!=null?Jp:$()?(Kp=(Vp=(zp=r.launcher)==null?void 0:zp.composerBar)==null?void 0:Vp.contentMaxWidth)!=null?Kp:"720px":void 0;ft?($e.style.maxWidth=ft,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ut&&(Ut.style.maxWidth=ft,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),Ht&&(Ht.style.maxWidth=ft,Ht.style.marginLeft="auto",Ht.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ut&&(Ut.style.maxWidth="",Ut.style.marginLeft="",Ut.style.marginRight=""),Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""));let lt=(Gp=r.statusIndicator)!=null?Gp:{},Mt=(Xp=lt.visible)!=null?Xp:!0;if(gn.style.display=Mt?"":"none",_){let Q=_.getStatus();xe(gn,(jt=>{var ut,Rt,un,xn;return jt==="idle"?(ut=lt.idleText)!=null?ut:vn.idle:jt==="connecting"?(Rt=lt.connectingText)!=null?Rt:vn.connecting:jt==="connected"?(un=lt.connectedText)!=null?un:vn.connected:jt==="error"?(xn=lt.errorText)!=null?xn:vn.error:vn[jt]})(Q),lt,Q)}gn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Rn=lt.align==="left"?"persona-text-left":lt.align==="center"?"persona-text-center":"persona-text-right";gn.classList.add(Rn)},open(){D()&&Nt(!0,"api")},close(){D()&&Nt(!1,"api")},toggle(){D()&&Nt(!R,"api")},clearChat(){Sn=!1,_.clearMessages(),ye.clear(),to();try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)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={},w.syncFromMetadata(),V==null||V.clear(),de==null||de.reset(),le==null||le.update()},setMessage(c){return!he||_.isStreaming()?!1:(!R&&D()&&Nt(!0,"system"),he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let g=(c==null?void 0:c.trim())||he.value.trim();return g?(!R&&D()&&Nt(!0,"system"),he.value="",he.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return _.isStreaming()?!1:((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(_.isVoiceActive()||(!R&&D()&&Nt(!0,"system"),yt.manuallyDeactivated=!1,Wn(),_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("user"),_.isVoiceActive()&&M()})),!0):Kn?!0:$s()?(!R&&D()&&Nt(!0,"system"),yt.manuallyDeactivated=!1,Wn(),Mo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Wn(),lr("user"),G()}),!0):!1:Kn?(yt.manuallyDeactivated=!0,Wn(),Cr("user"),!0):!1},injectMessage(c){return!R&&D()&&Nt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!R&&D()&&Nt(!0,"system");let g=_.injectAssistantMessage(c);return q&&(q=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(c){return!R&&D()&&Nt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!R&&D()&&Nt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!R&&D()&&Nt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!R&&D()&&Nt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!R&&D()&&Nt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,g){return _.connectStream(c,g)},__pushEventStreamEvent(c){V&&(de==null||de.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!He||!V||An()},hideEventStream(){ae&&Nn()},isEventStreamVisible(){return ae},showArtifacts(){fr(r)&&(Sn=!1,Un(),St==null||St.setMobileOpen(!0))},hideArtifacts(){fr(r)&&(Sn=!0,Un())},upsertArtifact(c){return fr(r)?(Sn=!1,_.upsertArtifact(c)):null},selectArtifact(c){fr(r)&&_.selectArtifact(c)},clearArtifacts(){fr(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!R&&!$()||!he?!1:(he.focus(),!0)},async resolveApproval(c,g,b){let E=_.getMessages().find(N=>{var O;return N.variant==="approval"&&((O=N.approval)==null?void 0:O.id)===c});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${c}`);if(E.approval.toolType==="webmcp"){_.resolveWebMcpApproval(E.id,g);return}return _.resolveApproval(E.approval,g,b)},getMessages(){return _.getMessages()},getStatus(){return _.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()&&R},isVoiceActive(){return yt.active},getState(){return{open:D()&&R,launcherEnabled:T,voiceActive:yt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!R&&D()&&Nt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let b=Fi({onSubmit:async(y,E)=>{var N;_.isClientTokenMode()&&await _.submitCSATFeedback(y,E),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&D()&&Nt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let b=$i({onSubmit:async(y,E)=>{var N;_.isClientTokenMode()&&await _.submitNPSFeedback(y,E),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return _.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return _.submitNPSFeedback(c,g)},destroy(){kr!=null&&(clearInterval(kr),kr=null),xt.forEach(c=>c()),me.remove(),Ze==null||Ze.remove(),Qe==null||Qe.destroy(),tt==null||tt.remove(),zn&&Ue.removeEventListener("click",zn)}};if((((Gc=n==null?void 0:n.debugTools)!=null?Gc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:on,getMessages:on.getMessages,getStatus:on.getStatus,getMetadata:on.getPersistentMetadata,updateMetadata:on.updatePersistentMetadata,clearHistory:()=>on.clearChat(),setVoiceActive:b=>b?on.startVoiceRecognition():on.stopVoiceRecognition()};window.AgentWidgetBrowser=g,xt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.focusInput()};if(window.addEventListener("persona:focusInput",g),xt.push(()=>{window.removeEventListener("persona:focusInput",g)}),He){let U=Te=>{let ge=Te.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.showEventStream()},H=Te=>{let ge=Te.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",H),xt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",H)})}let b=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.showArtifacts()},y=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.hideArtifacts()},E=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&on.upsertArtifact(H.artifact)},N=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&on.selectArtifact(H.id)},O=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",O),xt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",O)})}let dr=Xh(r.persistState);if(dr&&D()){let c=Qh(dr.storage),g=`${dr.keyPrefix}widget-open`,b=`${dr.keyPrefix}widget-voice`,y=`${dr.keyPrefix}widget-voice-mode`;if(c){let E=((Xc=dr.persist)==null?void 0:Xc.openState)&&c.getItem(g)==="true",N=((Qc=dr.persist)==null?void 0:Qc.voiceState)&&c.getItem(b)==="true",O=((Yc=dr.persist)==null?void 0:Yc.voiceState)&&c.getItem(y)==="true";if(E&&setTimeout(()=>{on.open(),setTimeout(()=>{var U;if(N||O)on.startVoiceRecognition();else if((U=dr.persist)!=null&&U.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(Zc=dr.persist)!=null&&Zc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(ed=dr.persist)!=null&&ed.voiceState&&(o.on("voice:state",U=>{c.setItem(b,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(y,U.viaVoice?"true":"false")})),dr.clearOnChatClear){let U=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},H=()=>U();window.addEventListener("persona:clear-chat",H),xt.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&D()&&setTimeout(()=>{on.open()},0),Or(),on};var Yh=(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},Fm=(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"},$l=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=""},$m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",$l(e)},Nl=e=>{e.style.transition=""},Ol=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=""},Fl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ui=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Zh=(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))},eb=(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)},_m=(e,t,n,r,s,o,a)=>{var v,x,w,T,B,k;let i=mr(o),d=i.reveal==="push";Zh(e,t,n,r,d),eb(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,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(T=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileBreakpoint)!=null?T:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ol(t),Nl(r),$m(r),Fl(n),Ui(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((k=(B=o==null?void 0:o.launcher)==null?void 0:B.zIndex)!=null?k:wn),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"),$m(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ol(t),Nl(r),Fl(n),Ui(s,r);let P=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":W;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=P,r.style.transform=S,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",Nl(r),$l(r),Ui(s,r);let P=Yh(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",I=i.side==="right"?a?`translateX(-${P}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${P}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=`${W+P}px`,t.style.transition=S,t.style.transform=I,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}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="",Ol(t),$l(r),Fl(n),Ui(s,r);let P=i.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${W}`,r.style.width=W,r.style.maxWidth=W,r.style.minWidth=W,r.style.minHeight="0",r.style.position="relative",r.style.overflow=P||I?"hidden":"visible",r.style.transition=S,P&&(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")}},tb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Fm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Fm(n,r)},destroy(){n.remove()}}},nb=(e,t)=>{var B,k,P,W;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"),p=n.createElement("div"),u=(k=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||k?(W=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),mr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{_m(a,i,d,l,p,t,u)}),f.observe(a))},x=()=>{_m(a,i,d,l,p,t,u),v()},w=a.ownerDocument.defaultView,T=()=>{x()};return w==null||w.addEventListener("resize",T),mr(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(S){let I=S.launcherEnabled?S.open:!0;u!==I&&(u=I,x())},updateConfig(S){var I,$;t=S,(($=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)!=null?$:!0)===!1&&(u=!0),x()},destroy(){w==null||w.removeEventListener("resize",T),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ya=(e,t)=>ln(t)?nb(e,t):tb(e,t);var _l={},jm=!1,rb=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},ob=()=>{try{if(typeof _l!="undefined"&&_l.url)return new URL("../widget.css",_l.url).href}catch{}return null},Um=(e,t)=>{let n=ob(),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)}},jl=e=>{let t=rb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=ya(t,s),a,i=[],d=(w,T)=>{var W,S;let k=!((S=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?S:!0)||ln(T),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),k&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let I=w.attachShadow({mode:"open"});I.appendChild(P),Um(I,r)}else w.appendChild(P),Um(w,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(o.host,s);a=ji(w,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(jm||(jm=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=w=>{f(),o.destroy(),o=ya(t,w),s=w,u()},v={update(w){var S,I,$,D,R,q;let T={...s,...w,launcher:{...(S=s==null?void 0:s.launcher)!=null?S:{},...(I=w==null?void 0:w.launcher)!=null?I:{},dock:{...(D=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?D:{},...(q=(R=w==null?void 0:w.launcher)==null?void 0:R.dock)!=null?q:{}}}},B=ln(s),k=ln(T),P=fo(s),W=fo(T);if(B!==k||P!==W){m(T);return}s=T,o.updateConfig(s),a.update(w),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,T,B){if(T==="host")return o.host;if(T in w)return Reflect.get(w,T,B);let k=a[T];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Jm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),sb=new Set(["button","a","input","select","textarea","details","summary"]),ab=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ul=/\b(product|card|item|listing|result)\b/i,zl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ib=3e3,lb=100;function Gm(e){let t=typeof e.className=="string"?e.className:"";if(Ul.test(t)||e.id&&Ul.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ul.test(r.value))return!0}return!1}function Xm(e){var t;return zl.test(((t=e.textContent)!=null?t:"").trim())}function Qm(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 cb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function qm(e){let t=e.match(zl);return t?t[0]:null}function zm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function db(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var pb="commerce-card",ub="result-card";function Vm(e){return!Gm(e)||!Xm(e)||!Qm(e)&&!cb(e)?0:5200}function Km(e){var r;return!Gm(e)||Xm(e)||!Qm(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 Vl=[{id:pb,scoreElement(e){return Vm(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||zl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Vm(e)===0)return null;let{title:n,href:r}=zm(e),s=(p=(l=qm(((d=e.textContent)!=null?d:"").trim()))!=null?l:qm(t.text))!=null?p:"",o=db(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
+ `)}},{id:ub,scoreElement(e){return Km(e)},formatSummary(e,t){if(Km(e)===0)return null;let{title:n,href:r}=zm(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
+ `)}}];function mb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function gb(e){var p,u,f,m,v,x,w,T,B,k,P,W,S;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(v=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(w=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?w:200,o=(B=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?B:!0,a=(k=t.root)!=null?k:e.root,i=(P=t.mode)!=null?P:"structured",d=(W=t.maxCandidates)!=null?W:Math.max(500,n*10),l=(S=e.rules)!=null?S:Vl;return i==="simple"&&e.rules&&e.rules.length>0?(mb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function ql(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var fb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function hb(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"||sb.has(t)||n&&ab.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ym(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 bb(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 p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Kl(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${ql(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of fb){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${ql(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=>ql(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 yb(e){return e==="static"?lb:ib}function Zm(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:Kl(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:hb(e),attributes:bb(e)}}function xb(e,t,n,r){let s=yb(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function vb(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function wb(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,p=l.tagName.toLowerCase();if(Jm.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Ym(l)){i=a.nextNode();continue}let u=Zm(l,e.maxTextLength),f=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(w=>w==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=xb(l,u,e.rules,n);s.push({el:l,domIndex:o,enriched:u,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;vb(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,n);m&&(p=m)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function Cb(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(Jm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Ym(d)){o=s.nextNode();continue}let p=Zm(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!f){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}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 eg(e={}){var r;let t=gb(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Cb(t,n):wb(t,n):[]}var qi=100;function tg(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:
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,_i)}" (clickable)`);r.push(`Interactive elements:
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,qi)}" (clickable)`);r.push(`Interactive elements:
114
114
  ${a.join(`
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,_i)}" (navigable)`);r.push(`Navigation links:
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,qi)}" (navigable)`);r.push(`Navigation links:
116
116
  ${a.join(`
117
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,_i)}" (input)`);r.push(`Form inputs:
117
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,qi)}" (input)`);r.push(`Form inputs:
118
118
  ${a.join(`
119
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,_i)}"`);r.push(`Content:
119
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,qi)}"`);r.push(`Content:
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
123
- `)}var Km={name:"@runtypelabs/persona",version:"3.29.1",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"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.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:launcher && pnpm run build:theme-ref && pnpm run build:codegen && 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:codegen":"tsup src/codegen.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","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},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 qo=Km.version;function Jm(){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 Gm(){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 Xm(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Er(e.colors.primary,.95),100:Er(e.colors.primary,.9),200:Er(e.colors.primary,.8),300:Er(e.colors.primary,.7),400:Er(e.colors.primary,.6),500:e.colors.primary,600:Er(e.colors.primary,.8),700:Er(e.colors.primary,.7),800:Er(e.colors.primary,.6),900:Er(e.colors.primary,.5),950:Er(e.colors.primary,.45)}}),{...t,palette:n}}}}function Qm(){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 Ym(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Er(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Zm(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var gy={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"}}},eg={components:{panel:{borderRadius:"0",shadow:"none"}}},zl={id:"shop",label:"Shopping Assistant",config:{theme:gy,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?"]}},Vl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:eg}},Kl={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:eg}},Jl={shop:zl,minimal:Vl,fullscreen:Kl};function tg(e){return Jl[e]}var ng=Ol;function qr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function fy(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 rg=`({ text, message }: any) => {
123
+ `)}var ng={name:"@runtypelabs/persona",version:"3.30.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"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.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"},"./plugin-kit":{types:"./dist/plugin-kit.d.ts",import:"./dist/plugin-kit.js",require:"./dist/plugin-kit.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:launcher && pnpm run build:theme-ref && pnpm run build:codegen && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:plugin-kit && pnpm run build:animations","build:plugin-kit":"tsup src/plugin-kit.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","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:codegen":"tsup src/codegen.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","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},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=ng.version;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(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Ir(e.colors.primary,.95),100:Ir(e.colors.primary,.9),200:Ir(e.colors.primary,.8),300:Ir(e.colors.primary,.7),400:Ir(e.colors.primary,.6),500:e.colors.primary,600:Ir(e.colors.primary,.8),700:Ir(e.colors.primary,.7),800:Ir(e.colors.primary,.6),900:Ir(e.colors.primary,.5),950:Ir(e.colors.primary,.45)}}),{...t,palette:n}}}}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 Ir(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 lg(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Sb={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"}}},Jl={id:"shop",label:"Shopping Assistant",config:{theme:Sb,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Yn},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?"]}},Gl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:cg}},Xl={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:cg}},Ql={shop:Jl,minimal:Gl,fullscreen:Xl};function dg(e){return Ql[e]}var pg=jl;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Tb(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var ug=`({ 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
- }`,og=`function(ctx) {
136
+ }`,mg=`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
- }`,sg=`(action: any, context: any) => {
149
+ }`,gg=`(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
- }`,ag=`function(action, context) {
166
+ }`,fg=`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
- }`,hy=`(parsed: any) => {
183
+ }`,Eb=`(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
- }`,yy=`function(parsed) {
189
+ }`,Mb=`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 by(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 ji(e){var t,n;return(n=(t=e.parserType)!=null?t:by(e.streamParser))!=null?n:"plain"}function Ui(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 qi(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 zi(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 Vi(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 Gl(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 ig(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}: {`),ig(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function yo(e,t,n,r){n&&(e.push(`${r}${t}: {`),ig(e,n,`${r} `),e.push(`${r}},`))}function fa(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function lg(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:fy(n.hooks)}:void 0;return t==="esm"?xy(r,s):t==="script-installer"?wy(r,s):t==="script-advanced"?Sy(r,s):t==="react-component"?vy(r,s):t==="react-advanced"?Cy(r,s):Ay(r,s)}function xy(e,t){let n=t==null?void 0:t.hooks,r=ji(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${fa(t)}',`," 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&&yo(o,"theme",e.theme," "),e.launcher&&yo(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(...Ui(e," ")),o.push(...qi(e," ",n)),o.push(...zi(e," ")),o.push(...Vi(e," ")),o.push(...Gl(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 vy(e,t){let n=t==null?void 0:t.hooks,r=ji(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: '${fa(t)}',`," 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&&yo(o,"theme",e.theme," "),e.launcher&&yo(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(...Ui(e," ")),o.push(...qi(e," ",n)),o.push(...zi(e," ")),o.push(...Vi(e," ")),o.push(...Gl(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 Cy(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: '${fa(t)}',`," 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&&yo(r,"theme",e.theme," "),e.launcher&&yo(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(...Ui(e," ")),r.push(...qi(e," ",n)),r.push(...zi(e," ")),r.push(...Vi(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(${hy}),`)),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(` ${rg}`),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(` ${rg}`),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(` ${sg}`),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(` ${sg}`),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 cg(e){var s;let t=ji(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(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(l[p]=m)}),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 wy(e,t){let n=cg(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${qo}/dist/install.global.js" data-config='${o}'></script>`}function Ay(e,t){let n=t==null?void 0:t.hooks,r=ji(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${qo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${qo}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${fa(t)}',`,...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&&yo(o,"theme",e.theme," "),e.launcher&&yo(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(...Ui(e," ")),o.push(...qi(e," ",n)),o.push(...zi(e," ")),o.push(...Vi(e," ")),o.push(...Gl(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 Sy(e,t){let n=t==null?void 0:t.hooks,r=cg(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
195
+ }`;function kb(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 zi(e){var t,n;return(n=(t=e.parserType)!=null?t:kb(e.streamParser))!=null?n:"plain"}function Vi(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 Ki(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 Gi(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 Yl(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 hg(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}: {`),hg(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function wo(e,t,n,r){n&&(e.push(`${r}${t}: {`),hg(e,n,`${r} `),e.push(`${r}},`))}function xa(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function bg(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:Tb(n.hooks)}:void 0;return t==="esm"?Lb(r,s):t==="script-installer"?Wb(r,s):t==="script-advanced"?Hb(r,s):t==="react-component"?Pb(r,s):t==="react-advanced"?Ib(r,s):Rb(r,s)}function Lb(e,t){let n=t==null?void 0:t.hooks,r=zi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${xa(t)}',`," 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&&wo(o,"theme",e.theme," "),e.launcher&&wo(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(...Vi(e," ")),o.push(...Ki(e," ",n)),o.push(...Ji(e," ")),o.push(...Gi(e," ")),o.push(...Yl(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 Pb(e,t){let n=t==null?void 0:t.hooks,r=zi(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: '${xa(t)}',`," 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&&wo(o,"theme",e.theme," "),e.launcher&&wo(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(...Vi(e," ")),o.push(...Ki(e," ",n)),o.push(...Ji(e," ")),o.push(...Gi(e," ")),o.push(...Yl(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 Ib(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: '${xa(t)}',`," 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&&wo(r,"theme",e.theme," "),e.launcher&&wo(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(...Vi(e," ")),r.push(...Ki(e," ",n)),r.push(...Ji(e," ")),r.push(...Gi(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(${Eb}),`)),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(` ${ug}`),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(` ${ug}`),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(` ${gg}`),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(` ${gg}`),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 yg(e){var s;let t=zi(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(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),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 Wb(e,t){let n=yg(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Jo}/dist/install.global.js" data-config='${o}'></script>`}function Rb(e,t){let n=t==null?void 0:t.hooks,r=zi(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: '${xa(t)}',`,...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&&wo(o,"theme",e.theme," "),e.launcher&&wo(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(...Vi(e," ")),o.push(...Ki(e," ",n)),o.push(...Ji(e," ")),o.push(...Gi(e," ")),o.push(...Yl(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 Hb(e,t){let n=t==null?void 0:t.hooks,r=yg(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@${qo}/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(${yy});`),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(` ${og}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${og}`),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(` ${ag}`),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(` ${ag}`),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: '${fa(t)}',`," 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 dg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},pg=.1,ug=.15,mg=1.5,Xl=24,gg=40,Ty=`
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(${Mb});`),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(` ${mg}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${mg}`),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(` ${fg}`),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(` ${fg}`),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: '${xa(t)}',`," 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 xg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},vg=.1,wg=.15,Cg=1.5,Zl=24,Ag=40,Bb=`
203
203
  /* \u2500\u2500 Root \u2500\u2500 */
204
204
  .persona-dc-root {
205
205
  display: flex;
@@ -350,7 +350,7 @@ ${a.join(`
350
350
  .persona-dc-stage {
351
351
  height: 550px;
352
352
  min-height: 400px;
353
- padding: ${Xl}px;
353
+ padding: ${Zl}px;
354
354
  overflow: auto;
355
355
  background: #f0f1f3;
356
356
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -440,5 +440,5 @@ ${a.join(`
440
440
  min-height: 300px;
441
441
  }
442
442
  }
443
- `;function Ey(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ty,document.head.appendChild(e)}function My(e,t){let n=e.clientWidth-Xl*2-gg,r=e.clientHeight-Xl*2-gg;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function ky(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 fg(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");Ey();let p=Math.max(0,Math.min(r,n.length-1)),m=s,g=o,u=null,v=1,x=!1,w=h("div","persona-dc-root"),E=h("div","persona-dc-toolbar"),B=h("div","persona-dc-toolbar-lead"),L=h("div","persona-dc-toolbar-trail"),I=jt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>we(-1)}),R=h("div");R.style.position="relative";let S=h("button","persona-dc-title-btn");S.type="button",S.setAttribute("aria-expanded","false"),S.setAttribute("aria-haspopup","listbox");let W=h("span","persona-dc-title-text"),$=h("span","persona-dc-title-chevron"),N=be("chevron-down",12,"currentColor",2);N&&$.appendChild(N),S.append(W,$);let H=h("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let j=!1;function V(){H.innerHTML="";for(let me=0;me<n.length;me++){let le=n[me],oe=h("button","persona-dc-dropdown-item");oe.type="button",oe.setAttribute("role","option"),oe.setAttribute("aria-current",me===p?"true":"false");let Ye=h("span");if(Ye.textContent=le.title,oe.appendChild(Ye),le.description){let We=h("span","persona-dc-dropdown-desc");We.textContent=le.description,oe.appendChild(We)}oe.addEventListener("click",()=>{He(),Ke(me)}),H.appendChild(oe)}}function se(){j=!j,H.style.display=j?"":"none",S.setAttribute("aria-expanded",j?"true":"false"),j&&V()}function He(){j&&(j=!1,H.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",me=>{me.stopPropagation(),se()});let qe=()=>He();document.addEventListener("click",qe),R.append(S,H);let Oe=jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>we(1)}),fe=h("span","persona-dc-counter");B.append(I,R,Oe,fe);let xe=null;i&&(xe=aa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:me=>{m=me,K.dataset.device=m,u=null,Q()}}),L.appendChild(xe.element));let Pe=null;if(a){let me=h("div","persona-dc-zoom-controls"),le=jt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let We=u!=null?u:v;u=Math.max(ug,We-pg),Q()}});Pe=h("span","persona-dc-zoom-level"),Pe.title="Reset to 100%",Pe.style.cursor="pointer",Pe.addEventListener("click",()=>{u=1,Q()});let oe=jt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let We=u!=null?u:v;u=Math.min(mg,We+pg),Q()}}),Ye=jt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{u=null,Q()}});me.append(le,Pe,oe,Ye),L.appendChild(me)}if(d){let me=h("div","persona-dc-separator");L.appendChild(me);let le=aa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:oe=>{g=oe,K.dataset.colorScheme=g,Ce()}});L.appendChild(le.element)}let De=h("div","persona-dc-separator");L.appendChild(De);let te=jt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});L.appendChild(te),E.append(B,L);let Ie=h("div","persona-dc-stage"),K=h("div","persona-dc-iframe-wrapper");K.dataset.device=m,K.dataset.colorScheme=g;let ce=h("iframe","persona-dc-iframe");ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ce.setAttribute("loading","lazy"),ce.title=n[p].title,K.appendChild(ce),Ie.appendChild(K),w.append(E,Ie),e.appendChild(w);function Ce(){var me;try{let le=(me=ce.contentDocument)==null?void 0:me.body;if(!le)return;g==="dark"?le.classList.add("theme-dark"):le.classList.remove("theme-dark")}catch{}}ce.addEventListener("load",()=>Ce());function he(){let me=n[p];W.textContent=me.title,fe.textContent=`${p+1} / ${n.length}`,ce.title=me.title}function we(me){let le=((p+me)%n.length+n.length)%n.length;Ke(le)}function Ke(me){me<0||me>=n.length||(p=me,ce.src=n[p].url,he(),l==null||l(p,n[p]))}function Q(){var oe;if(x)return;let me=(oe=dg[m])!=null?oe:dg.desktop;v=My(Ie,me);let le=Math.max(ug,Math.min(mg,u!=null?u:v));ky(K,ce,me,le,m),Pe&&(Pe.textContent=`${Math.round(le*100)}%`)}let ne=new ResizeObserver(()=>Q());ne.observe(Ie),he(),ce.src=n[p].url,requestAnimationFrame(()=>Q());function ae(){x||(x=!0,ne.disconnect(),document.removeEventListener("click",qe),w.remove())}return{element:w,goTo:Ke,next:()=>we(1),prev:()=>we(-1),getIndex:()=>p,setDevice(me){m=me,K.dataset.device=me,xe==null||xe.setSelected(me),u=null,Q()},setColorScheme(me){g=me,K.dataset.colorScheme=me},setZoom(me){u=me,Q()},destroy:ae}}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 Db(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Bb,document.head.appendChild(e)}function Nb(e,t){let n=e.clientWidth-Zl*2-Ag,r=e.clientHeight-Zl*2-Ag;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Ob(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 Sg(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");Db();let p=Math.max(0,Math.min(r,n.length-1)),u=s,f=o,m=null,v=1,x=!1,w=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),B=h("div","persona-dc-toolbar-lead"),k=h("div","persona-dc-toolbar-trail"),P=Vt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Se(-1)}),W=h("div");W.style.position="relative";let S=h("button","persona-dc-title-btn");S.type="button",S.setAttribute("aria-expanded","false"),S.setAttribute("aria-haspopup","listbox");let I=h("span","persona-dc-title-text"),$=h("span","persona-dc-title-chevron"),D=we("chevron-down",12,"currentColor",2);D&&$.appendChild(D),S.append(I,$);let R=h("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let q=!1;function K(){R.innerHTML="";for(let xe=0;xe<n.length;xe++){let me=n[xe],oe=h("button","persona-dc-dropdown-item");oe.type="button",oe.setAttribute("role","option"),oe.setAttribute("aria-current",xe===p?"true":"false");let Ze=h("span");if(Ze.textContent=me.title,oe.appendChild(Ze),me.description){let We=h("span","persona-dc-dropdown-desc");We.textContent=me.description,oe.appendChild(We)}oe.addEventListener("click",()=>{Re(),ze(xe)}),R.appendChild(oe)}}function se(){q=!q,R.style.display=q?"":"none",S.setAttribute("aria-expanded",q?"true":"false"),q&&K()}function Re(){q&&(q=!1,R.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",xe=>{xe.stopPropagation(),se()});let Ge=()=>Re();document.addEventListener("click",Ge),W.append(S,R);let Ce=Vt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Se(1)}),He=h("span","persona-dc-counter");B.append(P,W,Ce,He);let be=null;i&&(be=da({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:xe=>{u=xe,V.dataset.device=u,m=null,Y()}}),k.appendChild(be.element));let Be=null;if(a){let xe=h("div","persona-dc-zoom-controls"),me=Vt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let We=m!=null?m:v;m=Math.max(wg,We-vg),Y()}});Be=h("span","persona-dc-zoom-level"),Be.title="Reset to 100%",Be.style.cursor="pointer",Be.addEventListener("click",()=>{m=1,Y()});let oe=Vt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let We=m!=null?m:v;m=Math.min(Cg,We+vg),Y()}}),Ze=Vt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,Y()}});xe.append(me,Be,oe,Ze),k.appendChild(xe)}if(d){let xe=h("div","persona-dc-separator");k.appendChild(xe);let me=da({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:oe=>{f=oe,V.dataset.colorScheme=f,le()}});k.appendChild(me.element)}let Pe=h("div","persona-dc-separator");k.appendChild(Pe);let J=Vt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(J),T.append(B,k);let ue=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=u,V.dataset.colorScheme=f;let de=h("iframe","persona-dc-iframe");de.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),de.setAttribute("loading","lazy"),de.title=n[p].title,V.appendChild(de),ue.appendChild(V),w.append(T,ue),e.appendChild(w);function le(){var xe;try{let me=(xe=de.contentDocument)==null?void 0:xe.body;if(!me)return;f==="dark"?me.classList.add("theme-dark"):me.classList.remove("theme-dark")}catch{}}de.addEventListener("load",()=>le());function ae(){let xe=n[p];I.textContent=xe.title,He.textContent=`${p+1} / ${n.length}`,de.title=xe.title}function Se(xe){let me=((p+xe)%n.length+n.length)%n.length;ze(me)}function ze(xe){xe<0||xe>=n.length||(p=xe,de.src=n[p].url,ae(),l==null||l(p,n[p]))}function Y(){var oe;if(x)return;let xe=(oe=xg[u])!=null?oe:xg.desktop;v=Nb(ue,xe);let me=Math.max(wg,Math.min(Cg,m!=null?m:v));Ob(V,de,xe,me,u),Be&&(Be.textContent=`${Math.round(me*100)}%`)}let ne=new ResizeObserver(()=>Y());ne.observe(ue),ae(),de.src=n[p].url,requestAnimationFrame(()=>Y());function ce(){x||(x=!0,ne.disconnect(),document.removeEventListener("click",Ge),w.remove())}return{element:w,goTo:ze,next:()=>Se(1),prev:()=>Se(-1),getIndex:()=>p,setDevice(xe){u=xe,V.dataset.device=xe,be==null||be.setSelected(xe),m=null,Y()},setColorScheme(xe){f=xe,V.dataset.colorScheme=xe},setZoom(xe){m=xe,Y()},destroy:ce}}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