@runtypelabs/persona 3.29.1 → 3.31.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 (68) hide show
  1. package/README.md +15 -2547
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
  5. package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +6 -6
  9. package/dist/codegen.js +4 -4
  10. package/dist/index.cjs +50 -50
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +164 -7
  13. package/dist/index.d.ts +164 -7
  14. package/dist/index.global.js +60 -60
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +49 -49
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js +2 -2
  19. package/dist/launcher.global.js.map +1 -1
  20. package/dist/plugin-kit.cjs +1 -0
  21. package/dist/plugin-kit.d.cts +98 -0
  22. package/dist/plugin-kit.d.ts +98 -0
  23. package/dist/plugin-kit.js +1 -0
  24. package/dist/smart-dom-reader.d.cts +157 -4
  25. package/dist/smart-dom-reader.d.ts +157 -4
  26. package/dist/theme-editor.cjs +40 -40
  27. package/dist/theme-editor.d.cts +161 -6
  28. package/dist/theme-editor.d.ts +161 -6
  29. package/dist/theme-editor.js +40 -40
  30. package/dist/theme-reference.cjs +1 -1
  31. package/dist/theme-reference.d.cts +2 -0
  32. package/dist/theme-reference.d.ts +2 -0
  33. package/dist/theme-reference.js +1 -1
  34. package/dist/widget.css +19 -0
  35. package/package.json +8 -2
  36. package/src/client.ts +6 -0
  37. package/src/components/approval-bubble.test.ts +320 -0
  38. package/src/components/approval-bubble.ts +190 -20
  39. package/src/components/launcher.ts +6 -3
  40. package/src/components/panel.ts +7 -1
  41. package/src/components/tool-bubble.test.ts +39 -0
  42. package/src/components/tool-bubble.ts +4 -0
  43. package/src/defaults.ts +14 -0
  44. package/src/generated/runtype-openapi-contract.ts +4 -0
  45. package/src/index-core.ts +1 -0
  46. package/src/plugin-kit.test.ts +230 -0
  47. package/src/plugin-kit.ts +294 -0
  48. package/src/plugins/types.ts +49 -2
  49. package/src/session.test.ts +161 -0
  50. package/src/session.ts +41 -3
  51. package/src/styles/widget.css +19 -0
  52. package/src/theme-editor/preview-utils.test.ts +10 -0
  53. package/src/theme-editor/preview-utils.ts +29 -1
  54. package/src/theme-editor/sections.test.ts +17 -0
  55. package/src/theme-editor/sections.ts +31 -0
  56. package/src/theme-reference.ts +2 -2
  57. package/src/types/theme.ts +2 -0
  58. package/src/types.ts +109 -2
  59. package/src/ui.approval-plugin.test.ts +204 -0
  60. package/src/ui.scroll.test.ts +383 -0
  61. package/src/ui.ts +539 -56
  62. package/src/utils/auto-follow.test.ts +91 -0
  63. package/src/utils/auto-follow.ts +68 -0
  64. package/src/utils/theme.test.ts +6 -2
  65. package/src/utils/theme.ts +0 -8
  66. package/src/utils/tokens.ts +6 -1
  67. package/src/webmcp-bridge.test.ts +66 -0
  68. 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 rf=Object.create;var za=Object.defineProperty;var of=Object.getOwnPropertyDescriptor;var sf=Object.getOwnPropertyNames;var af=Object.getPrototypeOf,lf=Object.prototype.hasOwnProperty;var cf=(e,t)=>{for(var n in t)za(e,n,{get:t[n],enumerable:!0})},wu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sf(t))!lf.call(e,o)&&o!==n&&za(e,o,{get:()=>t[o],enumerable:!(r=of(t,o))||r.enumerable});return e};var Cu=(e,t,n)=>(n=e!=null?rf(af(e)):{},wu(t||!e||!e.__esModule?za(n,"default",{value:e,enumerable:!0}):n,e)),df=e=>wu(za({},"__esModule",{value:!0}),e);var by={};cf(by,{ASK_USER_QUESTION_TOOL_NAME:()=>Bl,AgentWidgetClient:()=>zo,AgentWidgetSession:()=>vs,AttachmentManager:()=>Go,DEFAULT_COMPONENTS:()=>bl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>di,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>er,DEFAULT_PALETTE:()=>fl,DEFAULT_SEMANTIC:()=>hl,DEFAULT_WIDGET_CONFIG:()=>Ft,PRESETS:()=>lc,PRESET_FULLSCREEN:()=>ic,PRESET_MINIMAL:()=>ac,PRESET_SHOP:()=>sc,THEME_ZONES:()=>em,VERSION:()=>ns,WEBMCP_TOOL_PREFIX:()=>Kr,WebMcpBridge:()=>bs,accessibilityPlugin:()=>Pg,animationsPlugin:()=>Ig,applyThemeVariables:()=>xo,attachHeaderToContainer:()=>Qo,brandPlugin:()=>Wg,buildComposer:()=>Ts,buildDefaultHeader:()=>Tl,buildHeader:()=>Qr,buildHeaderWithLayout:()=>Ss,buildMinimalHeader:()=>El,collectEnrichedPageContext:()=>Mg,componentRegistry:()=>eo,createActionManager:()=>Ta,createAgentExperience:()=>Xi,createAskUserQuestionBubble:()=>Fm,createBestAvailableVoiceProvider:()=>li,createBubbleWithLayout:()=>Sm,createCSATFeedback:()=>Ki,createComboButton:()=>Ei,createComponentMiddleware:()=>ig,createComponentStreamParser:()=>Ui,createDefaultSanitizer:()=>dl,createDemoCarousel:()=>Qg,createDirectivePostprocessor:()=>Mu,createDropdownMenu:()=>Ao,createFlexibleJsonStreamParser:()=>Bu,createIconButton:()=>Kt,createImagePart:()=>ju,createJsonStreamParser:()=>ei,createLabelButton:()=>ba,createLocalStorageAdapter:()=>ji,createMarkdownProcessor:()=>ta,createMarkdownProcessorFromConfig:()=>jo,createMessageActions:()=>Il,createNPSFeedback:()=>Ji,createPlainTextParser:()=>Ya,createPlugin:()=>Bg,createRegexJsonParser:()=>Za,createStandardBubble:()=>Es,createTextPart:()=>oa,createTheme:()=>Cs,createThemeObserver:()=>gi,createToggleGroup:()=>ya,createTypingIndicator:()=>Yo,createVoiceProvider:()=>Jo,createWidgetHostLayout:()=>Ea,createXmlParser:()=>ti,default:()=>Og,defaultActionHandlers:()=>ts,defaultJsonActionParser:()=>Sa,defaultParseRules:()=>rc,detectColorScheme:()=>ca,directivePostprocessor:()=>ku,ensureAskUserQuestionSheet:()=>Is,escapeHtml:()=>Uo,extractComponentDirectiveFromMessage:()=>Vi,fileToImagePart:()=>Uu,formatEnrichedContext:()=>kg,generateAssistantMessageId:()=>Vo,generateCodeSnippet:()=>qg,generateMessageId:()=>Nu,generateStableSelector:()=>oc,generateUserMessageId:()=>xs,getActiveTheme:()=>As,getColorScheme:()=>xl,getDisplayText:()=>Fu,getHeaderLayout:()=>Ml,getImageParts:()=>_u,getPreset:()=>Ng,hasComponentDirective:()=>zi,hasImages:()=>$u,headerLayouts:()=>Mi,highContrastPlugin:()=>Hg,initAgentWidget:()=>Zl,isAskUserQuestionMessage:()=>Yr,isComponentDirectiveType:()=>ag,isDockedMountMode:()=>gn,isVoiceSupported:()=>aa,isWebMcpToolName:()=>yo,listRegisteredStreamAnimations:()=>hm,markdownPostprocessor:()=>cl,mergeWithDefaults:()=>pi,normalizeContent:()=>Ou,parseAskUserQuestionPayload:()=>Zr,pluginRegistry:()=>Aa,reducedMotionPlugin:()=>Rg,registerStreamAnimationPlugin:()=>gm,removeAskUserQuestionSheet:()=>Eo,renderComponentDirective:()=>qi,renderLoadingIndicatorWithFallback:()=>Pl,renderLucideIcon:()=>Ce,resolveDockConfig:()=>mr,resolveSanitizer:()=>hs,resolveTokens:()=>ui,stripWebMcpPrefix:()=>Ka,themeToCssVariables:()=>mi,unregisterStreamAnimationPlugin:()=>fm,validateImageFile:()=>qu,validateTheme:()=>yl});module.exports=df(by);var Su=require("marked"),pf=e=>{if(e)return e},ta=e=>{var o,s;let t=e==null?void 0:e.markedOptions,n=new Su.Marked({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=pf(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},jo=e=>e?ta({markedOptions:e.options,renderer:e.renderer}):ta(),uf=ta(),cl=e=>uf(e),Uo=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;"),Au=e=>`%%FORM_PLACEHOLDER_${e}%%`,Eu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Au(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Au(t.length);return t.push({token:s,type:o}),s}),n},Mu=e=>{let t=jo(e);return n=>{let r=[],o=Eu(n,r),s=t(o);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>`;s=s.replace(d,p)}),s}},ku=e=>{let t=[],n=Eu(e,t),r=cl(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Tu(s)}"></div>`;r=r.replace(a,d)}),r};var Lu=Cu(require("dompurify"),1),mf={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"]},gf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,dl=()=>{let e=(0,Lu.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:")&&!gf.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,mf)},hs=e=>e===!1?null:typeof e=="function"?e:dl();var Kr="webmcp:",pl=new Map,Pu=e=>{var t;pl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&pl.set(n.name,r)}},ul=e=>pl.get(Ka(e)),Va={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Wu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${ff(t.join(""))}`}function Iu(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,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 ff(e){let t=Iu(e,0).toString(36),n=Iu(e,2654435761).toString(36);return`${t}.${n}`}var bs=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(o){return Va.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}Pu(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=bf(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return Ar("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return Ar(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 s=Ka(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return Ar(`Failed to read WebMCP registry: ${x}`)}Pu(a);let i=a.find(v=>v.name===s);if(!i)return Ar(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ar(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let d=ul(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Ar("User declined the tool call.");if(r!=null&&r.aborted)return Ar("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 o.executeTool(i,wf(n),{signal:p.signal});return yf(v)}catch(v){if(u)return Ar(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return Ar(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){Va.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,Va.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:xf;try{return await n(t)}catch(o){return Va.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>hf(t,r))}},Ka=e=>e.startsWith(Kr)?e.slice(Kr.length):e,yo=e=>e.startsWith(Kr),hf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},bf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},yf=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:Cf(t)}]}},Ar=e=>({isError:!0,content:[{type:"text",text:e}]}),xf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=vf(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,`
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(`
6
+ ${e.description}`:"");return window.confirm(n)},vf=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)}},wf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Cf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Jr=require("partial-json"),Ja=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ys=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)}},Af=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Ru=e=>e.status==="complete"?Af(e):e.status==="pending"?"Waiting":"",Sf=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Hu=e=>e.status==="complete"?Sf(e):"Using tool...",Ga=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ra=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Ga(t)},Xa=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Ga(t)},ml=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=ra(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&na(r,n.slice(s,a.index),[]),a[1]!==void 0?na(r,a[1],["bold"]):a[2]!==void 0?na(r,a[2],["italic"]):a[3]!==void 0&&na(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&na(r,n.slice(s),[]),r},na=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Tf=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},qo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ya=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Za=()=>{var t;let e=Tf();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)}},ei=()=>{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 o=(0,Jr.parse)(n,Jr.STR|Jr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Ja(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Ja(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Bu=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ja(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ja(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Jr.parse)(s,Jr.STR|Jr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ti=()=>{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 ni=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 s,a,i;let r=(i=(s=n==null?void 0:n.seq)!=null?s: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 o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.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 Ef="https://api.runtype.com/v1/dispatch",ri="https://api.runtype.com";function Mf(e){var s,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 o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var gl=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 kf(e){switch(e){case"json":return ei;case"regex-json":return Za;case"xml":return ti;default:return Ya}}var Du=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lf(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 o=Du(n);if(!Du(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=qo(e);return qo(t)!==null&&a===null?t:e}var zo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=t.apiUrl)!=null?n:Ef,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:kf(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new bs(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$/,""))||ri}/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 s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,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$/,""))||ri}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(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 o,s,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(),(s=(o=this.config).onSessionExpired)==null||s.call(o);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,u={sessionId:d.sessionId,messages:t.messages.filter(gl).map(I=>{var W,S,k;return{id:I.id,role:I.role,content:(k=(S=(W=I.contentParts)!=null?W:I.llmContent)!=null?S:I.rawContent)!=null?k: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}},f=l.clientTools,m=!!(f&&f.length>0),v=m?Wu(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,w=m&&x&&this.lastSentClientToolsFingerprint===v,T=!1,N=null,M;for(let I=0;;I++){let S={...u,...m&&(T||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),M.status===409&&I===0&&m){let k=await M.json().catch(()=>null);if((k==null?void 0:k.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}N=k!=null?k:{error:"Chat request failed"}}break}if(!M.ok){let I=N!=null?N:await M.json().catch(()=>({error:"Chat request failed"}));if(M.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(M.status===429){let S=new Error(I.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let W=new Error(I.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!M.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(M.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 o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw 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 o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw 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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ri}/resume`,a;o&&(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(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(gl).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}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(r.clientTools=o),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 s;let r={messages:t.slice().filter(gl).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}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(r.clientTools=o),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,o,s,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:s(),...p!==void 0&&{partId:p}};return r.current=u,o(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,o(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,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(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 Bt,ln,nr,Tr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=R=>{let pe=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,Ne=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,Ge=R.tools?R.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{...R,reasoning:pe,toolCall:Ne,tools:Ge}},u=R=>{if(R.role!=="assistant"||R.variant)return!0;let pe=Array.isArray(R.contentParts)&&R.contentParts.length>0,Ne=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||pe||Ne||!!R.stopReason},f=R=>{u(R)&&n({type:"message",message:p(R)})},m=null,v=null,x={current:null},w={current:null},T=!1,N=new Map,M=new Map,I=new Map,W=new Map,S={lastId:null,byStep:new Map},k={lastId:null,byCall:new Map},$=(R,pe,Ne="")=>`${R}::${pe}::${Ne}`,O=(R,pe)=>`${R}::${pe}::`,H=(R,pe,Ne,Ge)=>{let $e=$(R,pe,Ne),je=I.get($e);if(je)return je;let st=Ne?`-${Ne}`:"",It={id:`nested-${R}-${pe}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ne?{partId:Ne}:{},agentMetadata:{executionId:Ge,parentToolId:R,parentStepId:pe}};return I.set($e,It),f(It),It},U=R=>{if(R==null)return null;try{return String(R)}catch{return null}},J=R=>{var pe,Ne,Ge,$e,je;return U((je=($e=(Ge=(Ne=(pe=R.stepId)!=null?pe:R.step_id)!=null?Ne:R.step)!=null?Ge:R.parentId)!=null?$e:R.flowStepId)!=null?je:R.flow_step_id)},ce=R=>{var pe,Ne,Ge,$e,je,st,It;return U((It=(st=(je=($e=(Ge=(Ne=(pe=R.callId)!=null?pe:R.call_id)!=null?Ne:R.requestId)!=null?Ge:R.request_id)!=null?$e:R.toolCallId)!=null?je:R.tool_call_id)!=null?st:R.stepId)!=null?It:R.step_id)},Me=r,ze=!1,Ae=()=>{if(m)return m;let R;return!ze&&Me?(R=Me,ze=!0):Me&&w.current?R=`${Me}_${w.current}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:R,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},We=(R,pe)=>{S.lastId=pe,R&&S.byStep.set(R,pe)},be=(R,pe)=>{var je;let Ne=(je=R.reasoningId)!=null?je:R.id,Ge=J(R);if(Ne){let st=String(Ne);return We(Ge,st),st}if(Ge){let st=S.byStep.get(Ge);if(st)return S.lastId=st,st}if(S.lastId&&!pe)return S.lastId;if(!pe)return null;let $e=`reason-${l()}`;return We(Ge,$e),$e},ke=R=>{let pe=N.get(R);if(pe)return pe;let Ne={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:R,status:"streaming",chunks:[]}};return N.set(R,Ne),f(Ne),Ne},Re=(R,pe)=>{k.lastId=pe,R&&k.byCall.set(R,pe)},de=new Set,Q=new Map,re=new Set,le=new Map,ge=R=>{if(!R)return!1;let pe=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},V=(R,pe)=>{var je;let Ne=(je=R.toolId)!=null?je:R.id,Ge=ce(R);if(Ne){let st=String(Ne);return Re(Ge,st),st}if(Ge){let st=k.byCall.get(Ge);if(st)return k.lastId=st,st}if(k.lastId&&!pe)return k.lastId;if(!pe)return null;let $e=`tool-${l()}`;return Re(Ge,$e),$e},se=R=>{let pe=M.get(R);if(pe)return pe;let Ne={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:R,status:"pending"}};return M.set(R,Ne),f(Ne),Ne},He=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let pe=Number(R);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let Ne=Date.parse(R);if(!Number.isNaN(Ne))return Ne}return Date.now()},Z=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},ee=new Map,ae=new Map,Se=new Map,Ze=new Map,ve=null,fe=(R,pe,Ne)=>{var It;let Ge=Se.get(R);Ge||(Ge=[],Se.set(R,Ge));let $e=0,je=Ge.length;for(;$e<je;){let Jt=$e+je>>>1;Ge[Jt].seq<pe?$e=Jt+1:je=Jt}((It=Ge[$e])==null?void 0:It.seq)===pe?Ge[$e]={seq:pe,text:Ne}:Ge.splice($e,0,{seq:pe,text:Ne});let st="";for(let Jt=0;Jt<Ge.length;Jt++)st+=Ge[Jt].text;return st},Je=(R,pe)=>{let Ne=Z(pe),Ge=ae.get(R.id),$e=Lf(Ge,Ne);R.rawContent=$e;let je=ee.get(R.id),st=vt=>{var we;let it=(we=R.content)!=null?we:"";vt.trim()!==""&&(it.trim().length===0||vt.startsWith(it)||vt.trimStart().startsWith(it.trim()))&&(R.content=vt)},It=()=>{var vt;if(je){let it=(vt=je.close)==null?void 0:vt.call(je);it instanceof Promise&&it.catch(()=>{})}ee.delete(R.id),ae.delete(R.id),R.streaming=!1,f(R)};if(!je){st(Ne),It();return}let Jt=qo($e);if(Jt!==null&&Jt.trim()!==""){st(Jt),It();return}let Yt=vt=>{var ie;let it=typeof vt=="string"?vt:(ie=vt==null?void 0:vt.text)!=null?ie:null;if(it!==null&&it.trim()!=="")return it;let we=je.getExtractedText();return we!==null&&we.trim()!==""?we:Ne},K;try{K=je.processChunk($e)}catch{st(Ne),It();return}if(K instanceof Promise){K.then(vt=>{st(Yt(vt)),It()}).catch(()=>{st(Ne),It()});return}st(Yt(K)),It()},De=[],z=!1,ue,rt=()=>{z||(z=!0,queueMicrotask(()=>{z=!1,ue()}))},kt=new ni((R,pe)=>{De.push({payloadType:R,payload:pe}),rt()}),te=null,Ve=new Map,Bn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(ue=()=>{var R,pe,Ne,Ge,$e,je,st,It,Jt,Yt,K,vt,it,we,ie,nt,Zt,Gt,kn,xn,ft,Lt,et,zt,cn,wn,Cn,yn,Er,St,_n,jn,Nr,hr,wt,Lo,Mr,Po,Dn,rs,no,Or,Tt,Un,qn,Ln,Pt,rr,or,zn,ro,Fr,oo,Vn,Dt,Pn,sr,so,$r,ao,kr,Kn,br,bt,en,tn,Jn,io,ye,ar,ir,_,Lr,_r,jr,Pr,yr,Bs,Gn,Xn,xr,vr,Io,Ur,An,Ir,os,Wo,ss,ka,as,La,is,xt,Ds,lr,Nn,Pa,Ia,ls,qr,Ns,lo,Os,Fs,$s,_s,On,cs,Wr,Rr,js,Wa,Us,qs,Ro,Ra,Ha,Ba,Da,ol,Ho,co,Na,zs,po,Oa,Vs,uo,Ks,Fa,zr,$a,mo,Nt,ds,ps,Js;for(let cr=0;cr<De.length;cr++){let Xe=De[cr].payloadType,A=De[cr].payload;if(Xe==="reason_start"){let j=(R=be(A,!0))!=null?R:`reason-${l()}`,L=ke(j);L.reasoning=(pe=L.reasoning)!=null?pe:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Ge=L.reasoning.startedAt)!=null?Ge:He((Ne=A.startedAt)!=null?Ne:A.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",f(L)}else if(Xe==="reason_delta"||Xe==="reason_chunk"){let j=(je=($e=be(A,!1))!=null?$e:be(A,!0))!=null?je:`reason-${l()}`,L=ke(j);L.reasoning=(st=L.reasoning)!=null?st:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Jt=L.reasoning.startedAt)!=null?Jt:He((It=A.startedAt)!=null?It:A.timestamp);let Y=(vt=(K=(Yt=A.reasoningText)!=null?Yt:A.text)!=null?K:A.delta)!=null?vt:"";if(Y&&A.hidden!==!0){let oe=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(oe!==void 0){let G=fe(j,oe,String(Y));L.reasoning.chunks=[G]}else L.reasoning.chunks.push(String(Y))}if(L.reasoning.status=A.done?"complete":"streaming",A.done){L.reasoning.completedAt=He((it=A.completedAt)!=null?it:A.timestamp);let oe=(we=L.reasoning.startedAt)!=null?we:Date.now();L.reasoning.durationMs=Math.max(0,((ie=L.reasoning.completedAt)!=null?ie:Date.now())-oe)}L.streaming=L.reasoning.status!=="complete",f(L)}else if(Xe==="reason_complete"){let j=(Zt=(nt=be(A,!1))!=null?nt:be(A,!0))!=null?Zt:`reason-${l()}`,L=N.get(j);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=He((Gt=A.completedAt)!=null?Gt:A.timestamp);let oe=(kn=L.reasoning.startedAt)!=null?kn:Date.now();L.reasoning.durationMs=Math.max(0,((xn=L.reasoning.completedAt)!=null?xn:Date.now())-oe),L.streaming=!1,f(L)}let Y=J(A);Y&&S.byStep.delete(Y)}else if(Xe==="tool_start"){let j=(ft=V(A,!0))!=null?ft:`tool-${l()}`,L=(Lt=A.toolName)!=null?Lt:A.name;if(ge(L)){de.add(j);continue}let Y=se(j),oe=(et=Y.toolCall)!=null?et:{id:j,status:"pending"};oe.name=L!=null?L:oe.name,oe.status="running",A.args!==void 0?oe.args=A.args:A.parameters!==void 0&&(oe.args=A.parameters),oe.startedAt=(cn=oe.startedAt)!=null?cn:He((zt=A.startedAt)!=null?zt:A.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Y.toolCall=oe,Y.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(Y.agentMetadata={executionId:(wn=G==null?void 0:G.executionId)!=null?wn:A.executionId,iteration:(Cn=G==null?void 0:G.iteration)!=null?Cn:A.iteration}),f(Y)}else if(Xe==="tool_chunk"||Xe==="tool_delta"){let j=(Er=(yn=V(A,!1))!=null?yn:V(A,!0))!=null?Er:`tool-${l()}`;if(de.has(j))continue;let L=se(j),Y=(St=L.toolCall)!=null?St:{id:j,status:"running"};Y.startedAt=(jn=Y.startedAt)!=null?jn:He((_n=A.startedAt)!=null?_n:A.timestamp);let oe=(wt=(hr=(Nr=A.text)!=null?Nr:A.delta)!=null?hr:A.message)!=null?wt:"";oe&&(Y.chunks=(Lo=Y.chunks)!=null?Lo:[],Y.chunks.push(String(oe))),Y.status="running",L.toolCall=Y,L.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(L.agentMetadata=(Dn=L.agentMetadata)!=null?Dn:{executionId:(Mr=G==null?void 0:G.executionId)!=null?Mr:A.executionId,iteration:(Po=G==null?void 0:G.iteration)!=null?Po:A.iteration}),f(L)}else if(Xe==="tool_complete"){let j=(no=(rs=V(A,!1))!=null?rs:V(A,!0))!=null?no:`tool-${l()}`;if(de.has(j)){de.delete(j);continue}let L=se(j),Y=(Or=L.toolCall)!=null?Or:{id:j,status:"running"};Y.status="complete",A.result!==void 0&&(Y.result=A.result),typeof A.duration=="number"&&(Y.duration=A.duration),Y.completedAt=He((Tt=A.completedAt)!=null?Tt:A.timestamp);let oe=(Un=A.duration)!=null?Un:A.executionTime;if(typeof oe=="number")Y.durationMs=oe;else{let Fe=(qn=Y.startedAt)!=null?qn:Date.now();Y.durationMs=Math.max(0,((Ln=Y.completedAt)!=null?Ln:Date.now())-Fe)}L.toolCall=Y,L.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(L.agentMetadata=(or=L.agentMetadata)!=null?or:{executionId:(Pt=G==null?void 0:G.executionId)!=null?Pt:A.executionId,iteration:(rr=G==null?void 0:G.iteration)!=null?rr:A.iteration}),f(L);let Pe=ce(A);Pe&&k.byCall.delete(Pe)}else if(Xe==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let j=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,L=(zn=j!=null?j:A.toolId)!=null?zn:`local-${l()}`,Y=se(L),oe=A.toolName,G=yo(oe),Pe=(ro=Y.toolCall)!=null?ro:{id:L,status:"pending"};Pe.name=oe,Pe.args=A.parameters,Pe.status=G?"running":"complete",Pe.chunks=(Fr=Pe.chunks)!=null?Fr:[],Pe.startedAt=(Vn=Pe.startedAt)!=null?Vn:He((oo=A.startedAt)!=null?oo:A.timestamp),G?(Pe.completedAt=void 0,Pe.duration=void 0,Pe.durationMs=void 0):Pe.completedAt=(Dt=Pe.completedAt)!=null?Dt:Pe.startedAt,Y.toolCall=Pe,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(sr=A.executionId)!=null?sr:(Pn=Y.agentMetadata)==null?void 0:Pn.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},f(Y)}else if(Xe==="text_start"){if((so=A.toolContext)!=null&&so.toolId)continue;let j=A.partId;if(j!==void 0&&w.current!==null&&j!==w.current){let L=m;L&&(L.streaming=!1,f(L),ve=L,m=null,T=!0)}j!==void 0&&(w.current=j)}else if(Xe==="text_end"){if(($r=A.toolContext)!=null&&$r.toolId)continue;let j=m;j&&(j.streaming=!1,f(j),ve=j,m=null,T=!0)}else if(Xe==="step_chunk"||Xe==="step_delta"){let j=A.stepType,L=A.executionType;if(j==="tool"||L==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Fe=String((kr=(ao=A.id)!=null?ao:Y.stepId)!=null?kr:`step-${l()}`),lt=A.partId!==void 0&&A.partId!==null?String(A.partId):"",tt=`${Y.toolId}::${Fe}`,Ht=W.get(tt);if(lt!==""&&Ht!==void 0&&Ht!==""&&Ht!==lt){let ct=I.get($(Y.toolId,Fe,Ht));ct&&ct.streaming!==!1&&(ct.streaming=!1,f(ct))}lt!==""&&W.set(tt,lt);let jt=H(Y.toolId,Fe,lt,Y.executionId),$t=(en=(bt=(br=(Kn=A.text)!=null?Kn:A.delta)!=null?br:A.content)!=null?bt:A.chunk)!=null?en:"";$t&&(jt.content+=String($t),jt.streaming=!0,f(jt)),A.isComplete&&(jt.streaming=!1,f(jt));continue}let oe=A.partId;if(oe!==void 0&&w.current!==null&&oe!==w.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),ve=Fe,m=null,T=!0)}oe!==void 0&&(w.current=oe);let G=oe!==void 0&&(tn=Ze.get(oe))!=null?tn:Ae();oe!==void 0&&(G.partId||(G.partId=oe),Ze.set(oe,G));let Pe=(ar=(ye=(io=(Jn=A.text)!=null?Jn:A.delta)!=null?io:A.content)!=null?ye:A.chunk)!=null?ar:"";if(Pe){let Fe=typeof A.seq=="number"?A.seq:void 0,lt=oe!=null?oe:G.id,tt=Fe!==void 0?fe(lt,Fe,String(Pe)):((ir=ae.get(G.id))!=null?ir:"")+Pe;G.rawContent=tt,ee.has(G.id)||ee.set(G.id,this.createStreamParser());let Ht=ee.get(G.id),jt=tt.trim().startsWith("{")||tt.trim().startsWith("[");if(jt&&ae.set(G.id,tt),Ht.__isPlainTextParser===!0){G.content=Fe!==void 0?tt:G.content+Pe,ae.delete(G.id),ee.delete(G.id),G.rawContent=void 0,f(G);continue}let ct=Ht.processChunk(tt);if(ct instanceof Promise)ct.then(Et=>{var Sn;let Ue=typeof Et=="string"?Et:(Sn=Et==null?void 0:Et.text)!=null?Sn:null;if(Ue!==null&&Ue.trim()!=="")G.content=Ue,f(G);else if(!jt&&!tt.trim().startsWith("<")){let fn=m,Ut=fn&&fn.id===G.id?fn:G;Ut.id===G.id&&(Ut.content=Fe!==void 0?tt:Ut.content+Pe,ae.delete(Ut.id),ee.delete(Ut.id),Ut.rawContent=void 0,f(Ut))}}).catch(()=>{G.content=Fe!==void 0?tt:G.content+Pe,ae.delete(G.id),ee.delete(G.id),G.rawContent=void 0,f(G)});else{let Et=typeof ct=="string"?ct:(_=ct==null?void 0:ct.text)!=null?_:null;Et!==null&&Et.trim()!==""?(G.content=Et,f(G)):!jt&&!tt.trim().startsWith("<")&&(G.content=Fe!==void 0?tt:G.content+Pe,ae.delete(G.id),ee.delete(G.id),G.rawContent=void 0,f(G))}}if(A.isComplete){let Fe=(_r=(Lr=A.result)==null?void 0:Lr.response)!=null?_r:G.content;if(Fe){let lt=ae.get(G.id),tt=lt!=null?lt:Z(Fe);G.rawContent=tt;let Ht=ee.get(G.id),jt=null,$t=!1;if(Ht&&(jt=Ht.getExtractedText(),jt===null&&(jt=qo(tt)),jt===null)){let ct=Ht.processChunk(tt);ct instanceof Promise?($t=!0,ct.then(Et=>{var Sn;let Ue=typeof Et=="string"?Et:(Sn=Et==null?void 0:Et.text)!=null?Sn:null;if(Ue!==null){let fn=m;fn&&fn.id===G.id&&(fn.content=Ue,fn.streaming=!1,ee.delete(fn.id),ae.delete(fn.id),f(fn))}})):jt=typeof ct=="string"?ct:(jr=ct==null?void 0:ct.text)!=null?jr:null}if(!$t){jt!==null&&jt.trim()!==""?G.content=jt:ae.has(G.id)||(G.content=Z(Fe));let ct=ee.get(G.id);if(ct){let Et=(Pr=ct.close)==null?void 0:Pr.call(ct);Et instanceof Promise&&Et.catch(()=>{}),ee.delete(G.id)}ae.delete(G.id),G.streaming=!1,f(G)}}}}else if(Xe==="step_complete"){let j=A.stepType,L=A.executionType;if(j==="tool"||L==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Fe=String((Bs=(yr=A.id)!=null?yr:Y.stepId)!=null?Bs:"");if(Fe){let lt=O(Y.toolId,Fe);for(let[tt,Ht]of I)tt.startsWith(lt)&&Ht.streaming!==!1&&(Ht.streaming=!1,f(Ht));W.delete(`${Y.toolId}::${Fe}`)}continue}let oe=A.stopReason;if(T){if(m!==null){let tt=m;oe&&(tt.stopReason=oe),ee.delete(tt.id),ae.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,f(tt))}let Fe=(Gn=A.result)==null?void 0:Gn.response,lt=ve;lt&&(oe&&(lt.stopReason=oe),Fe!=null?Je(lt,Fe):(ee.delete(lt.id),ae.delete(lt.id))),ve=null;continue}let G=(Xn=A.result)==null?void 0:Xn.response,Pe=Ae();if(oe&&(Pe.stopReason=oe),G!=null){let Fe=ee.get(Pe.id),lt=!1,tt=!1;if(Fe){let Ht=Fe.getExtractedText(),jt=ae.get(Pe.id),$t=jt!=null?jt:Z(G);if(Pe.rawContent=$t,Ht!==null&&Ht.trim()!=="")Pe.content=Ht,lt=!0;else{let ct=qo($t);if(ct!==null)Pe.content=ct,lt=!0;else{let Et=Fe.processChunk($t);if(Et instanceof Promise)tt=!0,Et.then(Ue=>{var fn;let Sn=typeof Ue=="string"?Ue:(fn=Ue==null?void 0:Ue.text)!=null?fn:null;if(Sn!==null&&Sn.trim()!==""){let Ut=m;Ut&&Ut.id===Pe.id&&(Ut.content=Sn,Ut.streaming=!1,ee.delete(Ut.id),ae.delete(Ut.id),f(Ut))}else{let Ut=Fe.getExtractedText(),wr=m;wr&&wr.id===Pe.id&&(Ut!==null&&Ut.trim()!==""?wr.content=Ut:ae.has(wr.id)||(wr.content=Z(G)),wr.streaming=!1,ee.delete(wr.id),ae.delete(wr.id),f(wr))}});else{let Ue=typeof Et=="string"?Et:(xr=Et==null?void 0:Et.text)!=null?xr:null;if(Ue!==null&&Ue.trim()!=="")Pe.content=Ue,lt=!0;else{let Sn=Fe.getExtractedText();Sn!==null&&Sn.trim()!==""&&(Pe.content=Sn,lt=!0)}}}}}if(!tt){if(!Pe.rawContent){let Ht=ae.get(Pe.id);Pe.rawContent=Ht!=null?Ht:Z(G)}if(!lt&&!ae.has(Pe.id)&&(Pe.content=Z(G)),Fe){let Ht=(vr=Fe.close)==null?void 0:vr.call(Fe);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(Pe.id),ae.delete(Pe.id),Pe.streaming=!1,f(Pe)}}else ee.delete(Pe.id),ae.delete(Pe.id),Pe.streaming=!1,f(Pe)}else if(Xe==="flow_complete"){let j=(Io=A.result)==null?void 0:Io.response;if(T){if(m!==null){let L=m;ee.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}}else if(j!=null){let L=Ae(),Y=ae.get(L.id),oe=Y!=null?Y:Z(j);L.rawContent=oe;let G=Z(j),Pe=ee.get(L.id);if(Pe){let tt=qo(oe);if(tt!==null)G=tt;else{let Ht=Pe.processChunk(oe);Ht instanceof Promise&&Ht.then($t=>{var Et;let ct=typeof $t=="string"?$t:(Et=$t==null?void 0:$t.text)!=null?Et:null;ct!==null&&(L.content=ct,L.streaming=!1,f(L))});let jt=Pe.getExtractedText();jt!==null&&(G=jt)}}ee.delete(L.id),ae.delete(L.id);let Fe=G!==L.content,lt=L.streaming!==!1;Fe&&(L.content=G),L.streaming=!1,(Fe||lt)&&f(L)}else if(m!==null){let L=m;ee.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}n({type:"status",status:"idle"})}else if(Xe==="agent_start")te={executionId:A.executionId,agentId:(Ur=A.agentId)!=null?Ur:"virtual",agentName:(An=A.agentName)!=null?An:"",status:"running",currentIteration:0,maxTurns:(Ir=A.maxTurns)!=null?Ir:1,startedAt:He(A.startedAt)};else if(Xe==="agent_iteration_start"){if(te&&(te.currentIteration=A.iteration),Bn==="separate"&&A.iteration>1){let j=m;j&&(j.streaming=!1,f(j),Ve.set(A.iteration-1,j),m=null)}}else if(Xe==="agent_turn_start")v=null;else if(Xe==="agent_turn_delta"){if(A.contentType==="text"){let j=Ae();j.content+=(os=A.delta)!=null?os:"",j.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:te==null?void 0:te.agentName},v=j,f(j)}else if(A.contentType==="thinking"){let j=(Wo=A.turnId)!=null?Wo:`agent-think-${A.iteration}`,L=ke(j);L.reasoning=(ss=L.reasoning)!=null?ss:{id:j,status:"streaming",chunks:[]},L.reasoning.chunks.push((ka=A.delta)!=null?ka:""),L.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(L)}else if(A.contentType==="tool_input"){let j=(as=A.toolCallId)!=null?as:k.lastId;if(j){let L=M.get(j);L!=null&&L.toolCall&&(L.toolCall.chunks=(La=L.toolCall.chunks)!=null?La:[],L.toolCall.chunks.push((is=A.delta)!=null?is:""),f(L))}}}else if(Xe==="agent_turn_complete"){let j=A.turnId;if(j){let oe=N.get(j);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=He(A.completedAt);let G=(xt=oe.reasoning.startedAt)!=null?xt:Date.now();oe.reasoning.durationMs=Math.max(0,((Ds=oe.reasoning.completedAt)!=null?Ds:Date.now())-G),oe.streaming=!1,f(oe)}}let L=A.stopReason,Y=m!=null?m:v;if(L&&Y!==null){let oe=A.turnId;(!oe||((lr=Y.agentMetadata)==null?void 0:lr.turnId)===oe)&&(Y.stopReason=L,f(Y))}}else if(Xe==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let j=(Nn=A.toolCallId)!=null?Nn:`agent-tool-${l()}`;Re(ce(A),j);let L=se(j),Y=(Pa=L.toolCall)!=null?Pa:{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};Y.name=(ls=(Ia=A.toolName)!=null?Ia:A.name)!=null?ls:Y.name,Y.status="running",A.parameters!==void 0&&(Y.args=A.parameters),Y.startedAt=He((qr=A.startedAt)!=null?qr:A.timestamp),L.toolCall=Y,L.streaming=!0,L.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(L)}else if(Xe==="agent_tool_delta"){let j=(Ns=A.toolCallId)!=null?Ns:k.lastId;if(j){let L=(lo=M.get(j))!=null?lo:se(j);L.toolCall&&(L.toolCall.chunks=(Os=L.toolCall.chunks)!=null?Os:[],L.toolCall.chunks.push((Fs=A.delta)!=null?Fs:""),L.toolCall.status="running",L.streaming=!0,f(L))}}else if(Xe==="agent_tool_complete"){let j=($s=A.toolCallId)!=null?$s:k.lastId;if(j){let L=(_s=M.get(j))!=null?_s:se(j);if(L.toolCall){L.toolCall.status="complete",A.result!==void 0&&(L.toolCall.result=A.result),typeof A.executionTime=="number"&&(L.toolCall.durationMs=A.executionTime),L.toolCall.completedAt=He((On=A.completedAt)!=null?On:A.timestamp),L.streaming=!1,f(L);let Y=ce(A);Y&&k.byCall.delete(Y)}}}else if(Xe==="agent_media"){let j=Array.isArray(A.media)?A.media:[],L=[];for(let Y of j){if(!Y||typeof Y!="object")continue;let oe=Y,G=typeof oe.type=="string"?oe.type:void 0,Pe=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Fe=null,lt="";if(G==="media"){let tt=typeof oe.data=="string"?oe.data:void 0;if(!tt)continue;lt=Pe.length>0?Pe:"application/octet-stream",Fe=`data:${lt};base64,${tt}`}else if(G==="image-url"){let tt=typeof oe.url=="string"?oe.url:void 0;if(!tt)continue;lt=Pe,Fe=tt}else if(G==="file-url"){let tt=typeof oe.url=="string"?oe.url:void 0;if(!tt)continue;lt=Pe,Fe=tt}else continue;if(Fe)if(G==="image-url"||lt.startsWith("image/"))L.push({type:"image",image:Fe,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))L.push({type:"audio",audio:Fe,mimeType:lt});else if(lt.startsWith("video/"))L.push({type:"video",video:Fe,mimeType:lt});else{let tt=lt||"application/octet-stream";L.push({type:"file",data:Fe,mimeType:tt,filename:Mf(tt)})}}if(L.length>0){let Y=l(),oe=A.toolCallId,Pe={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Pe);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,x.current=null}}else if(Xe!=="agent_iteration_complete"){if(Xe==="agent_reflection"||Xe==="agent_reflect"){let j=`agent-reflection-${A.executionId}-${A.iteration}`,L={id:j,role:"assistant",content:(cs=A.reflection)!=null?cs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Wr=A.reflection)!=null?Wr:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(L)}else if(Xe==="agent_complete"){te&&(te.status=A.success?"complete":"error",te.completedAt=He(A.completedAt),te.stopReason=A.stopReason);let j=m;j&&(j.streaming=!1,f(j)),n({type:"status",status:"idle"})}else if(Xe==="agent_error"){let j=typeof A.error=="string"?A.error:(js=(Rr=A.error)==null?void 0:Rr.message)!=null?js:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):n({type:"error",error:new Error(j)})}else if(Xe!=="agent_ping"){if(Xe==="agent_approval_start"){let j=(Wa=A.approvalId)!=null?Wa:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Us=te==null?void 0:te.agentId)!=null?Us:"virtual",executionId:(Ro=(qs=A.executionId)!=null?qs:te==null?void 0:te.executionId)!=null?Ro:"",toolName:(Ra=A.toolName)!=null?Ra:"",toolType:A.toolType,description:(Ba=A.description)!=null?Ba:`Execute ${(Ha=A.toolName)!=null?Ha:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(Xe==="step_await"&&A.awaitReason==="approval_required"){let j=(Da=A.approvalId)!=null?Da:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(ol=te==null?void 0:te.agentId)!=null?ol:"virtual",executionId:(co=(Ho=A.executionId)!=null?Ho:te==null?void 0:te.executionId)!=null?co:"",toolName:(Na=A.toolName)!=null?Na:"",toolType:A.toolType,description:(po=A.description)!=null?po:`Execute ${(zs=A.toolName)!=null?zs:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(Xe==="agent_approval_complete"){let j=A.approvalId;if(j){let Y={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(Oa=A.decision)!=null?Oa:"approved",agentId:(Vs=te==null?void 0:te.agentId)!=null?Vs:"virtual",executionId:(Ks=(uo=A.executionId)!=null?uo:te==null?void 0:te.executionId)!=null?Ks:"",toolName:(Fa=A.toolName)!=null?Fa:"",description:(zr=A.description)!=null?zr:"",resolvedAt:Date.now()}};f(Y)}}else if(Xe==="artifact_start"||Xe==="artifact_delta"||Xe==="artifact_update"||Xe==="artifact_complete"){if(Xe==="artifact_start"){let j=A.artifactType,L=String(A.id),Y=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:L,artifactType:j,title:Y,component:typeof A.component=="string"?A.component:void 0}),le.set(L,{markdown:"",title:Y}),!re.has(L)){re.add(L);let oe={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:L,title:Y,artifactType:j,status:"streaming"}})};Q.set(L,oe),f(oe)}}else if(Xe==="artifact_delta"){let j=String(A.id),L=typeof A.delta=="string"?A.delta:String(($a=A.delta)!=null?$a:"");n({type:"artifact_delta",id:j,artDelta:L});let Y=le.get(j);Y&&(Y.markdown+=L)}else if(Xe==="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(Xe==="artifact_complete"){let j=String(A.id);n({type:"artifact_complete",id:j});let L=Q.get(j);if(L){L.streaming=!1;try{let Y=JSON.parse((mo=L.rawContent)!=null?mo:"{}");if(Y.props){Y.props.status="complete";let oe=le.get(j);oe!=null&&oe.markdown&&(Y.props.markdown=oe.markdown)}L.rawContent=JSON.stringify(Y)}catch{}le.delete(j),f(L),Q.delete(j)}}}else if(Xe==="transcript_insert"){let j=A.message;if(!j||typeof j!="object")continue;let L=String((Nt=j.id)!=null?Nt:`msg-${l()}`),Y=j.role,G={id:L,role:Y==="user"?"user":Y==="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 Pe=JSON.parse(G.rawContent),Fe=(ds=Pe==null?void 0:Pe.props)==null?void 0:ds.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}m=null,x.current=null,ee.delete(L),ae.delete(L)}else if(Xe==="error"||Xe==="step_error"||Xe==="dispatch_error"||Xe==="flow_error"){let j=null;if(A.error instanceof Error)j=A.error;else if(Xe==="dispatch_error"){let L=(ps=A.message)!=null?ps:A.error;L!=null&&L!==""&&(j=new Error(String(L)))}else if(Xe==="step_error"||Xe==="flow_error"){let L=A.error;typeof L=="string"&&L!==""?j=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(j=new Error(String((Js=L.message)!=null?Js:L)))}else Xe==="error"&&A.error!=null&&A.error!==""&&(j=new Error(String(A.error)));if(j){n({type:"error",error:j});let L=m;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}}}}De.length=0};;){let{done:R,value:pe}=await o.read();if(R)break;a+=s.decode(pe,{stream:!0});let Ne=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=(ln=Ne.pop())!=null?ln:"";for(let Ge of Ne){let $e=Ge.split(`
12
+ `),je="message",st="";for(let Yt of $e)Yt.startsWith("event:")?je=Yt.replace("event:","").trim():Yt.startsWith("data:")&&(st+=Yt.replace("data:","").trim());if(!st)continue;let It;try{It=JSON.parse(st)}catch(Yt){n({type:"error",error:Yt instanceof Error?Yt:new Error("Failed to parse chat stream payload")});continue}let Jt=je!=="message"?je:(nr=It.type)!=null?nr:"message";if((Tr=this.onSSEEvent)==null||Tr.call(this,Jt,It),this.parseSSEEvent){x.current=m;let Yt=await this.handleCustomSSEEvent(It,n,x,f,l,w);if(x.current&&x.current!==m&&(m=x.current),Yt)continue}kt.push(Jt,It),ue()}}kt.flushPending(),ue(),kt.destroy()}};function Nu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function xs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Vo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var oi="[Image]";function Ou(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 $u(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function _u(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function oa(e){return{type:"text",text:e}}function ju(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 Uu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function qu(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 zu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Pf=["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"],Gr=[...zu,...Pf];function If(e){return zu.includes(e)||e.startsWith("image/")}function si(e){return If(e.type)}async function Vu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;si(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Ku(e,t=Gr,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 Wf(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Ju(e,t){let n=Wf(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 ai=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(),o=this.pcmToFloat32(n),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let 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),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var ii=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,o,s){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<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var sa=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 ii;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 o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${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 N=T.code!==1006?` (code ${T.code})`:"";x("WebSocket connection failed"+N+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(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(o=>o({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(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(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(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ai(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,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let 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(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(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 s,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=(s=this.config)==null?void 0:s.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),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];n(a)},o.onerror=r,o.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 o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(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 Ko=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=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 Jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new sa(e.runtype);case"browser":if(!Ko.isSupported())throw new Error("Browser speech recognition not supported");return new Ko(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function li(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Jo({type:"runtype",runtype:e.runtype});if(Ko.isSupported())return Jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function aa(e){try{return li(e),!0}catch{return!1}}function Gu(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 ia=e=>({isError:!0,content:[{type:"text",text:e}]}),Xu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,vs=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,o,s,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)&&yo(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:(o=t.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s: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,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new zo(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,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 aa((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,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Jo(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let 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(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(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,o,s,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:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.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 zo(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:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,m={id:a!=null?a:n==="user"?xs():n==="assistant"?Vo():`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,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...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:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:o==="user"?xs():o==="assistant"?Vo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,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:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(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 o=xs(),s=Vo(),a={id:o,role:"user",content:r||oi,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:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let w=Gu(v,this.config.errorMessage);if(w){let T={id:s,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 o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Vo();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=Gu(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=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(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=(s=this.callbacks).onError)==null||a.call(s,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 o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,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 o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,m,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,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:s};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(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.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,N,M,I,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 o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(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,k=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(k.length===1){let $=typeof((w=k[0])==null?void 0:w.question)=="string"?k[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=(N=t.toolCall)==null?void 0:N.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(([k,$])=>`${k}: ${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((k,$)=>{let O=typeof(k==null?void 0:k.question)=="string"?k.question:"";if(!O)return;let H=S[O],U=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${$}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(o,{[s]:n});if(!S.ok){let k=await S.json().catch(()=>null);throw new Error((M=k==null?void 0:k.error)!=null?M:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let k=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(W=(I=this.callbacks).onError)==null||W.call(I,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.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 o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.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 o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.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,o=Date.now()){this.messages.some(s=>s.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:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var I,W,S,k,$,O,H;let f=(I=u.toolCall)==null?void 0:I.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),o.push(w);let T=(k=(S=u.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?k:f,N=this.client.executeWebMcpToolCall(f,($=u.toolCall)==null?void 0:$.args,w.signal),M;if(!N)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await N}catch(U){let J=U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")||U.message.includes("abort"));return J||(H=(O=this.callbacks).onError)==null||H.call(O,U instanceof Error?U:new Error(String(U))),this.markWebMcpToolComplete(u,ia(J?"Aborted by cancel()":Xu(U)),x),this.webMcpInflightKeys.delete(v),null}return w.signal.aborted?(this.markWebMcpToolComplete(u,ia("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:M,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:s.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,ia("Aborted by cancel()"),m.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var m,v,x,w,T,N,M,I,W,S,k,$;let n=(m=t.agentMetadata)==null?void 0:m.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(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(!o){let O=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(O)||this.webMcpResolvedKeys.has(O))return;this.webMcpInflightKeys.add(O);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(O)}catch(H){(M=(N=this.callbacks).onError)==null||M.call(N,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(O)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);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),u="execute",f=a;try{let O;if(p?O=await p:O={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ia("Aborted by cancel()"),a);return}let H=(S=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?S:r;u="resume",await this.resumeWithToolOutput(n,H,O,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,O,a,f)},signal:d})}catch(O){let H=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));(u==="execute"||H||d.aborted)&&this.markWebMcpToolComplete(t,ia(H||d.aborted?"Aborted by cancel()":Xu(O)),a),H||($=(k=this.callbacks).onError)==null||$.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.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 o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};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 o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.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 o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t),s=r.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(o.rate=n.rate),n.pitch!==void 0&&(o.pitch=n.pitch),setTimeout(()=>r.speak(o),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 o of n){let s=t.find(a=>a.name===o);if(s)return s}return(r=t.find(o=>o.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(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,m,v,x,w,T,N,M,I,W,S;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let k=o.approval,$=n.approval;a.approval={...k,...$,executionId:$.executionId||k.executionId,toolName:$.toolName||k.toolName,description:$.description||k.description,toolType:(u=$.toolType)!=null?u:k.toolType,reason:(f=$.reason)!=null?f:k.reason,parameters:(m=$.parameters)!=null?m:k.parameters}}let i=(v=n.toolCall)==null?void 0:v.name,d=(x=n.agentMetadata)==null?void 0:x.executionId,l=(w=n.toolCall)==null?void 0:w.id;if(i&&yo(i)&&d&&l&&((T=n.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let k=`${d}:${l}`,$=this.webMcpInflightKeys.has(k),O=this.webMcpResolvedKeys.has(k),H=(N=o.toolCall)==null?void 0:N.name,U=((M=o.agentMetadata)==null?void 0:M.executionId)===d&&((I=o.toolCall)==null?void 0:I.id)===l&&H!==void 0&&yo(H)&&((W=o.toolCall)==null?void 0:W.status)==="complete";($||O||U)&&(a.agentMetadata={...(S=a.agentMetadata)!=null?S:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.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 o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;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},Br=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var C=require("lucide"),Rf={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},Ce=(e,t=24,n="currentColor",r=2)=>{let o=Rf[e];return o?Hf(o,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 Hf(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var ci={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function Bf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Df(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 Go=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ci.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ci.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ci.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:ci.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,o,s,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=Ku(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Vu(l),f=si(l)?URL.createObjectURL(l):null,m={id:Bf(),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 s,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 o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.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=si(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=Df(t.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Ju(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 o=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),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 Qu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function la(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Qu(s)&&Qu(o)?n[r]=la(s,o):n[r]=o}return n}var er="min(440px, calc(100vw - 24px))",di="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:er,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:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},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 Yu(e,t){if(!(!e&&!t))return e?t?la(e,t):e:t}function pi(e){var t,n,r,o,s,a,i,d,l,p,u,f,m,v,x,w,T,N,M,I,W;return e?{...Ft,...e,theme:Yu(Ft.theme,e.theme),darkTheme:Yu(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(t=Ft.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,Q,re,le,ge,V,se,He,Z,ee;let S=(de=Ft.features)==null?void 0:de.artifacts,k=(Q=e.features)==null?void 0:Q.artifacts,$=(re=Ft.features)==null?void 0:re.scrollToBottom,O=(le=e.features)==null?void 0:le.scrollToBottom,H=(ge=Ft.features)==null?void 0:ge.scrollBehavior,U=(V=e.features)==null?void 0:V.scrollBehavior,J=(se=Ft.features)==null?void 0:se.streamAnimation,ce=(He=e.features)==null?void 0:He.streamAnimation,Me=(Z=Ft.features)==null?void 0:Z.askUserQuestion,ze=(ee=e.features)==null?void 0:ee.askUserQuestion,Ae=S===void 0&&k===void 0?void 0:{...S,...k,layout:{...S==null?void 0:S.layout,...k==null?void 0:k.layout}},We=$===void 0&&O===void 0?void 0:{...$,...O},be=H===void 0&&U===void 0?void 0:{...H,...U},ke=J===void 0&&ce===void 0?void 0:{...J,...ce},Re=Me===void 0&&ze===void 0?void 0:{...Me,...ze,styles:{...Me==null?void 0:Me.styles,...ze==null?void 0:ze.styles}};return{...Ft.features,...e.features,...We!==void 0?{scrollToBottom:We}:{},...be!==void 0?{scrollBehavior:be}:{},...Ae!==void 0?{artifacts:Ae}:{},...ke!==void 0?{streamAnimation:ke}:{},...Re!==void 0?{askUserQuestion:Re}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Ft.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=Ft.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:{...(N=Ft.layout)==null?void 0:N.slots,...(M=e.layout)==null?void 0:M.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(I=Ft.markdown)==null?void 0:I.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var fl={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"}},hl={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"}},bl={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:er,maxWidth:di,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 ws(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ws(e,r):r}function ui(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ws(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function yl(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 Zu(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Zu(s,o):n[r]=o}return n}function Nf(e,t){return t?Zu(e,t):e}function Cs(e,t={}){var o,s,a,i,d,l,p,u,f,m,v,x,w;let n={palette:fl,semantic:hl,components:bl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.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:Nf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=yl(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(N=>N.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function mi(e){var x,w,T,N,M,I,W,S,k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re,de,Q,re,le,ge,V,se,He,Z,ee,ae,Se,Ze,ve,fe,Je,De,z,ue,rt,kt,te,Ve,Bn,Bt,ln,nr,Tr,R,pe,Ne,Ge,$e,je,st,It,Jt,Yt,K,vt,it,we,ie,nt,Zt,Gt,kn,xn,ft,Lt,et,zt,cn,wn,Cn,yn,Er,St,_n,jn,Nr,hr,wt,Lo,Mr,Po,Dn,rs,no,Or,Tt,Un,qn,Ln,Pt,rr,or,zn,ro,Fr,oo,Vn,Dt,Pn,sr,so,$r,ao,kr,Kn,br,bt,en,tn,Jn,io;let t=ui(e),n={};for(let[ye,ar]of Object.entries(t)){let ir=ye.replace(/\./g,"-");n[`--persona-${ir}`]=ar.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"]=(N=n["--persona-semantic-colors-surface"])!=null?N:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(M=n["--persona-semantic-colors-background"])!=null?M: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"]=(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"]=(k=n["--persona-semantic-colors-text-inverse"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-border"]=($=n["--persona-semantic-colors-border"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(O=n["--persona-semantic-colors-divider"])!=null?O: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"]=(U=n["--persona-components-voice-recording-background"])!=null?U:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(J=n["--persona-components-voice-processing-icon"])!=null?J:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ce=n["--persona-components-voice-speaking-icon"])!=null?ce:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Me=n["--persona-components-approval-requested-background"])!=null?Me:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ze=n["--persona-components-approval-requested-border"])!=null?ze:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ae=n["--persona-components-approval-requested-text"])!=null?Ae:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(We=n["--persona-components-approval-requested-shadow"])!=null?We:"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"]=(ke=n["--persona-components-approval-deny-background"])!=null?ke:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Re=n["--persona-components-attachment-image-background"])!=null?Re: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"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(le=n["--persona-semantic-typography-fontWeight"])!=null?le:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ge=n["--persona-semantic-typography-lineHeight"])!=null?ge: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"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(se=n["--persona-palette-radius-md"])!=null?se:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(Z=n["--persona-palette-radius-xl"])!=null?Z:"0.75rem",n["--persona-radius-full"]=(ee=n["--persona-palette-radius-full"])!=null?ee:"9999px",n["--persona-launcher-radius"]=(Se=(ae=n["--persona-components-launcher-borderRadius"])!=null?ae:n["--persona-palette-radius-full"])!=null?Se:"9999px",n["--persona-launcher-bg"]=(Ze=n["--persona-components-launcher-background"])!=null?Ze:n["--persona-primary"],n["--persona-launcher-fg"]=(ve=n["--persona-components-launcher-foreground"])!=null?ve:n["--persona-text-inverse"],n["--persona-launcher-border"]=(fe=n["--persona-components-launcher-border"])!=null?fe:n["--persona-border"],n["--persona-button-primary-bg"]=(Je=n["--persona-components-button-primary-background"])!=null?Je:n["--persona-primary"],n["--persona-button-primary-fg"]=(De=n["--persona-components-button-primary-foreground"])!=null?De:n["--persona-text-inverse"],n["--persona-button-radius"]=(ue=(z=n["--persona-components-button-primary-borderRadius"])!=null?z:n["--persona-palette-radius-full"])!=null?ue:"9999px",n["--persona-panel-radius"]=(kt=(rt=n["--persona-components-panel-borderRadius"])!=null?rt:n["--persona-radius-xl"])!=null?kt:"0.75rem",n["--persona-panel-border"]=(te=n["--persona-components-panel-border"])!=null?te:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Bn=(Ve=n["--persona-components-panel-shadow"])!=null?Ve:n["--persona-palette-shadows-xl"])!=null?Bn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Bt=n["--persona-components-launcher-shadow"])!=null?Bt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(nr=(ln=n["--persona-components-input-borderRadius"])!=null?ln:n["--persona-radius-lg"])!=null?nr:"0.5rem",n["--persona-message-user-radius"]=(R=(Tr=n["--persona-components-message-user-borderRadius"])!=null?Tr:n["--persona-radius-lg"])!=null?R:"0.5rem",n["--persona-message-assistant-radius"]=(Ne=(pe=n["--persona-components-message-assistant-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?Ne:"0.5rem",n["--persona-header-bg"]=(Ge=n["--persona-components-header-background"])!=null?Ge:n["--persona-surface"],n["--persona-header-border"]=($e=n["--persona-components-header-border"])!=null?$e:n["--persona-divider"],n["--persona-header-icon-bg"]=(je=n["--persona-components-header-iconBackground"])!=null?je:n["--persona-primary"],n["--persona-header-icon-fg"]=(st=n["--persona-components-header-iconForeground"])!=null?st: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"]=(Jt=n["--persona-components-header-subtitleForeground"])!=null?Jt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Yt=n["--persona-components-header-actionIconForeground"])!=null?Yt:n["--persona-muted"];let r=(K=e.components)==null?void 0:K.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(vt=e.components)==null?void 0:vt.introCard;n["--persona-intro-card-bg"]=(it=n["--persona-components-introCard-background"])!=null?it:n["--persona-surface"],n["--persona-intro-card-radius"]=(we=n["--persona-components-introCard-borderRadius"])!=null?we:"1rem",n["--persona-intro-card-padding"]=(ie=n["--persona-components-introCard-padding"])!=null?ie:"1.5rem",n["--persona-intro-card-shadow"]=(Zt=(nt=o==null?void 0:o.shadow)!=null?nt:n["--persona-components-introCard-shadow"])!=null?Zt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Gt=n["--persona-components-input-background"])!=null?Gt:n["--persona-surface"],n["--persona-input-placeholder"]=(kn=n["--persona-components-input-placeholder"])!=null?kn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(xn=n["--persona-components-message-user-background"])!=null?xn:n["--persona-accent"],n["--persona-message-user-text"]=(ft=n["--persona-components-message-user-text"])!=null?ft:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Lt=n["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(et=n["--persona-components-message-assistant-background"])!=null?et:n["--persona-surface"],n["--persona-message-assistant-text"]=(zt=n["--persona-components-message-assistant-text"])!=null?zt:n["--persona-text"],n["--persona-message-assistant-border"]=(cn=n["--persona-components-message-assistant-border"])!=null?cn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(wn=n["--persona-components-message-assistant-shadow"])!=null?wn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(yn=(Cn=n["--persona-components-scrollToBottom-background"])!=null?Cn:n["--persona-button-primary-bg"])!=null?yn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(St=(Er=n["--persona-components-scrollToBottom-foreground"])!=null?Er:n["--persona-button-primary-fg"])!=null?St:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(_n=n["--persona-components-scrollToBottom-border"])!=null?_n:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(jn=n["--persona-components-scrollToBottom-size"])!=null?jn:"40px",n["--persona-scroll-to-bottom-radius"]=(wt=(hr=(Nr=n["--persona-components-scrollToBottom-borderRadius"])!=null?Nr:n["--persona-button-radius"])!=null?hr:n["--persona-radius-full"])!=null?wt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Mr=(Lo=n["--persona-components-scrollToBottom-shadow"])!=null?Lo:n["--persona-palette-shadows-sm"])!=null?Mr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Po=n["--persona-components-scrollToBottom-padding"])!=null?Po:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Dn=n["--persona-components-scrollToBottom-gap"])!=null?Dn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(no=(rs=n["--persona-components-scrollToBottom-fontSize"])!=null?rs:n["--persona-palette-typography-fontSize-sm"])!=null?no:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Or=n["--persona-components-scrollToBottom-iconSize"])!=null?Or:"14px",n["--persona-tool-bubble-shadow"]=(Tt=n["--persona-components-toolBubble-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Un=n["--persona-components-reasoningBubble-shadow"])!=null?Un:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(qn=n["--persona-components-composer-shadow"])!=null?qn:"none",n["--persona-md-inline-code-bg"]=(Ln=n["--persona-components-markdown-inlineCode-background"])!=null?Ln:n["--persona-container"],n["--persona-md-inline-code-color"]=(Pt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Pt:n["--persona-text"],n["--persona-md-link-color"]=(or=(rr=n["--persona-components-markdown-link-foreground"])!=null?rr:n["--persona-accent"])!=null?or:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);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"]=(zn=n["--persona-components-markdown-codeBlock-background"])!=null?zn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(ro=n["--persona-components-markdown-codeBlock-borderColor"])!=null?ro:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Fr=n["--persona-components-markdown-codeBlock-textColor"])!=null?Fr:"inherit",n["--persona-md-table-header-bg"]=(oo=n["--persona-components-markdown-table-headerBackground"])!=null?oo:n["--persona-container"],n["--persona-md-table-border-color"]=(Vn=n["--persona-components-markdown-table-borderColor"])!=null?Vn:n["--persona-border"],n["--persona-md-hr-color"]=(Dt=n["--persona-components-markdown-hr-color"])!=null?Dt:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Pn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Pn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(sr=n["--persona-components-markdown-blockquote-background"])!=null?sr:"transparent",n["--persona-md-blockquote-text-color"]=(so=n["--persona-components-markdown-blockquote-textColor"])!=null?so:n["--persona-palette-colors-gray-500"],n["--cw-container"]=($r=n["--persona-components-collapsibleWidget-container"])!=null?$r:n["--persona-surface"],n["--cw-surface"]=(ao=n["--persona-components-collapsibleWidget-surface"])!=null?ao:n["--persona-surface"],n["--cw-border"]=(kr=n["--persona-components-collapsibleWidget-border"])!=null?kr:n["--persona-border"],n["--persona-message-border"]=(Kn=n["--persona-components-message-border"])!=null?Kn: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"]=(br=n["--persona-dropdown-bg"])!=null?br:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(bt=n["--persona-dropdown-border"])!=null?bt:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(en=n["--persona-dropdown-shadow"])!=null?en:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tn=n["--persona-dropdown-radius"])!=null?tn:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Jn=n["--persona-dropdown-item-hover-bg"])!=null?Jn: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 ar=(io=ws(e,ye.toolbarBackground))!=null?io:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ar}}return n}var em={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 Of={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"}}},tm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ca=()=>{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"},Ff=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ca()},xl=e=>Ff(e),$f=e=>Cs(e),_f=e=>{var n;let t=Cs(void 0,{validate:!1});return Cs({...e,palette:{...t.palette,colors:{...Of.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},As=e=>{let t=xl(e),n=tm(e==null?void 0:e.theme),r=tm(e==null?void 0:e.darkTheme);return t==="dark"?_f(la(n!=null?n:{},r!=null?r:{})):$f(n)},jf=e=>mi(e),xo=(e,t)=>{let n=As(t),r=jf(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},gi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ca())});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(ca());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 nm=require("idiomorph"),fi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;nm.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var hi={index:-1,draft:""};function rm(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...hi}}}function om(e,t){var n,r,o,s,a,i,d,l,p,u,f,m,v,x,w,T,N,M,I,W,S,k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re,de,Q,re;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(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:"",(M=(N=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:N.length)!=null?M:0,(k=(S=(W=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?k:"",typeof(($=e.toolCall)==null?void 0:$.args)=="string"?e.toolCall.args.length:(O=e.toolCall)!=null&&O.args?JSON.stringify(e.toolCall.args).length:0,(J=(U=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:U.length)!=null?J:0,(Ae=(ze=(Me=(ce=e.reasoning)==null?void 0:ce.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:ze.length)!=null?Ae:0,(Re=(ke=(be=(We=e.reasoning)==null?void 0:We.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:ke.slice(-32))!=null?Re:"",(Q=(de=e.contentParts)==null?void 0:de.length)!=null?Q:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function sm(){return new Map}function am(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function im(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function lm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function bi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Xo(e,t){return Xr(e)-e.scrollTop<=t}function yi(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function xi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function cm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function dm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function pm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var En={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Mn=1e5,vo=Mn+1;var da={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Uf=["pre","code","a","script","style"],vi=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:da.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:da.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:da.speed,duration:(o=e==null?void 0:e.duration)!=null?o:da.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:da.buffer}},mm=[{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"}],pa=new Map;for(let e of mm)pa.set(e.name,e);var gm=e=>{pa.set(e.name,e)},fm=e=>{mm.some(t=>t.name===e)||pa.delete(e)},hm=()=>Array.from(pa.keys()),ua=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=pa.get(e))!=null?r:null},wi=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
15
+ `);return s<0?"":e.slice(0,s)}return e},qf=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},zf=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},vl=/\s/,Vf=(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},Kf=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(vl.test(s[i])){let l=i;for(;l<s.length&&vl.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!vl.test(s[p]);)l.appendChild(qf(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Jf=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(zf(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},ma=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:Uf).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Vf(d,s)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Kf:Jf;for(let m of i)p(m,n,l);return o.innerHTML},Ci=(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},ga=(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},um=new WeakMap,Gf=(e,t)=>{var s;if(!e.styles)return;let n=um.get(t);if(n||(n=new Set,um.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 o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},wl=new WeakMap,Xf=(e,t)=>{if(!e.onAttach)return;let n=wl.get(t);if(n||(n=new Map,wl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},bm=e=>{let t=wl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Cl=(e,t)=>{Gf(e,t),Xf(e,t)};function Al(e,t=Mn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var fa=0,wo=null;function Sl(e=document){var n;if(fa++,fa===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;wo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,fa=Math.max(0,fa-1),fa===0&&wo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=wo.originalOverflow,o.style.position=wo.originalPosition,o.style.top=wo.originalTop,o.style.width=wo.originalWidth,s.scrollTo(0,wo.scrollY),wo=null}}}var Ai={side:"right",width:"420px",animate:!0,reveal:"resize"},gn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Co=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,o,s,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:Ai.side,width:(o=t==null?void 0:t.width)!=null?o:Ai.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ai.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ai.reveal}};var Sr={"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 ha=(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=s=>{var M,I,W,S,k,$,O,H,U,J,ce,Me,ze;let a=(M=s.launcher)!=null?M:{},i=gn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let Ae=(I=a.title)!=null?I:"Chat Assistant";d.textContent=Ae,d.setAttribute("title",Ae)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Ae=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=Ae,l.setAttribute("title",Ae)}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 Ae=(S=a.agentIconSize)!=null?S:"40px";if(u.style.height=Ae,u.style.width=Ae,u.innerHTML="",a.agentIconName){let We=parseFloat(Ae)||24,be=Ce(a.agentIconName,We*.6,"var(--persona-text-inverse, #ffffff)",2);be?(u.appendChild(be),u.style.display=""):(u.textContent=(k=a.agentIconText)!=null?k:"\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 Ae=(O=a.agentIconSize)!=null?O:"40px";f.style.height=Ae,f.style.width=Ae,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 Ae=(H=a.callToActionIconSize)!=null?H:"32px";m.style.height=Ae,m.style.width=Ae,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let We=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,We=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let be=parseFloat(Ae)||24,ke=Math.max(be-We,8),Re=Ce(a.callToActionIconName,ke,"currentColor",2);Re?m.appendChild(Re):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(J=a.callToActionIconText)!=null?J:"\u2197"}let v=a.position&&Sr[a.position]?Sr[a.position]:Sr["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((ce=a.zIndex)!=null?ce:Mn));let T="1px solid var(--persona-border, #e5e7eb)",N="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=(Me=a.border)!=null?Me:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:N,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=(ze=a.collapsedMaxWidth)!=null?ze:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Qf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{var x,w,T,N,M,I;let{showClose:n=!0,wrapperClassName:r=Qf,buttonSize:o,iconSize:s="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(w=o!=null?o: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=(N=a.closeButtonShowTooltip)!=null?N:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(M=a.closeButtonIconName)!=null?M:"x",m=(I=a.closeButtonIconText)!=null?I:"\xD7";l.style.color=a.closeButtonColor||Hn.actionIconColor;let v=Ce(f,s,"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,O=$.body;if(!O)return;W=Br($,"div","persona-clear-chat-tooltip"),W.textContent=p;let H=Br($,"div");H.className="persona-clear-chat-tooltip-arrow",W.appendChild(H);let U=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(vo),W.style.left=`${U.left+U.width/2}px`,W.style.top=`${U.top-8}px`,W.style.transform="translate(-50%, -100%)",O.appendChild(W)},k=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",k),l.addEventListener("focus",S),l.addEventListener("blur",k),d._cleanupTooltip=()=>{k(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",k),l.removeEventListener("focus",S),l.removeEventListener("blur",k)}}return{button:l,wrapper:d}},Yf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ti=(e,t={})=>{var W,S,k,$,O,H,U,J,ce,Me,ze,Ae,We;let{wrapperClassName:n=Yf,buttonSize:r,iconSize:o="20px"}=t,a=(S=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?S:{},i=(k=r!=null?r:a.size)!=null?k:"32px",d=($=a.iconName)!=null?$:"refresh-cw",l=(O=a.iconColor)!=null?O:"",p=(H=a.backgroundColor)!=null?H:"",u=(U=a.borderWidth)!=null?U:"",f=(J=a.borderColor)!=null?J:"",m=(ce=a.borderRadius)!=null?ce:"",v=(Me=a.paddingX)!=null?Me:"",x=(ze=a.paddingY)!=null?ze:"",w=(Ae=a.tooltipText)!=null?Ae:"Clear chat",T=(We=a.showTooltip)!=null?We:!0,N=h("div",n),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=i,M.style.width=i,M.type="button",M.setAttribute("aria-label",w),M.style.color=l||Hn.actionIconColor;let I=Ce(d,o,"currentColor",1);if(I&&(I.style.display="block",M.appendChild(I)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),u||f){let be=u||"0px",ke=f||"transparent";M.style.border=`${be} solid ${ke}`,M.classList.remove("persona-border-none")}if(m&&(M.style.borderRadius=m,M.classList.remove("persona-rounded-full")),v&&(M.style.paddingLeft=v,M.style.paddingRight=v),x&&(M.style.paddingTop=x,M.style.paddingBottom=x),N.appendChild(M),T&&w){let be=null,ke=()=>{if(be)return;let de=M.ownerDocument,Q=de.body;if(!Q)return;be=Br(de,"div","persona-clear-chat-tooltip"),be.textContent=w;let re=Br(de,"div");re.className="persona-clear-chat-tooltip-arrow",be.appendChild(re);let le=M.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(vo),be.style.left=`${le.left+le.width/2}px`,be.style.top=`${le.top-8}px`,be.style.transform="translate(-50%, -100%)",Q.appendChild(be)},Re=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};N.addEventListener("mouseenter",ke),N.addEventListener("mouseleave",Re),M.addEventListener("focus",ke),M.addEventListener("blur",Re),N._cleanupTooltip=()=>{Re(),N.removeEventListener("mouseenter",ke),N.removeEventListener("mouseleave",Re),M.removeEventListener("focus",ke),M.removeEventListener("blur",Re)}}return{button:M,wrapper:N}};var Hn={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,k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re;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 o=(W=t==null?void 0:t.launcher)!=null?W:{},s=(S=o.headerIconSize)!=null?S:"48px",a=(k=o.closeButtonPlacement)!=null?k:"inline",i=($=o.headerIconHidden)!=null?$:!1,d=o.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let de=parseFloat(s)||24,Q=Ce(d,de*.6,"currentColor",1);Q?l.replaceChildren(Q):l.textContent=(H=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?H:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let de=h("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=s,de.style.width=s,l.replaceChildren(de)}else l.textContent=(ce=(J=t==null?void 0:t.launcher)==null?void 0:J.agentIconText)!=null?ce:"\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=Hn.titleColor,u.textContent=(ze=(Me=t==null?void 0:t.launcher)==null?void 0:Me.title)!=null?ze:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Hn.subtitleColor,f.textContent=(We=(Ae=t==null?void 0:t.launcher)==null?void 0:Ae.subtitle)!=null?We:"Here to help you get answers fast",p.append(u,f),i?r.append(p):r.append(l,p);let m=(be=o.clearChat)!=null?be:{},v=(ke=m.enabled)!=null?ke:!0,x=(Re=m.placement)!=null?Re:"inline",w=null,T=null;if(v){let Q=Ti(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=Q.button,T=Q.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let N=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:M,wrapper:I}=Si(t,{showClose:n,wrapperClassName:N});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:M,closeButtonWrapper:I,clearChatButton:w,clearChatButtonWrapper:T}},Qo=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Ao(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(vo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let 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=Ce(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(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="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 s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Kt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ce(t,r!=null?r:16,"currentColor",o!=null?o: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 ba(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=Ce(t,s!=null?s: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 ya(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=h("div","persona-toggle-group"+(o?" "+o:""));s.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=Kt({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}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Ei(e){var m,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=Ce(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=Ao({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let 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 Tl=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 o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Zf(e,t,n){var r,o,s;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",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Ce(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=h("div","persona-relative");d.appendChild(i);let l=Ao({items:a.menuItems,onSelect: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 El=e=>{var N,M,I,W,S,k,$,O,H;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(N=t==null?void 0:t.launcher)!=null?N:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Ei({label:(M=a.title)!=null?M:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Hn.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=Hn.titleColor,p.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(p),Zf(l,o==null?void 0:o.trailingActions,(S=o==null?void 0:o.onAction)!=null?S:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let J=o.onTitleClick;l.addEventListener("click",ce=>{ce.target.closest("button")||J()}),l.addEventListener("keydown",ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),J())})}let U=o==null?void 0:o.titleRowHover;U&&(l.style.borderRadius=(k=U.borderRadius)!=null?k:"10px",l.style.padding=($=U.padding)!=null?$:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var J,ce;l.style.backgroundColor=(J=U.background)!=null?J:"",l.style.borderColor=(ce=U.border)!=null?ce:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(O=a.closeButtonSize)!=null?O:"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||Hn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=Ce(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}},Mi={default:Tl,minimal:El},Ml=e=>{var t;return(t=Mi[e])!=null?t:Mi.default},Ss=(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",s=Ml(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&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ki=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 o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());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:s}},Li=e=>{var W,S,k,$,O,H,U,J,ce,Me,ze,Ae;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(S=t.useIcon)!=null?S:!1,r=(k=t.iconText)!=null?k:"\u2191",o=t.iconName,s=($=t.stopIconName)!=null?$:"square",a=(O=t.tooltipText)!=null?O:"Send message",i=(H=t.stopTooltipText)!=null?H:"Stop generating",d=(J=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?J:"Send",l=(Me=(ce=e==null?void 0:e.copy)==null?void 0:ce.stopButtonLabel)!=null?Me:"Stop",p=(ze=t.showTooltip)!=null?ze:!1,u=(Ae=t.size)!=null?Ae:"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 We=parseFloat(u)||24,be=(m==null?void 0:m.trim())||"currentColor";o?(w=Ce(o,We,be,2),w?x.appendChild(w):x.textContent=r):x.textContent=r,T=Ce(s,We,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 N=null;p&&a&&(N=h("div","persona-send-button-tooltip"),N.textContent=a,v.appendChild(N)),x.setAttribute("aria-label",a),v.appendChild(x);let M="send";return{button:x,wrapper:v,setMode:We=>{if(We===M)return;M=We;let be=We==="stop"?i:a;if(x.setAttribute("aria-label",be),N&&(N.textContent=be),n){if(w&&T){let ke=We==="stop"?T:w;x.replaceChildren(ke)}}else x.textContent=We==="stop"?l:d}}},Pi=e=>{var N,M,I,W,S,k,$,O,H,U,J,ce;let t=(N=e==null?void 0:e.voiceRecognition)!=null?N:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((M=t.provider)==null?void 0:M.type)==="runtype";if(!(r||o))return null;let a=(W=(I=e==null?void 0:e.sendButton)==null?void 0:I.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=(k=t.iconSize)!=null?k:a,u=parseFloat(p)||24,f=(O=t.backgroundColor)!=null?O:($=e==null?void 0:e.sendButton)==null?void 0:$.backgroundColor,m=(U=t.iconColor)!=null?U:(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",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Ce(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=(J=t.tooltipText)!=null?J:"Start voice recognition";if(((ce=t.showTooltip)!=null?ce:!1)&&w){let Me=h("div","persona-send-button-tooltip");Me.textContent=w,i.appendChild(Me)}return{button:d,wrapper:i}},Ii=e=>{var v,x,w,T,N,M,I,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 o=h("input");o.type="file",o.accept=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((N=t.maxFiles)!=null?N:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(M=t.buttonTooltipText)!=null?M:"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 u=Ce(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",S=>{S.preventDefault(),o.click()}),s.appendChild(a);let f=(W=t.buttonTooltipText)!=null?W:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:o,previewsContainer:r}},Wi=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 o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(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=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},Ri=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ts=e=>{var v,x,w,T,N,M;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=Ri(),o=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=ki(t);a();let i=Li(t),d=Pi(t),l=Ii(t),p=Wi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);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),o.append(u),o.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)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,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:(N=l==null?void 0:l.input)!=null?N:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var ym=()=>{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=Ce("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),o=h("span","persona-pill-peek__caret"),s=Ce("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},xm=e=>{var v,x,w,T,N,M;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=Ri();r.style.display="none";let o=Wi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ki(t);s.style.maxHeight="100px",a();let i=Li(t),d=Pi(t),l=Ii(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",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)&&s.focus()}),l&&p.append(l.input),p.append(u,s,f),l&&n.append(l.previewsContainer),n.append(p,r,o);let m=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,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:o,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(N=l==null?void 0:l.input)!=null?N:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var vm=e=>{var p,u,f,m,v,x,w,T,N,M,I,W,S,k,$,O,H;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=gn(e);if(Co(e)){let U=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},J=h("div","persona-widget-wrapper persona-fixed persona-transition");J.setAttribute("data-persona-composer-bar",""),J.dataset.state="collapsed",J.dataset.expandedSize=(v=U.expandedSize)!=null?v:"anchored",J.style.zIndex=String((w=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?w:Mn);let ce=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ce.style.width="100%",J.appendChild(ce);let Me=h("div","persona-widget-pill-root");return Me.setAttribute("data-persona-composer-bar",""),Me.dataset.state="collapsed",Me.dataset.expandedSize=(T=U.expandedSize)!=null?T:"anchored",Me.style.zIndex=String((M=(N=e==null?void 0:e.launcher)==null?void 0:N.zIndex)!=null?M:Mn),{wrapper:J,panel:ce,pillRoot:Me}}if(n){let U=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),J=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(J),{wrapper:U,panel:J}}if(!t){let U=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),J=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ce=(W=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?W:"100%";return U.style.width=ce,J.style.width="100%",U.appendChild(J),{wrapper:U,panel:J}}let o=(S=e==null?void 0:e.launcher)!=null?S:{},s=o.position&&Sr[o.position]?Sr[o.position]:Sr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(($=(k=e==null?void 0:e.launcher)==null?void 0:k.zIndex)!=null?$:Mn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(O=e==null?void 0:e.launcher)==null?void 0:O.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:er;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},eh=(e,t)=>{var I,W,S,k,$,O,H,U,J;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:o}=Si(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(S=(W=(I=e==null?void 0:e.launcher)==null?void 0:I.clearChat)==null?void 0:W.enabled)!=null?S:!0,a=null,i=null;if(s){let ce=Ti(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ce.button,i=ce.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"),l.style.setProperty("scrollbar-gutter","stable");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=($=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?$:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(H=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",p.append(u,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((J=e==null?void 0:e.copy)==null?void 0:J.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=xm({config:e}),{root:N,textNode:M}=ym();return n.append(d,o,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:o,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:N,peekTextNode:M}},wm=(e,t=!0)=>{var w,T,N,M,I,W,S,k,$;if(Co(e))return eh(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,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?Ss(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"),a.style.setProperty("scrollbar-gutter","stable");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=gn(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=(M=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(I=e==null?void 0:e.copy)==null?void 0:I.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",""),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=Ts({config:e}),v=(($=e==null?void 0:e.layout)==null?void 0:$.showFooter)!==!1;o?Qo(n,s,e):(s.header.style.display="none",Qo(n,s,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:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.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 th=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}},nh=(e,t)=>{if(!e)return null;let n=th(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},rh=(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},oh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},kl=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(":"))},Ll=320,Am=320,sh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),ah=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),ih=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),lh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),ch=(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 o=0,s=!1,a=()=>{s||(s=!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=`${Ll}px`,l.style.maxHeight=`${Am}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;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),oh(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},dh=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(!kl(r.audio))return;let o=h("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ph=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(!kl(r.video))return;let o=h("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,o.style.maxHeight=`${Am}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},uh=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(!kl(r.data))return;let o=h("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Yo=()=>{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 o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Pl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Yo};if(t){let o=t(r);if(o!==null)return o}return Yo()},mh=(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 o=h("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}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},Cm=(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},gh=(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},Il=(e,t,n)=>{var m,v,x,w,T,N;let r=(m=t.showCopy)!=null?m:!0,o=(v=t.showUpvote)!=null?v:!0,s=(x=t.showDownvote)!=null?x:!0;if(!r&&!o&&!s){let M=h("div");return M.style.display="none",M.id=`actions-${e.id}`,M.setAttribute("data-actions-for",e.id),M}let a=(w=t.visibility)!=null?w:"hover",i=(T=t.align)!=null?T:"right",d=(N=t.layout)!=null?N:"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=(M,I,W)=>{let S=Kt({icon:M,label:I,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",W),S};return r&&u.appendChild(f("copy","Copy message","copy")),o&&u.appendChild(f("thumbs-up","Upvote","upvote")),s&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},Es=(e,t,n,r,o,s)=>{var de,Q,re,le,ge,V,se,He,Z,ee,ae,Se,Ze,ve,fe,Je,De;let a=n!=null?n:{},i=(de=a.layout)!=null?de:"bubble",d=a.avatar,l=a.timestamp,p=(Q=d==null?void 0:d.show)!=null?Q:!1,u=(re=l==null?void 0:l.show)!=null?re:!1,f=(le=d==null?void 0:d.position)!=null?le:"left",m=(ge=l==null?void 0:l.position)!=null?ge:"below",v=gh(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=sh(e),T=(se=(V=e.content)==null?void 0:V.trim())!=null?se:"",M=w.length>0&&T===oi,I=vi((Z=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.features)==null?void 0:Z.streamAnimation),W=(Se=(ae=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:ae.streamAnimation)==null?void 0:Se.plugins,S=e.role==="assistant"&&I.type!=="none"?ua(I.type,W):null,k=e.role==="assistant"&&((Ze=S==null?void 0:S.isAnimating)==null?void 0:Ze.call(S,e))===!0,$=e.role==="assistant"&&S!==null&&(!!e.streaming||k);$&&(S!=null&&S.bubbleClass)&&x.classList.add(S.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),$&&S&&(S.containerClass&&O.classList.add(S.containerClass),O.style.setProperty("--persona-stream-step",`${I.speed}ms`),O.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let H=$?wi((ve=e.content)!=null?ve:"",I.buffer,S,e,!!e.streaming):(fe=e.content)!=null?fe:"",U=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),J=U;$&&(S==null?void 0:S.wrap)==="char"?J=ma(U,"char",e.id,{skipTags:S.skipTags}):$&&(S==null?void 0:S.wrap)==="word"&&(J=ma(U,"word",e.id,{skipTags:S.skipTags}));let ce=null;if(M?(ce=document.createElement("div"),ce.innerHTML=J,ce.style.display="none",O.appendChild(ce)):O.innerHTML=J,$&&(S!=null&&S.useCaret)&&!M&&T){let z=Ci(),ue=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),rt=ue[ue.length-1];if(rt!=null&&rt.parentNode)rt.parentNode.insertBefore(z,rt.nextSibling);else{let kt=O.lastElementChild;kt?kt.appendChild(z):O.appendChild(z)}}if(u&&m==="inline"&&e.createdAt){let z=Cm(e,l);z.classList.add("persona-ml-2","persona-inline"),O.appendChild(z)}if(w.length>0){let z=ch(w,!M&&!!T,()=>{M&&ce&&(ce.style.display="")});z?x.appendChild(z):M&&ce&&(ce.style.display="")}let Me=ah(e);if(Me.length>0){let z=dh(Me);z&&x.appendChild(z)}let ze=ih(e);if(ze.length>0){let z=ph(ze);z&&x.appendChild(z)}let Ae=lh(e);if(Ae.length>0){let z=uh(Ae);z&&x.appendChild(z)}if(x.appendChild(O),u&&m==="below"&&e.createdAt){let z=Cm(e,l);z.classList.add("persona-mt-1"),x.appendChild(z)}let We=e.role==="assistant"?nh(e.stopReason,(De=(Je=s==null?void 0:s.widgetConfig)==null?void 0:Je.copy)==null?void 0:De.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let z=!!(H&&H.trim()),ue=I.placeholder==="skeleton",rt=ue&&I.buffer==="line"&&z;if(z)rt&&x.appendChild(ga());else if(ue)x.appendChild(ga());else{let kt=Pl("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);kt&&x.appendChild(kt)}}if(We&&e.stopReason&&!e.streaming&&(T||(O.style.display="none"),x.appendChild(rh(e.stopReason,We))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let z=Il(e,r,o);x.appendChild(z)}if(!p||e.role==="system")return x;let ke=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Re=mh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ke.append(x,Re):ke.append(Re,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ke},Sm=(e,t,n,r,o,s)=>{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}):Es(e,t,n,r,o,s)};var Ms=new Set,fh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),hh=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
24
+ `):""},Tm=(e,t)=>{let n=Ms.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)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=Ce(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Wl=(e,t)=>{var ze,Ae,We,be,ke,Re,de,Q,re,le,ge;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 o=(Ae=(ze=t==null?void 0:t.features)==null?void 0:ze.reasoningDisplay)!=null?Ae:{},s=o.expandable!==!1,a=s&&Ms.has(e.id),i=n.status!=="complete",d=hh(e,(We=o.previewMaxLines)!=null?We:3),l=h("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let 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((ke=n.startedAt)!=null?ke:Date.now()),x=()=>{let V=h("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=Xa(n),V},w=(Re=m.renderCollapsedSummary)==null?void 0:Re.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Xa(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=Ru(n),p.appendChild(T);let N=(de=o.loadingAnimation)!=null?de:"none",M=m.activeTextTemplate,I=m.completeTextTemplate,W=i?M:I,S=w instanceof HTMLElement,k=(V,se,He)=>{let Z=He;for(let ee of se){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(Z)),ae.textContent=ee===" "?"\xA0":ee,V.appendChild(ae),Z++}return Z},$=(V,se)=>{u.textContent="";let He=Qa(V,""),Z=0;for(let ee of He){let ae=ee.styles.length>0?(()=>{let Se=h("span",ee.styles.map(Ze=>`persona-tool-text-${Ze}`).join(" "));return u.appendChild(Se),Se})():u;if(ee.isDuration&&i)ae.appendChild(x());else{let Se=ee.isDuration?Xa(n):ee.text;se?Z=k(ae,Se,Z):ae.appendChild(document.createTextNode(Se))}}};if(!S&&W)if(T.style.display="none",u.style.display="",i&&N!=="none"){let V=(Q=m.loadingAnimationDuration)!=null?Q:2e3;u.setAttribute("data-preserve-animation","true"),N==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),$(W,!1)):(u.classList.add(`persona-tool-loading-${N}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),N==="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&&N!=="none"){u.style.display="";let V=(re=m.loadingAnimationDuration)!=null?re:2e3;if(u.setAttribute("data-preserve-animation","true"),N==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${N}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),N==="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="",k(u,se,0)}n.status==="complete"&&(u.style.display="none")}else S||(n.status==="complete"?u.style.display="none":u.style.display="");let O=null;if(s){O=h("div","persona-flex persona-items-center");let se=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);se?O.appendChild(se):O.textContent=a?"Hide":"Show";let He=h("div","persona-flex persona-items-center persona-ml-auto");He.append(O),l.append(p,He)}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&&o.activePreview&&d){let V=(ge=(le=t==null?void 0:t.reasoning)==null?void 0:le.renderCollapsedPreview)==null?void 0:ge.call(le,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});fh(H,V)||(H.textContent=d),H.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,H),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let J=n.chunks.join(""),ce=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ce.textContent=J||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(ce),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),O){O.innerHTML="";let se=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);se?O.appendChild(se):O.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(l,H,U),r};var ks=new Set,bh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),yh=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
+ `);let o=ys(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},xh=(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,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=yh(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Hu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=ml(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ml(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Em=(e,t,n)=>{var p;let r=ks.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"currentColor",f=Ce(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")},Rl=(e,t)=>{var J,ce,Me,ze,Ae,We,be,ke,Re;let n=e.toolCall,r=(J=t==null?void 0:t.toolCall)!=null?J:{},o=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.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 o;let s=(Me=(ce=t==null?void 0:t.features)==null?void 0:ce.toolCallDisplay)!=null?Me:{},a=s.expandable!==!1,i=a&&ks.has(e.id),{summary:d,previewText:l,isActive:p}=xh(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((ze=n.startedAt)!=null?ze:Date.now()),x=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",v),de.textContent=ra(n),de},w=(We=r.renderCollapsedSummary)==null?void 0:We.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ae=s.collapsedMode)!=null?Ae:"tool-call",isActive:p,config:t!=null?t:{},elapsed:ra(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=s.loadingAnimation)!=null?be:"none",N=r.activeTextTemplate,M=r.completeTextTemplate,I=p?N:M,W=w instanceof HTMLElement,S=(de,Q,re)=>{let le=re;for(let ge of Q){let V=h("span","persona-tool-char");V.style.setProperty("--char-index",String(le)),V.textContent=ge===" "?"\xA0":ge,de.appendChild(V),le++}return le},k=(de,Q)=>{var V;m.textContent="";let re=((V=n.name)==null?void 0:V.trim())||"tool",le=Qa(de,re),ge=0;for(let se of le){let He=se.styles.length>0?(()=>{let Z=h("span",se.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(Z),Z})():m;if(se.isDuration&&p)He.appendChild(x());else{let Z=se.isDuration?ra(n):se.text;Q?ge=S(He,Z,ge):He.appendChild(document.createTextNode(Z))}}};if(!W)if(p&&T!=="none"){let de=(ke=r.loadingAnimationDuration)!=null?ke:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),I&&k(I,!1);else if(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${de}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)),I)k(I,!0);else{let Q=m.textContent||d;m.textContent="",S(m,Q,0)}}else I&&k(I,!1);let $=null;if(a){$=h("div","persona-flex persona-items-center");let de=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Ce(i?"chevron-up":"chevron-down",16,de,2);Q?$.appendChild(Q):$.textContent=i?"Hide":"Show";let re=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append($),u.append(f,re)}else u.append(f);let O=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let de=(Re=r.renderCollapsedPreview)==null?void 0:Re.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});bh(O,de)||(O.textContent=l),O.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,O),o;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 de=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?de.style.color=r.contentTextColor:r.headerTextColor&&(de.style.color=r.headerTextColor),de.textContent=n.name,H.appendChild(de)}if(n.args!==void 0){let de=h("div","persona-space-y-1"),Q=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=ys(n.args),de.append(Q,re),H.appendChild(de)}if(n.chunks&&n.chunks.length){let de=h("div","persona-space-y-1"),Q=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=n.chunks.join(""),de.append(Q,re),H.appendChild(de)}if(n.status==="complete"&&n.result!==void 0){let de=h("div","persona-space-y-1"),Q=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=ys(n.result),de.append(Q,re),H.appendChild(de)}if(n.status==="complete"&&typeof n.duration=="number"){let de=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(de.style.color=r.contentTextColor),de.textContent=`Duration: ${n.duration}ms`,H.appendChild(de)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let de=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Ce(i?"chevron-up":"chevron-down",16,de,2);Q?$.appendChild(Q):$.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",O.style.display=i?"none":O.textContent||O.childNodes.length?"":"none"})(),o.append(u,O,H),o};var So=require("partial-json");var Bl="ask_user_question",Hl=8,Ls="data-persona-ask-sheet-for",vh="Other",wh="Other\u2026",km="Type your own answer here",Lm="Send",Ch="Next",Ah="Back",Sh="Submit all",Th="Skip",Eh=3,Dl="data-ask-current-index",Nl="data-ask-question-count",Pm="data-ask-answers",Ol="data-ask-grouped",Im="data-ask-layout",Mh=e=>e.layout==="pills"?"pills":"rows",kh=e=>e.getAttribute(Im)==="pills"?"pills":"rows",Mm=!1,Wm=e=>e.replace(/["\\]/g,"\\$&"),Yr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Bl,Hi=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Zr=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 o=r.join(""),s=(0,So.parse)(o,So.STR|So.OBJ|So.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},xa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Hl&&!Mm&&(Mm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Hl}.`)),t.slice(0,Hl)},Lh=e=>{var t;return(t=xa(e)[0])!=null?t:null},Ph=(e,t)=>{var n;return(n=xa(e)[t])!=null?n:null},Rm=(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))},Hm=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=h("span","persona-ask-row-check");r.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Ih=(e,t,n,r)=>{let s=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.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)}s.appendChild(a);let d=Hm(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Wh=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},Rh=(e,t,n,r)=>{var p,u,f;let s=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<Eh;m++)s.appendChild(Wh(r));return s}if(d.forEach((m,v)=>{s.appendChild(Ih(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?vh:wh;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:km,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=Hm(r,a,d.length);T&&v.appendChild(T),s.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,s.appendChild(v)}}return s},Bm=(e,t)=>{var s,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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:km,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),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:Lm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Hh=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:Lm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Bh=(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 o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:Ah,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Th,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Sh:(f=n.nextLabel)!=null?f:Ch,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Zo=e=>{let t=e.getAttribute(Pm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Dm=(e,t)=>{e.setAttribute(Pm,JSON.stringify(t))},gr=e=>{var n;let t=Number((n=e.getAttribute(Dl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Dh=(e,t)=>{e.setAttribute(Dl,String(Math.max(0,Math.floor(t))))},Ps=e=>{var n;let t=Number((n=e.getAttribute(Nl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},To=e=>e.getAttribute(Ol)==="true",Nh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Oh=(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)))},Bi=(e,t)=>{let{payload:n}=Zr(t),r=xa(n),o=Zo(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Nm=e=>{let t=Zo(e),n=gr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Om=e=>{if(!To(e))return;let t=Zo(e),n=gr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Fl=(e,t,n)=>{let r=Hi(n),o=kh(e),{payload:s,complete:a}=Zr(t),i=To(e),d=gr(e),l=Ps(e),p=i?Ph(s,d):Lh(s),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 N=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=N,v.classList.toggle("persona-ask-question-skeleton",!N&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let N=Rh(p,r,a,o);x.replaceWith(N)}if(o!=="rows"){let N=e.querySelector('[data-ask-free-text-row="true"]');N&&N.replaceWith(Bm(r,o))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(Hh(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 N=Bh(d,l,r);T?T.replaceWith(N):e.appendChild(N)}else T&&T.remove();Nm(e),Om(e)},Fh=(e,t,n)=>{let r=Hi(t),o=Mh(r),s=e.toolCall.id,a=xa(n),i=Math.max(1,a.length),d=i>1,l=Nh(e,a),p=d?Oh(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ls,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Nl,String(i)),u.setAttribute(Dl,String(p)),u.setAttribute(Ol,d?"true":"false"),u.setAttribute(Im,o),Dm(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`),Rm(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",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),o!=="rows"&&u.appendChild(Bm(r,o)),Fl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},$h=(e,t,n)=>{let{payload:r}=Zr(t),o=Math.max(1,xa(r).length);o>Ps(e)&&(e.setAttribute(Nl,String(o)),o>1&&!To(e)&&e.setAttribute(Ol,"true")),Fl(e,t,n)},Fm=(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=Hi(t);Rm(n,r);let o=h("span","persona-ask-stub-label"),{complete:s}=Zr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Is=(e,t,n)=>{if(!n||!Yr(e)||Hi(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Ls}]`).forEach(l=>{l.getAttribute(Ls)!==o&&l.remove()});let a=n.querySelector(`[${Ls}="${Wm(o)}"]`);if(a){$h(a,e,t);return}let{payload:i}=Zr(e),d=Fh(e,t,i);n.appendChild(d)},Eo=(e,t)=>{if(!e)return;let n=t?`[${Ls}="${Wm(t)}"]`:`[${Ls}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},$l=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),Mo=(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,Dm(e,n),Nm(e),Om(e)},Di=(e,t,n,r)=>{let o=Ps(e),s=Math.max(0,Math.min(o-1,r));Dh(e,s),Fl(e,t,n)};var Ni=new Map,_h=e=>{let n=(e.startsWith(Kr)?e.slice(Kr.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)},$m=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,_m=(e,t)=>{var r,o,s;let n=(o=(r=$m(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ni.get(e))!=null?s:n==="expanded"},jm=(e,t,n)=>{var a,i;let r=$m(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.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 s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ce(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Um=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=_m(e,n);jm(r,s,n),o.style.display=s?"":"none"};var Oi=(e,t)=>{var k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re,de;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(k=r==null?void 0:r.backgroundColor)!=null?k:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=($=r==null?void 0:r.borderColor)!=null?$:"var(--persona-approval-border, #fef08a)",s.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 s;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=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)":(O=r==null?void 0:r.titleColor)!=null?O:"currentColor",p=Ce(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=(H=r==null?void 0:r.title)!=null?H:"Approval Required",f.appendChild(m),!o){let Q=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",n.status),n.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):n.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):n.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),f.appendChild(Q)}u.appendChild(f);let x=n.toolType==="webmcp"||n.toolName.startsWith(Kr)?ul(n.toolName):void 0,w=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,N=w||(T?n.description:`The assistant wants to use \u201C${x!=null?x:_h(n.toolName)}\u201D.`),M=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(M.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(M.style.color=r.descriptionColor),M.textContent=N,u.appendChild(M),n.reason){let Q=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let re=h("span","persona-font-medium");re.textContent=`${(J=r==null?void 0:r.reasonLabel)!=null?J:"Agent's stated reason:"} `,Q.appendChild(re),Q.appendChild(document.createTextNode(n.reason)),u.appendChild(Q)}let I=(ce=r==null?void 0:r.detailsDisplay)!=null?ce:"collapsed",W=!!n.description&&!T,S=W||!!n.parameters;if(I!=="hidden"&&S){let Q=_m(e.id,t),re=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");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let le=h("span");le.setAttribute("data-approval-details-label","true");let ge=h("span","persona-inline-flex persona-items-center");ge.setAttribute("data-approval-details-chevron","true"),re.append(le,ge),jm(re,Q,t),u.appendChild(re);let V=h("div");if(V.setAttribute("data-approval-details","true"),V.style.display=Q?"":"none",W){let se=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor),se.textContent=n.description,V.appendChild(se)}if(n.parameters){let se=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&&(se.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(se.style.color=r.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=ys(n.parameters),V.appendChild(se)}u.appendChild(V)}if(o){let Q=h("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let re=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");re.type="button",re.style.backgroundColor=(Me=r==null?void 0:r.approveButtonColor)!=null?Me:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(ze=r==null?void 0:r.approveButtonTextColor)!=null?ze:"#ffffff",re.setAttribute("data-approval-action","approve");let le=Ce("shield-check",14,(Ae=r==null?void 0:r.approveButtonTextColor)!=null?Ae:"#ffffff",2);le&&(le.style.marginRight="4px",re.appendChild(le));let ge=document.createTextNode((We=r==null?void 0:r.approveLabel)!=null?We:"Approve");re.appendChild(ge);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-cursor-pointer");V.type="button",V.style.backgroundColor=(be=r==null?void 0:r.denyButtonColor)!=null?be:"transparent",V.style.color=(ke=r==null?void 0:r.denyButtonTextColor)!=null?ke:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let se=Ce("shield-x",14,(Re=r==null?void 0:r.denyButtonTextColor)!=null?Re:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",V.appendChild(se));let He=document.createTextNode((de=r==null?void 0:r.denyLabel)!=null?de:"Deny");V.appendChild(He),Q.append(re,V),u.appendChild(Q)}return a.append(i,u),s.appendChild(a),s};var qm=e=>{let t=[];return{buttons:t,render:(r,o,s,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=o?o.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",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(m))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var va=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 wa=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 o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,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 o of t)r.put(o)}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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.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 o of t)r.put(o)}catch{}}};var jh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Uh=new Set(["step_start","execution_start"]),qh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),zh=new Set(["step_complete","agent_turn_complete"]),Vh=new Set(["flow_complete","agent_complete"]),zm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Km=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,es=(e,t)=>{let n=e[t];return Km(n)?n:void 0};function _l(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Kh(e,t){return typeof t.type=="string"?t.type:e}function Jh(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 Gh(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 Vm(e){var r,o,s,a,i;let t=es(e,"result"),n=[es(e,"tokens"),es(e,"totalTokens"),t?es(t,"tokens"):void 0,es(e,"usage"),t?es(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=tr(d.output))!=null?r:tr(d.outputTokens))!=null?o:tr(d.completionTokens);if(l!==void 0)return l}return(i=(s=tr(e.outputTokens))!=null?s:tr(e.completionTokens))!=null?i:t?(a=tr(t.outputTokens))!=null?a:tr(t.completionTokens):void 0}function Xh(e){var n,r,o,s,a;let t=es(e,"result");return(a=(o=(r=(n=tr(e.executionTime))!=null?n:tr(e.executionTimeMs))!=null?r:tr(e.execution_time))!=null?o:tr(e.duration))!=null?a:t?(s=tr(t.executionTime))!=null?s:tr(t.executionTimeMs):void 0}function Qh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ca=class{constructor(t=Qh){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:Fi(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 s;if(!Km(n)){zm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Kh(t,n),o=this.now();if(jh.has(r)){this.startRun(o);return}if(Uh.has(r)){this.run||this.startRun(o);return}if(qh.has(r)){if(!Gh(r,n))return;let a=Jh(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+_l(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Fi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(zh.has(r)){if(!this.run)return;let a=this.run,i=Vm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+_l(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Fi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Vh.has(r)){if(!this.run)return;let a=this.run,i=Vm(n),d=i!=null?i:a.exactOutputTokens+_l(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Fi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(zm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Xh(n);return s!=null?s:r-t.startedAt}};function Ws(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Yh={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)"}},Zh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},eb=["flowName","stepName","reasoningText","text","name","tool","toolName"],tb=100;function nb(e,t){let n={...Yh,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Zh}function rb(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ob(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function sb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function ab(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 ib(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 lb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function cb(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 db(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function jl(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Ws(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:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var J,ce;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=Ce(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]"),N=(J=r.timestampFormat)!=null?J:"relative";T.textContent=N==="relative"?rb(e.timestamp,n):ob(e.timestamp);let M=null;r.showSequenceNumbers!==!1&&(M=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let I=nb(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=I.bg,W.style.color=I.text,W.style.borderColor=I.text+"50",W.textContent=e.type;let S=(ce=r.descriptionFields)!=null?ce:eb,k=sb(e.payload,S),$=null;k&&($=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=k);let O=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"),U=Ce("clipboard","12px","currentColor",1.5);return U&&H.appendChild(U),H.addEventListener("click",async Me=>{Me.stopPropagation(),await ab(ib(e)),H.innerHTML="";let ze=Ce("check","12px","currentColor",1.5);ze&&H.appendChild(ze),setTimeout(()=>{H.innerHTML="";let Ae=Ce("clipboard","12px","currentColor",1.5);Ae&&H.appendChild(Ae)},1500)}),v.appendChild(x),v.appendChild(T),M&&v.appendChild(M),v.appendChild(W),$&&v.appendChild($),v.appendChild(O),v.appendChild(H),m.appendChild(v),d&&m.appendChild(db(e,a,i)),m}}function Jm(e){var v,x,w,T,N;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.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=(N=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?N:{},f=s.find(M=>M.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let M=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return m();function m(){let M=u.classNames,I=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ws(I,M==null?void 0:M.panel);let W=[],S="",k="",$=null,O=[],H={},U=0,J=bi(),ce=0,Me=0,ze=!1,Ae=null,We=!1,be=0,ke=new Set,Re=new Map,de="",Q="",re=null,le,ge,V,se,He,Z=null,ee=null,ae=null;function Se(){let we=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ie=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");Ws(ie,M==null?void 0:M.headerBar);let nt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(nt.textContent="Events",le=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"),le.textContent="0",a){ee=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let wn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");wn.textContent="Throughput",Z=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"),Z.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 Cn=ee,yn=ae,Er=()=>{if(!yn.textContent)return;let _n=Cn.getBoundingClientRect(),jn=we.getBoundingClientRect();yn.style.left=`${_n.left-jn.left}px`,yn.style.top=`${_n.bottom-jn.top+4}px`,yn.style.display="block"},St=()=>{yn.style.display="none"};ee.addEventListener("mouseenter",Er),ee.addEventListener("mouseleave",St),ee.appendChild(wn),ee.appendChild(Z)}let Zt=h("div","persona-flex-1");ge=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 Gt=h("option","");Gt.value="",Gt.textContent="All events",ge.appendChild(Gt),V=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"),V.type="button",V.title="Copy All";let xn=Ce("clipboard-copy","12px","currentColor",1.5);xn&&V.appendChild(xn);let ft=h("span","persona-text-xs");ft.textContent="Copy All",V.appendChild(ft),ie.appendChild(nt),ie.appendChild(le),ee&&ie.appendChild(ee),ie.appendChild(Zt),ie.appendChild(ge),ie.appendChild(V);let Lt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ws(Lt,M==null?void 0:M.searchBar);let et=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");et&&zt.appendChild(et),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"),Ws(se,M==null?void 0:M.searchInput),se.type="text",se.placeholder="Search event payloads...",He=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"),He.type="button",He.style.display="none";let cn=Ce("x","12px","currentColor",2);return cn&&He.appendChild(cn),Lt.appendChild(zt),Lt.appendChild(se),Lt.appendChild(He),we.appendChild(ie),we.appendChild(Lt),ae&&we.appendChild(ae),we}let Ze,ve=s.find(we=>we.renderEventStreamToolbar);if(ve!=null&&ve.renderEventStreamToolbar&&o){let we=ve.renderEventStreamToolbar({config:o,defaultRenderer:()=>Se(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ie=>{S=ie,ln(),R()},onSearchChange:ie=>{k=ie,ln(),R()}});Ze=we!=null?we:Se()}else Ze=Se();let fe=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");fe.style.display="none";function Je(){if(!a||!Z||!ee)return;let we=a();Z.textContent=lb(we);let ie=cb(we);ae&&(ae.textContent=ie,ie||(ae.style.display="none")),ie?ee.setAttribute("aria-label",ie):ee.removeAttribute("aria-label")}let De=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let ue=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");Ws(ue,M==null?void 0:M.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let rt=Ce(l,"14px","currentColor",2);rt&&ue.appendChild(rt);let kt=h("span","");kt.textContent=p,ue.appendChild(kt);let te=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",De.appendChild(z),De.appendChild(te),De.appendChild(ue),I.setAttribute("tabindex","0"),I.appendChild(Ze),I.appendChild(fe),I.appendChild(De);function Ve(){let we=t.getAll(),ie={};for(let ft of we)ie[ft.type]=(ie[ft.type]||0)+1;let nt=Object.keys(ie).sort(),Zt=nt.length!==O.length||!nt.every((ft,Lt)=>ft===O[Lt]),Gt=!Zt&&nt.some(ft=>ie[ft]!==H[ft]),kn=we.length!==Object.values(H).reduce((ft,Lt)=>ft+Lt,0);if(!Zt&&!Gt&&!kn||(O=nt,H=ie,!ge))return;let xn=ge.value;if(ge.options[0].textContent="All events",Zt){for(;ge.options.length>1;)ge.remove(1);for(let ft of nt){let Lt=h("option","");Lt.value=ft,Lt.textContent=`${ft} (${ie[ft]||0})`,ge.appendChild(Lt)}xn&&nt.includes(xn)?ge.value=xn:xn&&(ge.value="",S="")}else for(let ft=1;ft<ge.options.length;ft++){let Lt=ge.options[ft];Lt.textContent=`${Lt.value} (${ie[Lt.value]||0})`}}function Bn(){let we=t.getAll();if(S&&(we=we.filter(ie=>ie.type===S)),k){let ie=k.toLowerCase();we=we.filter(nt=>nt.type.toLowerCase().includes(ie)||nt.payload.toLowerCase().includes(ie))}return we}function Bt(){return S!==""||k!==""}function ln(){U=0,ce=0,J.resume(),ue.style.display="none"}function nr(we){ke.has(we)?ke.delete(we):ke.add(we),re=we;let ie=z.scrollTop,nt=J.isFollowing();We=!0,J.pause(),R(),z.scrollTop=ie,nt&&J.resume(),We=!1}function Tr(){return Xo(z,50)}function R(){Me=Date.now(),ze=!1,Je(),Ve();let we=t.getEvictedCount();we>0?(fe.textContent=`${we.toLocaleString()} older events truncated`,fe.style.display=""):fe.style.display="none",W=Bn();let ie=W.length,nt=t.getSize()>0;le&&(le.textContent=String(t.getSize())),ie===0&&nt&&Bt()?(te.textContent=k?`No events matching '${k}'`:"No events matching filter",te.style.display="",z.style.display="none"):(te.style.display="none",z.style.display=""),V&&(V.title=Bt()?`Copy Filtered (${ie})`:"Copy All"),d&&!J.isFollowing()&&ie>U&&(ce+=ie-U,kt.textContent=p?`${p}${ce>0?` (${ce})`:""}`:"",ue.style.display=""),U=ie;let Zt=t.getAll(),Gt=Zt.length>0?Zt[0].timestamp:0,kn=new Set(W.map(Lt=>Lt.id));for(let Lt of ke)kn.has(Lt)||ke.delete(Lt);let xn=S!==de||k!==Q,ft=Re.size===0&&W.length>0;if(xn||ft||W.length===0){z.innerHTML="",Re.clear();let Lt=document.createDocumentFragment();for(let et=0;et<W.length;et++){let zt=jl(W[et],et,Gt,u,ke,nr,s,o);Re.set(W[et].id,zt),Lt.appendChild(zt)}z.appendChild(Lt),de=S,Q=k,re=null}else{if(re!==null){let et=Re.get(re);if(et&&et.parentNode===z){let zt=W.findIndex(cn=>cn.id===re);if(zt>=0){let cn=jl(W[zt],zt,Gt,u,ke,nr,s,o);z.insertBefore(cn,et),et.remove(),Re.set(re,cn)}}re=null}let Lt=new Set(W.map(et=>et.id));for(let[et,zt]of Re)Lt.has(et)||(zt.remove(),Re.delete(et));for(let et=0;et<W.length;et++){let zt=W[et];if(!Re.has(zt.id)){let cn=jl(zt,et,Gt,u,ke,nr,s,o);Re.set(zt.id,cn),z.appendChild(cn)}}}J.isFollowing()&&(z.scrollTop=z.scrollHeight)}function pe(){if(Date.now()-Me>=tb){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),R();return}ze||(ze=!0,Ae=requestAnimationFrame(()=>{Ae=null,R()}))}let Ne=(we,ie)=>{if(!V)return;V.innerHTML="";let nt=Ce(we,"12px","currentColor",1.5);nt&&V.appendChild(nt);let Zt=h("span","persona-text-xs");Zt.textContent="Copy All",V.appendChild(Zt),setTimeout(()=>{V.innerHTML="";let Gt=Ce("clipboard-copy","12px","currentColor",1.5);Gt&&V.appendChild(Gt);let kn=h("span","persona-text-xs");kn.textContent="Copy All",V.appendChild(kn),V.disabled=!1},ie)},Ge=async()=>{if(V){V.disabled=!0;try{let we;Bt()?we=W:n?(we=await n(),we.length===0&&(we=t.getAll())):we=t.getAll();let ie=we.map(nt=>{try{return JSON.parse(nt.payload)}catch{return nt.payload}});await navigator.clipboard.writeText(JSON.stringify(ie,null,2)),Ne("check",1500)}catch{Ne("x",1500)}}},$e=()=>{ge&&(S=ge.value,ln(),R())},je=()=>{!se||!He||(He.style.display=se.value?"":"none",$&&clearTimeout($),$=setTimeout(()=>{k=se.value,ln(),R()},150))},st=()=>{!se||!He||(se.value="",k="",He.style.display="none",$&&clearTimeout($),ln(),R())},It=()=>{if(We)return;let we=z.scrollTop,{action:ie,nextLastScrollTop:nt}=yi({following:J.isFollowing(),currentScrollTop:we,lastScrollTop:be,nearBottom:Tr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=nt,ie==="resume"?(J.resume(),ce=0,ue.style.display="none"):ie==="pause"&&(J.pause(),d&&(kt.textContent=p,ue.style.display=""))},Jt=we=>{let ie=xi({following:J.isFollowing(),deltaY:we.deltaY,nearBottom:Tr(),resumeWhenNearBottom:!0});ie==="pause"?(J.pause(),d&&(kt.textContent=p,ue.style.display="")):ie==="resume"&&(J.resume(),ce=0,ue.style.display="none")},Yt=()=>{d&&(z.scrollTop=z.scrollHeight,J.resume(),ce=0,ue.style.display="none")},K=we=>{let ie=we.target;if(!ie||ie.closest("button"))return;let nt=ie.closest("[data-event-id]");if(!nt)return;let Zt=nt.getAttribute("data-event-id");Zt&&nr(Zt)},vt=we=>{if((we.metaKey||we.ctrlKey)&&we.key==="f"){we.preventDefault(),se==null||se.focus(),se==null||se.select();return}we.key==="Escape"&&(se&&document.activeElement===se?(st(),se.blur(),I.focus()):r&&r())};V&&V.addEventListener("click",Ge),ge&&ge.addEventListener("change",$e),se&&se.addEventListener("input",je),He&&He.addEventListener("click",st),z.addEventListener("scroll",It),z.addEventListener("wheel",Jt,{passive:!0}),z.addEventListener("click",K),ue.addEventListener("click",Yt),I.addEventListener("keydown",vt);function it(){$&&clearTimeout($),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),ze=!1,Re.clear(),V&&V.removeEventListener("click",Ge),ge&&ge.removeEventListener("change",$e),se&&se.removeEventListener("input",je),He&&He.removeEventListener("click",st),z.removeEventListener("scroll",It),z.removeEventListener("wheel",Jt),z.removeEventListener("click",K),ue.removeEventListener("click",Yt),I.removeEventListener("keydown",vt)}return{element:I,update:pe,destroy:it}}}function Gm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${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)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",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),o==="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 Xm=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.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:()=>Gm(e,t)});if(p)return p}return Gm(e,t)};var Ul=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)})}},eo=new Ul;eo.register("PersonaArtifactCard",Xm);function pb(e){var o;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((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Qm(e,t){var ge,V,se,He;let n=(V=(ge=e.features)==null?void 0:ge.artifacts)==null?void 0:V.layout,o=((se=n==null?void 0:n.toolbarPreset)!=null?se:"default")==="document",s=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?jo(e.markdown):null,i=hs(e.sanitize),d=Z=>{let ee=a?a(Z):Uo(Z);return i?i(ee):ee},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"),U==null||U.hide()};l&&l.addEventListener("click",()=>{var Z;p(),(Z=t.onDismiss)==null||Z.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"),o&&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"),o&&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 Z;p(),(Z=t.onDismiss)==null||Z.call(t)});let x="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Kt({icon:"eye",label:"Rendered view"}),N=o?Kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Kt({icon:"code-2",label:"Source"}),M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,k=!!(W&&S&&S.length>0),$=null,O,H=null,U=null;if(o&&(I||W)&&!k){if(O=I?ba({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Z=Ce("chevron-down",14,"currentColor",2);Z&&O.appendChild(Z)}}else o&&k?($=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),O=I?ba({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=Kt({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(O,H)):o?O=Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):O=Kt({icon:"copy",label:"Copy"});let J=o?Kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"refresh-cw",label:"Refresh"}),ce=o?Kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"x",label:"Close"}),Me=()=>{var Ze,ve,fe;let Z=(Ze=Re.find(Je=>Je.id===de))!=null?Ze:Re[Re.length-1],ee=(ve=Z==null?void 0:Z.id)!=null?ve:null,ae=(Z==null?void 0:Z.artifactType)==="markdown"&&(fe=Z.markdown)!=null?fe:"",Se=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"";return{markdown:ae,jsonPayload:Se,id:ee}},ze=async()=>{var Ze;let{markdown:Z,jsonPayload:ee}=Me(),ae=(Ze=Re.find(ve=>ve.id===de))!=null?Ze:Re[Re.length-1],Se=(ae==null?void 0:ae.artifactType)==="markdown"?Z:ae?ee:"";try{await navigator.clipboard.writeText(Se)}catch{}};if(O.addEventListener("click",async()=>{let Z=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Z&&k){let{markdown:ee,jsonPayload:ae,id:Se}=Me();try{await Z({actionId:"primary",artifactId:Se,markdown:ee,jsonPayload:ae})}catch{}return}await ze()}),H&&(S!=null&&S.length)){let Z=()=>{var ae;return(ae=u.closest("[data-persona-root]"))!=null?ae:document.body},ee=()=>{U=Ao({items:S.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:Se,jsonPayload:Ze,id:ve}=Me(),fe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{fe?await fe({actionId:ae,artifactId:ve,markdown:Se,jsonPayload:Ze}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(Se):ae==="json"||ae==="source"?await navigator.clipboard.writeText(Ze):await navigator.clipboard.writeText(Se||Ze)}catch{}},anchor:$!=null?$:H,position:"bottom-right",portal:Z()})};u.isConnected?ee():requestAnimationFrame(ee),H.addEventListener("click",ae=>{ae.stopPropagation(),U==null||U.toggle()})}J.addEventListener("click",async()=>{var Z;try{await((Z=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Z.call(n))}catch{}re()}),ce.addEventListener("click",()=>{var Z;p(),(Z=t.onDismiss)==null||Z.call(t)});let Ae=()=>{o&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),N.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Ae(),re()}),N.addEventListener("click",()=>{x="source",Ae(),re()});let We=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),w.append(T,N),$?M.append($,J,ce):M.append(O,J,ce),f.append(w,We,M),Ae()):(f.appendChild(m),f.appendChild(v)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);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"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,ke.style.padding=s),u.appendChild(f),u.appendChild(be),u.appendChild(ke);let Re=[],de=null,Q=!1,re=()=>{var Se,Ze,ve,fe;let Z=o&&Re.length<=1;be.classList.toggle("persona-hidden",Z),be.replaceChildren();for(let Je of Re){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=Je.title||Je.id.slice(0,8),Je.id===de&&De.classList.add("persona-bg-persona-container","persona-border-persona-border"),De.addEventListener("click",()=>t.onSelect(Je.id)),be.appendChild(De)}ke.replaceChildren();let ee=de&&Re.find(Je=>Je.id===de)||Re[Re.length-1];if(!ee)return;if(o){let Je=ee.artifactType==="markdown"?"MD":(Se=ee.component)!=null?Se:"Component",z=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";We.textContent=`${z} \xB7 ${Je}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(o&&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=(Ze=ee.markdown)!=null?Ze:"",ke.appendChild(De);return}let Je=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Je.innerHTML=d((ve=ee.markdown)!=null?ve:""),ke.appendChild(Je);return}let ae=ee.component?eo.get(ee.component):void 0;if(ae){let De={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let z=ae((fe=ee.props)!=null?fe:{},De);if(z){ke.appendChild(z);return}}catch{}}ke.appendChild(pb(ee))},le=()=>{var ee;let Z=Re.length>0;if(u.classList.toggle("persona-hidden",!Z),l){let ae=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ze=((ee=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Z&&Ze&&Q?(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(Z){var ee,ae,Se;Re=Z.artifacts,de=(Se=(ae=Z.selectedId)!=null?ae:(ee=Z.artifacts[Z.artifacts.length-1])==null?void 0:ee.id)!=null?Se:null,Re.length>0&&(Q=!0),re(),le()},setMobileOpen(Z){Q=Z,!Z&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):le()}}}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 Ym(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!fr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(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)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function ub(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 $i(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"),ub(e),Ym(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 o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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"),Ym(e,t)}var Zm=["panel","seamless"];function _i(e,t){var i,d,l,p,u,f;for(let m of Zm)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",o=Zm.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);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())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function eg(e,t){var n,r,o;return!t||!fr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function mb(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 gb(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 fb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function hb(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function tg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function ng(e,t,n,r,o,s){let a=mb(o,200),i=hb(t,n,r,200);i=Math.max(a,i);let d=gb(s);return d!==null&&(i=Math.min(i,d)),fb(e,a,i)}var rg={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"}},ql=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,w;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=rg[a])!=null?x:rg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let 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,k;let N=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");N.htmlFor=`${t.id}-${a}-${T.name}`;let M=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=T.label,N.appendChild(M);let I=(S=T.type)!=null?S:"text",W;I==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=I),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=(k=T.placeholder)!=null?k:"",T.required&&(W.required=!0),N.appendChild(W),p.appendChild(N)});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),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var W,S;T.preventDefault();let N=(W=n.formEndpoint)!=null?W:"/form",M=new FormData(p),I={};M.forEach((k,$)=>{I[$]=k}),I.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let $=await k.json();f.textContent=(S=$.message)!=null?S:"Thanks! We'll be in touch soon.",$.success&&$.nextPrompt&&await r.sendMessage(String($.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var zl=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,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Aa=new zl;var og=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var bb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Sa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=bb(e),n=yb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Vl=e=>typeof e=="string"?e:e==null?"":String(e),ts={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Vl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Vl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Vl(n.text)}}},sg=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ta=e=>{let t=new Set(sg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(sg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.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 xb=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}},vb=e=>e.map(t=>({...t,streaming:!1})),wb=e=>e.map(t=>({...t,status:"complete"})),ji=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?xb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?vb(n.messages):void 0,artifacts:n.artifacts?wb(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},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 Rs=require("partial-json");function Cb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Ab(e,t){if(!Cb(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 Ui(){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 o=(0,Rs.parse)(n,Rs.STR|Rs.OBJ),s=Ab(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ag(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function qi(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=eo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function ig(){let e=Ui();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function lg(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 zi(e){let t=lg(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 Vi(e){let t=lg(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 Sb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ki(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Sb}=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=o,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 k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),k.title=l[S-1],k.dataset.rating=String(S),k.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
+ `,k.addEventListener("click",()=>{u=S,T.forEach(($,O)=>{let H=O<S;$.classList.toggle("selected",H),$.setAttribute("aria-checked",O===S-1?"true":"false")})}),T.push(k),w.appendChild(k)}f.appendChild(w);let N=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),S.appendChild(N),f.appendChild(S)}let M=document.createElement("div");M.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 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=(N==null?void 0:N.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)}}),M.appendChild(I),M.appendChild(W),f.appendChild(M),p.appendChild(f),p}function Ji(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel: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=o,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 N=document.createElement("div");N.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=p,N.appendChild(M),N.appendChild(I);let W=document.createElement("div");W.className="persona-feedback-numbers";let S=[];for(let U=0;U<=10;U++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-number-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`Rating ${U} out of 10`),J.textContent=String(U),J.dataset.rating=String(U),U<=6?J.classList.add("persona-feedback-detractor"):U<=8?J.classList.add("persona-feedback-passive"):J.classList.add("persona-feedback-promoter"),J.addEventListener("click",()=>{f=U,S.forEach((ce,Me)=>{ce.classList.toggle("selected",Me===U),ce.setAttribute("aria-checked",Me===U?"true":"false")})}),S.push(J),W.appendChild(J)}T.appendChild(N),T.appendChild(W),m.appendChild(T);let k=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),U.appendChild(k),m.appendChild(U)}let $=document.createElement("div");$.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=i,O.addEventListener("click",()=>{n==null||n(),u.remove()});let 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(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let U=(k==null?void 0:k.value.trim())||void 0;await t(f,U),u.remove()}catch(U){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),$.appendChild(O),$.appendChild(H),m.appendChild($),u.appendChild(m),u}var Hs="persona-chat-history",Tb=30*1e3,Eb={"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 Mb(e){var r,o,s;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=(o=Eb[i.type])!=null?o:"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((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Gi(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 kb(e){var t,n,r,o,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Lb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Kl=e=>!e||typeof e!="object"?{}:{...e},cg=e=>e.map(t=>({...t,streaming:!1})),dg=(e,t,n)=>{let r=e!=null&&e.markdown?jo(e.markdown):null,o=hs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,u;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):r?d=r(a):d=Uo(a),o?o(d):d}};function pg(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",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Ce(n,r,o,s);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 Xi=(e,t,n)=>{var 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,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd;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=pi(t),o=Aa.getForInstance(r.plugins);r.components&&eo.registerAll(r.components);let s=og(),i=r.persistState===!1?null:(Ec=r.storageAdapter)!=null?Ec:ji(),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=Kl(b.metadata)),(Mc=b.messages)!=null&&Mc.length&&(r={...r,initialMessages:b.messages}),(kc=b.artifacts)!=null&&kc.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Lc=b.selectedArtifactId)!=null?Lc: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:{},ls()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Sa],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ts.message,ts.messageAndClick],w=Ta({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let T=(Wc=(Ic=r.launcher)==null?void 0:Ic.enabled)!=null?Wc:!0,N=(Hc=(Rc=r.launcher)==null?void 0:Rc.autoExpand)!=null?Hc:!1,M=(Bc=r.autoFocusInput)!=null?Bc:!1,I=N,W=T,S=(Nc=(Dc=r.layout)==null?void 0:Dc.header)==null?void 0:Nc.layout,k=!1,$=()=>Co(r),O=()=>T||$(),H=$()?!1:T?N:!0,U=!1,J=null,ce=()=>{U=!0,J&&clearTimeout(J),J=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},Me=dg(r,w,ce),ze=(Fc=(Oc=r.features)==null?void 0:Oc.showReasoning)!=null?Fc:!0,Ae=(_c=($c=r.features)==null?void 0:$c.showToolCalls)!=null?_c:!0,We=(Uc=(jc=r.features)==null?void 0:jc.showEventStreamToggle)!=null?Uc:!1,be=(zc=(qc=r.features)==null?void 0:qc.scrollToBottom)!=null?zc:{},ke=(Kc=(Vc=r.features)==null?void 0:Vc.scrollBehavior)!=null?Kc:{},de=`${(Gc=typeof r.persistState=="object"?(Jc=r.persistState)==null?void 0:Jc.keyPrefix:void 0)!=null?Gc:"persona-"}event-stream`,Q=We?new wa(de):null,re=(Yc=(Qc=(Xc=r.features)==null?void 0:Xc.eventStream)==null?void 0:Qc.maxEvents)!=null?Yc:2e3,le=We?new va(re,Q):null,ge=We?new Ca:null,V=null,se=!1,He=null,Z=0;Q==null||Q.open().then(()=>le==null?void 0:le.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ee={onCopy:c=>{var g,b;s.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;s.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)}},ae=(Zc=r.statusIndicator)!=null?Zc:{},Se=c=>{var g,b,y,E;return c==="idle"?(g=ae.idleText)!=null?g:En.idle:c==="connecting"?(b=ae.connectingText)!=null?b:En.connecting:c==="connected"?(y=ae.connectedText)!=null?y:En.connected:c==="error"?(E=ae.errorText)!=null?E:En.error:En[c]};function Ze(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:ve,panel:fe,pillRoot:Je}=vm(r),De=wm(r,O()),{container:z,body:ue,messagesWrapper:rt,suggestions:kt,textarea:te,sendButton:Ve,sendButtonWrapper:Bn,composerForm:Bt,statusText:ln,introTitle:nr,introSubtitle:Tr,closeButton:R,iconHolder:pe,headerTitle:Ne,headerSubtitle:Ge,header:$e,footer:je,actionsRow:st,leftActions:It,rightActions:Jt}=De,Yt=De.setSendButtonMode,K=De.micButton,vt=De.micButtonWrapper,it=De.attachmentButton,we=De.attachmentButtonWrapper,ie=De.attachmentInput,nt=De.attachmentPreviewsContainer;z.classList.add("persona-relative"),ue.classList.add("persona-relative");let Zt=12,Gt=()=>{var c;return(c=be.label)!=null?c:""},kn=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},xn=()=>be.enabled!==!1,ft=()=>{var c;return(c=ke.mode)!=null?c:"follow"},Lt=()=>{var c;return(c=ke.anchorTopOffset)!=null?c:16},et=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");et.type="button",et.style.display="none",et.setAttribute("data-persona-scroll-to-bottom","true");let zt=h("span","persona-flex persona-items-center"),cn=h("span",""),wn=h("span","");wn.setAttribute("data-persona-scroll-to-bottom-count",""),wn.style.display="none",et.append(zt,cn,wn),z.appendChild(et);let Cn=h("div","persona-stream-anchor-spacer");Cn.setAttribute("aria-hidden","true"),Cn.setAttribute("data-persona-anchor-spacer",""),Cn.style.flexShrink="0",Cn.style.pointerEvents="none",Cn.style.height="0px",ue.appendChild(Cn);let yn=()=>{let g=je.style.display==="none"?0:je.offsetHeight;et.style.bottom=`${g+Zt}px`};yn();let Er=()=>{let c=!!Gt();et.setAttribute("aria-label",Gt()||"Jump to latest"),et.title=Gt(),et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),zt.innerHTML="";let g=Ce(kn(),"14px","currentColor",2);g?(zt.appendChild(g),zt.style.display=""):zt.style.display="none",cn.textContent=Gt(),cn.style.display=c?"":"none"};Er();let St=null,_n=null,jn=o.find(c=>c.renderHeader);if(jn!=null&&jn.renderHeader){let c=jn.renderHeader({config:r,defaultRenderer:()=>{let g=Qr({config:r,showClose:O()});return Qo(z,g,r),g.header},onClose:()=>Nt(!1,"user")});if(c){let g=z.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),$e=c)}}let Nr=()=>{var g,b,y,E;if(!le)return;if(se=!0,!V&&le&&(V=Jm({buffer:le,getFullHistory:()=>le.getAllFromStore(),onClose:()=>hr(),config:r,plugins:o,getThroughput:()=>{var D;return(D=ge==null?void 0:ge.getMetric())!=null?D:{status:"idle"}}})),V&&(ue.style.display="none",(g=je.parentNode)==null||g.insertBefore(V.element,je),V.update()),wt){wt.style.boxShadow=`inset 0 0 0 1.5px ${Hn.actionIconColor}`;let D=(E=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:E.toggleButtonActive;D&&D.split(/\s+/).forEach(F=>F&&wt.classList.add(F))}let c=()=>{if(!se)return;let D=Date.now();D-Z>=200&&(V==null||V.update(),Z=D),He=requestAnimationFrame(c)};Z=0,He=requestAnimationFrame(c),On(),s.emit("eventStream:opened",{timestamp:Date.now()})},hr=()=>{var c,g,b;if(se){if(se=!1,V&&V.element.remove(),ue.style.display="",wt){wt.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&&wt.classList.remove(E))}He!==null&&(cancelAnimationFrame(He),He=null),On(),s.emit("eventStream:closed",{timestamp:Date.now()})}},wt=null;if(We){let c=(td=(ed=r.features)==null?void 0:ed.eventStream)==null?void 0:td.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:"");wt=h("button",g),wt.style.width="28px",wt.style.height="28px",wt.style.color=Hn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let b=Ce("activity","18px","currentColor",1.5);b&&wt.appendChild(b);let y=De.clearChatButtonWrapper,E=De.closeButtonWrapper,D=y||E;D&&D.parentNode===$e?$e.insertBefore(wt,D):$e.appendChild(wt),wt.addEventListener("click",()=>{se?hr():Nr()})}let Lo=c=>{var y,E,D;let g=r.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let F=c.querySelector("[data-persona-composer-form]");F!=null&&F.parentNode?F.parentNode.insertBefore(b,F):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let F=h("input");F.type="file",F.accept=((y=g.allowedTypes)!=null?y:Gr).join(","),F.multiple=((E=g.maxFiles)!=null?E:4)>1,F.style.display="none",F.setAttribute("aria-label",(D=g.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(F)}},Mr=o.find(c=>c.renderComposer);if(Mr!=null&&Mr.renderComposer){let c=r.composer,g=Mr.renderComposer({config:r,defaultRenderer:()=>Ts({config:r}).footer,onSubmit:b=>{var F;if(!_||_.isStreaming())return;let y=b.trim(),E=(F=St==null?void 0:St.hasAttachments())!=null?F:!1;if(!y&&!E)return;A();let D;E&&(D=[],D.push(...St.getContentParts()),y&&D.push(oa(y))),_.sendMessage(y,{contentParts:D}),E&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ie==null||ie.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:((nd=r.voiceRecognition)==null?void 0:nd.enabled)===!0?()=>{_n==null||_n()}:void 0});g&&(je.replaceWith(g),je=g)}let Po=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]"),D=c.querySelector("[data-persona-composer-status]");g&&(Bt=g),b&&(te=b),y&&(Ve=y),E&&(K=E,vt=E.parentElement),D&&(ln=D);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(kt=F);let q=c.querySelector(".persona-attachment-button");q&&(it=q,we=q.parentElement),ie=c.querySelector('input[type="file"]'),nt=c.querySelector(".persona-attachment-previews");let B=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(st=B)};Lo(je),Po(je);let Dn=(id=(rd=r.layout)==null?void 0:rd.contentMaxWidth)!=null?id:$()?(ad=(sd=(od=r.launcher)==null?void 0:od.composerBar)==null?void 0:sd.contentMaxWidth)!=null?ad:"720px":void 0;if(Dn&&(rt.style.maxWidth=Dn,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%"),Dn&&Bt&&!$()&&(Bt.style.maxWidth=Dn,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Dn&&kt&&!$()&&(kt.style.maxWidth=Dn,kt.style.marginLeft="auto",kt.style.marginRight="auto"),Dn&&nt&&!$()&&(nt.style.maxWidth=Dn,nt.style.marginLeft="auto",nt.style.marginRight="auto"),(ld=r.attachments)!=null&&ld.enabled&&ie&&nt){St=Go.fromConfig(r.attachments),St.setPreviewsContainer(nt),ie.addEventListener("change",b=>{let y=b.target;St==null||St.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=pg(c);z.appendChild(g)}(()=>{var y,E;let c=(E=(y=r.layout)==null?void 0:y.slots)!=null?E:{},g=D=>{switch(D){case"body-top":return z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return rt;case"footer-top":return kt;case"composer":return Bt;case"footer-bottom":return ln;default:return null}},b=(D,F)=>{var q;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")$e.insertBefore(F,$e.firstChild);else if(D==="header-right")$e.appendChild(F);else{let B=$e.querySelector(".persona-flex-col");B?(q=B.parentNode)==null||q.insertBefore(F,B.nextSibling):$e.appendChild(F)}break;case"body-top":{let B=ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(F):ue.insertBefore(F,ue.firstChild);break}case"body-bottom":ue.appendChild(F);break;case"footer-top":kt.replaceWith(F);break;case"footer-bottom":ln.replaceWith(F);break;default:break}};for(let[D,F]of Object.entries(c))if(F)try{let q=F({config:r,defaultContent:()=>g(D)});q&&b(D,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,q)}})();let no=c=>{var F,q;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 D=b.getAttribute("data-bubble-type");if(D==="reasoning")Ms.has(E)?Ms.delete(E):Ms.add(E),Tm(E,y);else if(D==="tool")ks.has(E)?ks.delete(E):ks.add(E),Em(E,y,r);else if(D==="approval"){let B=r.approval!==!1?r.approval:void 0,xe=((F=B==null?void 0:B.detailsDisplay)!=null?F:"collapsed")==="expanded",me=(q=Ni.get(E))!=null?q:xe;Ni.set(E,!me),Um(E,y,r)}_r.delete(E)};rt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),no(c))}),rt.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),no(c))});let Or=new Map;rt.addEventListener("click",c=>{var F;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest("[data-actions-for]");if(!y)return;let E=y.getAttribute("data-actions-for");if(!E)return;let D=b.getAttribute("data-action");if(D==="copy"){let B=_.getMessages().find(xe=>xe.id===E);if(B&&ee.onCopy){let xe=B.content||"";navigator.clipboard.writeText(xe).then(()=>{b.classList.add("persona-message-action-success");let me=Ce("check",14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ne=Ce("copy",14,"currentColor",2);ne&&(b.innerHTML="",b.appendChild(ne))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ee.onCopy(B)}}else if(D==="upvote"||D==="downvote"){let B=((F=Or.get(E))!=null?F:null)===D,xe=D==="upvote"?"thumbs-up":"thumbs-down";if(B){Or.delete(E),b.classList.remove("persona-message-action-active");let me=Ce(xe,14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me))}else{let me=D==="upvote"?"downvote":"upvote",ne=y.querySelector(`[data-action="${me}"]`);if(ne){ne.classList.remove("persona-message-action-active");let Ke=Ce(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ke&&(ne.innerHTML="",ne.appendChild(Ke))}Or.set(E,D),b.classList.add("persona-message-action-active");let Ee=Ce(xe,14,"currentColor",2);Ee&&(Ee.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Ee)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Te=_.getMessages().find(ot=>ot.id===E);Te&&ee.onFeedback&&ee.onFeedback({type:D,messageId:Te.id,message:Te})}}}),rt.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 D=b.getAttribute("data-approval-action");if(!D)return;let F=D==="approve"?"approved":"denied",B=_.getMessages().find(me=>me.id===E);if(!(B!=null&&B.approval))return;let xe=y.querySelector("[data-approval-buttons]");xe&&xe.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(E,F):_.resolveApproval(B.approval,F)});let Tt=null,Un=null,qn={artifacts:[],selectedId:null},Ln=!1,Pt={current:null};rt.addEventListener("click",c=>{var ne,Ee,_e,Te,ot;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((_e=(Ee=(ne=r.features)==null?void 0:ne.artifacts)==null?void 0:Ee.onArtifactAction)==null?void 0:_e.call(Ee,{type:"download",artifactId:y}))===!0)return;let D=_.getArtifactById(y),F=D==null?void 0:D.markdown,q=(D==null?void 0:D.title)||"artifact";if(!F){let Ke=b.closest("[data-open-artifact]"),dt=Ke==null?void 0:Ke.closest("[data-message-id]"),pt=dt==null?void 0:dt.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);F=(Te=qe==null?void 0:qe.props)==null?void 0:Te.markdown,q=((ot=qe==null?void 0:qe.props)==null?void 0:ot.title)||q}catch{}}}if(!F)return;let B=new Blob([F],{type:"text/markdown"}),xe=URL.createObjectURL(B),me=document.createElement("a");me.href=xe,me.download=`${q}.md`,me.click(),URL.revokeObjectURL(xe)}),rt.addEventListener("click",c=>{var D,F,q;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((q=(F=(D=r.features)==null?void 0:D.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:q.call(F,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Ln=!1,_.selectArtifact(y),Kn())}),rt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let rr=De.composerOverlay,or=(c,g,b)=>{var q,B,xe,me;let y=g.trim();if(!y||!Pt.current)return;let E=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",D=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:E,answer:y,answers:b.structured,values:(B=b.values)!=null?B:b.source==="multi"?y.split(", "):[y],isFreeText:D,source:b.source},bubbles:!0,composed:!0})),Eo(rr,E);let F=Pt.current.getMessages().find(ne=>{var Ee;return((Ee=ne.toolCall)==null?void 0:Ee.id)===E});(xe=F==null?void 0:F.agentMetadata)!=null&&xe.awaitingLocalTool?Pt.current.resolveAskUserQuestion(F,(me=b.structured)!=null?me:y):Pt.current.sendMessage(y)},zn=c=>{var E;let g=Pt.current;if(!g)return;let b=(E=c.getAttribute("data-tool-call-id"))!=null?E:"",y=g.getMessages().find(D=>{var F;return((F=D.toolCall)==null?void 0:F.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:Bi(c,y),currentIndex:gr(c)})},ro=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Fr=c=>{var E,D,F;if(((D=(E=r.features)==null?void 0:E.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let g=gr(c),b=Ps(c);if(g>=b-1)return;let y=(F=Pt.current)==null?void 0:F.getMessages().find(q=>{var B;return((B=q.toolCall)==null?void 0:B.id)===c.getAttribute("data-tool-call-id")});y&&(Di(c,y,r,g+1),zn(c))};rr.addEventListener("click",c=>{var D,F,q,B,xe,me,ne,Ee,_e,Te,ot,Ke,dt,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=(D=y.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Eo(rr,Ie);let Le=(F=Pt.current)==null?void 0:F.getMessages().find(qe=>{var Qe;return((Qe=qe.toolCall)==null?void 0:Qe.id)===Ie});(q=Le==null?void 0:Le.agentMetadata)!=null&&q.awaitingLocalTool&&((B=Pt.current)==null||B.markAskUserQuestionResolved(Le),(xe=Pt.current)==null||xe.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=To(y);if(qe&&Le){let Qe=Zo(y)[gr(y)],Ct=new Set(Array.isArray(Qe)?Qe:[]);Ct.has(Ie)?Ct.delete(Ie):Ct.add(Ie),Mo(y,Array.from(Ct)),zn(y);return}if(qe){Mo(y,Ie),zn(y),Fr(y);return}if(Le){let Qe=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",Qe?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!Qe);let Ct=y.querySelector('[data-ask-user-action="submit-multi"]');Ct&&(Ct.disabled=$l(y).length===0);return}or(y,Ie,{source:"pick",values:[Ie]});return}if(E==="submit-multi"){let Ie=$l(y);if(Ie.length===0)return;or(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=(me=Ie==null?void 0:Ie.value)!=null?me:"";if(!Le.trim())return;if(To(y)){Mo(y,Le.trim()),zn(y),Fr(y);return}or(y,Le,{source:"free-text"});return}if(E==="next"||E==="back"){if(!Pt.current)return;let Ie=(ne=y.getAttribute("data-tool-call-id"))!=null?ne:"",Le=Pt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(_e=(Ee=qe==null?void 0:qe.value)==null?void 0:Ee.trim())!=null?_e:"";if(Qe){let Be=Zo(y)[gr(y)];(typeof Be!="string"||Be!==Qe)&&Mo(y,Qe)}let Ct=E==="next"?1:-1,P=gr(y)+Ct;Di(y,Le,r,P),zn(y);return}if(E==="submit-all"){if(!Pt.current)return;let Ie=(Te=y.getAttribute("data-tool-call-id"))!=null?Te:"",Le=Pt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(Ke=(ot=qe==null?void 0:qe.value)==null?void 0:ot.trim())!=null?Ke:"";Qe&&Mo(y,Qe);let Ct=Bi(y,Le);Pt.current.persistAskUserQuestionProgress(Le,{answers:Ct,currentIndex:gr(y)});let P=ro(Ct);or(y,P||"(submitted)",{source:"submit-all",structured:Ct});return}if(E==="skip"){if(!Pt.current)return;let Ie=(dt=y.getAttribute("data-tool-call-id"))!=null?dt:"",Le=Pt.current.getMessages().find(Oe=>{var he;return((he=Oe.toolCall)==null?void 0:he.id)===Ie});if(!Le)return;let qe=To(y),Qe=gr(y),Ct=Ps(y),P=Qe>=Ct-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Eo(rr,Ie),(pt=Le.agentMetadata)!=null&&pt.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(Le),Pt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}Mo(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),P){let Oe=Bi(y,Le),he=ro(Oe);or(y,he||"(skipped)",{source:"submit-all",structured:Oe});return}Di(y,Le,r,Qe+1),zn(y);return}}),rr.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let b=c.target;if(!((D=b.matches)!=null&&D.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(To(y)){Mo(y,E.trim()),zn(y),Fr(y);return}or(y,E,{source:"free-text"})}});let oo=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=rr.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),D=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];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",oo);let Vn=null,Dt=null,Pn=null,sr=null,so=()=>{};function $r(){sr==null||sr(),sr=null}let ao=()=>{var F;if(!Vn||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((F=e.ownerDocument.defaultView)!=null?F:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){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=Vn.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 D=y.offsetWidth-E/2;Dt.style.left=`${Math.max(0,D)}px`},kr=()=>{},Kn=()=>{var b,y,E,D,F;if(!Tt||!fr(r))return;$i(e,r),_i(e,r),kr();let c=(D=(E=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:E.narrowHostMaxWidth)!=null?D:520,g=fe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),Tt.update(qn),Ln?(Tt.setMobileOpen(!1),Tt.element.classList.add("persona-hidden"),(F=Tt.backdrop)==null||F.classList.add("persona-hidden")):qn.artifacts.length>0&&(Tt.element.classList.remove("persona-hidden"),Tt.setMobileOpen(!0)),so()};if(fr(r)){fe.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(z),Tt=Qm(r,{onSelect:b=>{var y;return(y=Pt.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{Ln=!0,Kn()}}),Tt.element.classList.add("persona-hidden"),Vn=g,g.appendChild(c),g.appendChild(Tt.element),Tt.backdrop&&fe.appendChild(Tt.backdrop),fe.appendChild(g),so=()=>{var y,E,D,F;if(!Vn||!Tt)return;if(!(((D=(E=(y=r.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:D.resizable)===!0)){Pn==null||Pn(),Pn=null,$r(),Dt&&(Dt.remove(),Dt=null),Tt.element.style.removeProperty("width"),Tt.element.style.removeProperty("maxWidth");return}if(!Dt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let B=e.ownerDocument,xe=(F=B.defaultView)!=null?F:window,me=ne=>{var dt,pt;if(!Tt||ne.button!==0||e.classList.contains("persona-artifact-narrow-host")||xe.innerWidth<=640)return;ne.preventDefault(),$r();let Ee=ne.clientX,_e=Tt.element.getBoundingClientRect().width,Te=(pt=(dt=r.features)==null?void 0:dt.artifacts)==null?void 0:pt.layout,ot=Ie=>{let Le=Vn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Qe=qe?0:tg(Vn,xe),Ct=qe?0:q.getBoundingClientRect().width||6,P=_e-(Ie.clientX-Ee),Be=ng(P,Le,Qe,Ct,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);Tt.element.style.width=`${Be}px`,Tt.element.style.maxWidth="none",ao()},Ke=()=>{B.removeEventListener("pointermove",ot),B.removeEventListener("pointerup",Ke),B.removeEventListener("pointercancel",Ke),sr=null;try{q.releasePointerCapture(ne.pointerId)}catch{}};sr=Ke,B.addEventListener("pointermove",ot),B.addEventListener("pointerup",Ke),B.addEventListener("pointercancel",Ke);try{q.setPointerCapture(ne.pointerId)}catch{}};q.addEventListener("pointerdown",me),Dt=q,Vn.insertBefore(q,Tt.element),Pn=()=>{q.removeEventListener("pointerdown",me)}}if(Dt){let q=qn.artifacts.length>0&&!Ln;Dt.classList.toggle("persona-hidden",!q),ao()}},kr=()=>{var xe,me,ne,Ee,_e,Te,ot,Ke,dt,pt,Ie,Le,qe,Qe;if(!T||!Tt||((me=(xe=r.launcher)==null?void 0:xe.sidebarMode)!=null?me:!1)||gn(r)&&mr(r).reveal==="emerge")return;let y=(ne=e.ownerDocument.defaultView)!=null?ne:window,E=(_e=(Ee=r.launcher)==null?void 0:Ee.mobileFullscreen)!=null?_e:!0,D=(ot=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?ot:640;if(E&&y.innerWidth<=D||!eg(r,T))return;let F=(pt=(dt=(Ke=r.launcher)==null?void 0:Ke.width)!=null?dt:r.launcherWidth)!=null?pt:er,q=(Qe=(qe=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:qe.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";qn.artifacts.length>0&&!Ln?(fe.style.width=q,fe.style.maxWidth=q):(fe.style.width=F,fe.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Un=new ResizeObserver(()=>{Kn()}),Un.observe(fe))}else fe.appendChild(z),$()&&Je&&(De.peekBanner&&Je.appendChild(De.peekBanner),Je.appendChild(je));e.appendChild(ve),Je&&e.appendChild(Je);let br=()=>{var Be,Oe,he,_t,Ot,Xt,At,Vt,Qn,sn,Ye,Wt,pn,pr,Yn,Bo,Do,gs,fs,Qt,No,ho,bo,Vr,at,vn,In,an;if($()){fe.style.width="100%",fe.style.maxWidth="100%";let ut=(Oe=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?Oe:{},yt=ve.dataset.state==="expanded",mt=(he=ut.expandedSize)!=null?he:"anchored";if(!(yt&&mt!=="fullscreen")){z.style.background="",z.style.border="",z.style.borderRadius="",z.style.overflow="",z.style.boxShadow="";return}let un=(Ot=(_t=r.theme)==null?void 0:_t.components)==null?void 0:Ot.panel,Hr=As(r),mn=(Fo,qa)=>{var Ys;return Fo==null||Fo===""?qa:(Ys=ws(Hr,Fo))!=null?Ys:Fo},Wn="1px solid var(--persona-border)",ur="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Oo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";z.style.background="var(--persona-surface, #ffffff)",z.style.border=mn(un==null?void 0:un.border,Wn),z.style.borderRadius=mn(un==null?void 0:un.borderRadius,Oo),z.style.boxShadow=mn(un==null?void 0:un.shadow,ur),z.style.overflow="hidden";return}let c=gn(r),g=(At=(Xt=r.launcher)==null?void 0:Xt.sidebarMode)!=null?At:!1,b=c||g||((Qn=(Vt=r.launcher)==null?void 0:Vt.fullHeight)!=null?Qn:!1),y=((sn=r.launcher)==null?void 0:sn.enabled)===!1,E=(Wt=(Ye=r.theme)==null?void 0:Ye.components)==null?void 0:Wt.panel,D=As(r),F=(ut,yt)=>{var mt;return ut==null||ut===""?yt:(mt=ws(D,ut))!=null?mt:ut},q=(pn=e.ownerDocument.defaultView)!=null?pn:window,B=(Yn=(pr=r.launcher)==null?void 0:pr.mobileFullscreen)!=null?Yn:!0,xe=(Do=(Bo=r.launcher)==null?void 0:Bo.mobileBreakpoint)!=null?Do:640,me=q.innerWidth<=xe,ne=B&&me&&T,Ee=(fs=(gs=r.launcher)==null?void 0:gs.position)!=null?fs:"bottom-left",_e=Ee==="bottom-left"||Ee==="top-left",Te=(No=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?No:Mn,ot=g||ne?"none":"1px solid var(--persona-border)",Ke=ne?"none":g?_e?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ne&&(Ke="none",ot="none");let dt=g||ne?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=F(E==null?void 0:E.border,ot),Ie=F(E==null?void 0:E.shadow,Ke),Le=F(E==null?void 0:E.borderRadius,dt),qe=ue.scrollTop;e.style.cssText="",ve.style.cssText="",fe.style.cssText="",z.style.cssText="",ue.style.cssText="",je.style.cssText="";let Qe=()=>{var yt;if(qe<=0)return;((yt=ue.ownerDocument.defaultView)!=null?yt:window).requestAnimationFrame(()=>{if(ue.scrollTop===qe)return;let mt=ue.scrollHeight-ue.clientHeight;mt<=0||(ue.scrollTop=Math.min(qe,mt))})};if(ne){ve.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"),ve.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -37,9 +37,9 @@ _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: ${Te} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
- `,oe.style.cssText=`
42
+ `,fe.style.cssText=`
43
43
  position: relative !important;
44
44
  display: flex !important;
45
45
  flex-direction: column !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
+ `,z.style.cssText=`
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
58
  flex: 1 1 0% !important;
@@ -63,20 +63,20 @@ _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
+ `,ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",je.style.flexShrink="0",k=!0,Qe();return}let Ct=(bo=(ho=r==null?void 0:r.launcher)==null?void 0:ho.width)!=null?bo:r==null?void 0:r.launcherWidth,P=Ct!=null?Ct:er;if(!g&&!c)y&&b?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=P,fe.style.maxWidth=P);else if(c)if(mr(r).reveal==="emerge"){let yt=mr(r).width;fe.style.width=yt,fe.style.maxWidth=yt}else fe.style.width="100%",fe.style.maxWidth="100%";if(kr(),fe.style.boxShadow=Ie,fe.style.borderRadius=Le,z.style.border=pt,z.style.borderRadius=Le,c&&!ne&&(E==null?void 0:E.border)===void 0&&(z.style.border="none",mr(r).side==="right"?z.style.borderLeft="1px solid var(--persona-border)":z.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%"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.height="100%",y&&(ve.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.height="100%",fe.style.overflow="hidden",z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.overflow="hidden",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",je.style.flexShrink="0"),ve.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&&((Vr=Sr[Ee])!=null?Vr:Sr["bottom-right"]).split(" ").forEach(yt=>ve.classList.add(yt)),g){let ut=(vn=(at=r.launcher)==null?void 0:at.sidebarWidth)!=null?vn:"420px";ve.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${Dt} !important;
70
+ width: ${ut} !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;"}
79
- `,oe.style.cssText=`
77
+ z-index: ${Te} !important;
78
+ ${_e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
+ `,fe.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
82
82
  flex-direction: column !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
+ `,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),z.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
+ `,je.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 ut="max-height: -moz-available !important; max-height: stretch !important;",yt=g?"":"padding-top: 1.25em !important;",mt=g?"":`z-index: ${(an=(In=r.launcher)==null?void 0:In.zIndex)!=null?an:Mn} !important;`;ve.style.cssText+=ut+yt+mt}Qe()};br(),xo(e,r),$i(e,r),_i(e,r);let bt=[];bt.push(()=>{document.removeEventListener("keydown",oo)});let en=null,tn=null;bt.push(()=>{en==null||en(),en=null,tn==null||tn(),tn=null}),Un&&bt.push(()=>{Un==null||Un.disconnect(),Un=null}),bt.push(()=>{Pn==null||Pn(),Pn=null,$r(),Dt&&(Dt.remove(),Dt=null),Tt==null||Tt.element.style.removeProperty("width"),Tt==null||Tt.element.style.removeProperty("maxWidth")}),We&&bt.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),V==null||V.destroy(),V=null,le==null||le.destroy(),le=null,Q=null});let Jn=null,io=()=>{Jn&&(Jn(),Jn=null),r.colorScheme==="auto"&&(Jn=gi(()=>{xo(e,r)}))};io(),bt.push(()=>{Jn&&(Jn(),Jn=null)});let ye=(cd=r.features)==null?void 0:cd.streamAnimation;if(ye!=null&&ye.type&&ye.type!=="none"){let c=ua(ye.type,ye.plugins);c&&(Cl(c,e),bt.push(()=>bm(e)))}let ar=qm(kt),ir=null,_,Lr=!1,_r=sm(),jr=new Map,Pr=new Map,yr=new Map,Bs=0,Gn=bi(),Xn=0,xr=null,vr=!1,Io=!1,Ur=0,An=null,Ir=null,os=!1,Wo=!1,ss=null,ka=4,as=24,La=80,is=new Map,xt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ds=(pd=(dd=r.voiceRecognition)==null?void 0:dd.autoResume)!=null?pd:!1,lr=c=>{s.emit("voice:state",{active:xt.active,source:c,timestamp:Date.now()})},Nn=()=>{m(c=>({...c,voiceState:{active:xt.active,timestamp:Date.now(),manuallyDeactivated:xt.manuallyDeactivated}}))},Pa=()=>{var y,E;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Kl(d.voiceState),g=!!c.active,b=Number((E=c.timestamp)!=null?E:0);xt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<Tb&&setTimeout(()=>{var D,F;xt.active||(xt.manuallyDeactivated=!1,((F=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:F.type)==="runtype"?_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),lr("restore"),_.isVoiceActive()&&Gs()}):fn("restore"))},1e3)},Ia=()=>_?cg(_.getMessages()).filter(c=>!c.__skipPersist):[];function ls(c){if(!(i!=null&&i.save))return;let b={messages:c?cg(c):_?Ia():[],metadata:d,artifacts:qn.artifacts,selectedArtifactId:qn.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 qr=null,Ns=()=>ve.querySelector("#persona-scroll-container")||ue,lo=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null),vr=!1},Os=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!1,lo()},Fs=()=>{Ur>0?(wn.textContent=String(Ur),wn.style.display="",et.setAttribute("aria-label",`${Gt()||"Jump to latest"} (${Ur} new)`)):(wn.textContent="",wn.style.display="none",et.setAttribute("aria-label",Gt()||"Jump to latest"))},$s=()=>{Ur!==0&&(Ur=0,Fs())},_s=()=>ft()==="follow"?!Gn.isFollowing():!Xo(ue,as),On=()=>{if(!xn()||se){et.parentNode&&et.remove(),et.style.display="none";return}et.parentNode!==z&&z.appendChild(et),yn();let g=Xr(ue)>0&&_s();g||$s(),et.style.display=g?"":"none"},cs=()=>{Gn.pause()&&(Os(),On())},Wr=()=>{Gn.resume(),$s(),On()},Rr=(c=!1)=>{ft()==="follow"&&Gn.isFollowing()&&(!c&&!Lr||(xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!0,xr=requestAnimationFrame(()=>{xr=null,Io=!1,Gn.isFollowing()&&Wa(Ns(),c?220:140)})))},js=(c,g,b,y=()=>!0)=>{let E=c.scrollTop,D=g(),F=D-E;lo();let q=performance.now();vr=!0;let B=me=>1-Math.pow(1-me,3),xe=me=>{if(!y()){lo();return}let ne=g();ne!==D&&(D=ne,F=D-E);let Ee=me-q,_e=Math.min(Ee/b,1),Te=B(_e),ot=E+F*Te;c.scrollTop=ot,Xn=c.scrollTop,_e<1?qr=requestAnimationFrame(xe):(c.scrollTop=D,Xn=c.scrollTop,qr=null,vr=!1)};qr=requestAnimationFrame(xe)},Wa=(c,g=500)=>{let b=Xr(c)-c.scrollTop;if(Math.abs(b)<1){Xn=c.scrollTop;return}if(Math.abs(b)>=La){lo(),vr=!0,c.scrollTop=Xr(c),Xn=c.scrollTop,vr=!1;return}js(c,()=>Xr(c),g,()=>Gn.isFollowing())},Us=()=>{let c=Ns();vr=!0,c.scrollTop=Xr(c),Xn=c.scrollTop,vr=!1,On()},qs=c=>{Cn.style.height=`${Math.max(0,Math.round(c))}px`,An&&(An.spacerHeight=Math.max(0,c))},Ro=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),lo(),An=null,Cn.style.height="0px"},Ra=c=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var xe;Ir=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=ue.querySelector(`[data-message-id="${g}"]`);if(!b)return;let y=0,E=b;for(;E&&E!==ue;)y+=E.offsetTop,E=E.offsetParent;let D=(xe=An==null?void 0:An.spacerHeight)!=null?xe:0,F=ue.scrollHeight-D,{targetScrollTop:q,spacerHeight:B}=dm({anchorOffsetTop:y,topOffset:Lt(),viewportHeight:ue.clientHeight,contentHeight:F});An={initialSpacerHeight:B,contentHeightAtAnchor:F,spacerHeight:B},qs(B),js(ue,()=>q,220)})},Ha=()=>{if(ft()==="follow"){if(!Gn.isFollowing()||Xo(ue,1))return;Rr(!Lr);return}if(An&&An.initialSpacerHeight>0){let c=ue.scrollHeight-An.spacerHeight,g=pm({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:c});g!==An.spacerHeight&&qs(g)}On()},Ba=c=>{let g=ft();g==="follow"?(Wr(),Rr(!0)):g==="anchor-top"&&Ra(c)},Da=c=>{let g=new Map;c.forEach(b=>{let y=is.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&(s.emit("assistant:message",b),!Wo&&ft()!=="anchor-top"&&_s()&&(Ur+=1,Fs(),On())),b.role==="assistant"&&(y!=null&&y.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(y?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),is.clear(),g.forEach((b,y)=>{is.set(y,b)})},Ho=(c,g,b)=>{var pt,Ie,Le,qe,Qe,Ct;let y=document.createElement("div"),D=(()=>{var Be;let P=o.find(Oe=>Oe.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),F=(P,Be)=>Be==null?!1:typeof Be=="string"?(P.textContent=Be,!0):(P.appendChild(Be),!0),q=new Set,B=new Set,xe=o.some(P=>P.renderAskUserQuestion),me=[],ne=[],Ee=r.enableComponentStreaming!==!1,_e=o.some(P=>P.renderApproval)&&r.approval!==!1,Te=[];if(g.forEach(P=>{var Ye,Wt,pn,pr,Yn,Bo,Do,gs,fs,Qt,No,ho,bo,Vr;q.add(P.id);let Be=xe&&Yr(P),Oe=_e&&P.variant==="approval"&&!!P.approval,he=!Be&&P.role==="assistant"&&!P.variant&&Ee&&zi(P);if(!Oe&&yr.has(P.id)){let at=c.querySelector(`#wrapper-${P.id}`);at==null||at.removeAttribute("data-preserve-runtime"),yr.delete(P.id)}if(!he&&Pr.has(P.id)){let at=c.querySelector(`#wrapper-${P.id}`);at==null||at.removeAttribute("data-preserve-runtime"),Pr.delete(P.id)}let _t=Yr(P)?`:${(Ye=P.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Wt=P.agentMetadata)!=null&&Wt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=om(P,Bs)+_t,Xt=Be||Oe||he?null:am(_r,P.id,Ot);if(Xt){y.appendChild(Xt.cloneNode(!0)),Yr(P)&&((pn=P.toolCall)!=null&&pn.id)&&((pr=P.agentMetadata)==null?void 0:pr.awaitingLocalTool)===!0&&!((Yn=P.agentMetadata)!=null&&Yn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Is(P,r,De.composerOverlay));return}let At=null,Vt=o.find(at=>!!(P.variant==="reasoning"&&at.renderReasoning||P.variant==="tool"&&at.renderToolCall||!P.variant&&at.renderMessage)),Qn=(Bo=r.layout)==null?void 0:Bo.messages;if(Yr(P)&&((Do=P.agentMetadata)==null?void 0:Do.askUserQuestionAnswered)===!0){jr.delete(P.id);let at=c.querySelector(`#wrapper-${P.id}`);at==null||at.removeAttribute("data-preserve-runtime");return}if(Yr(P)&&((fs=(gs=r.features)==null?void 0:gs.askUserQuestion)==null?void 0:fs.enabled)!==!1){let at=o.find(vn=>typeof vn.renderAskUserQuestion=="function");if(at&&Pt.current){let vn=jr.get(P.id),In=vn!==Ot,an=null;if(In){let{payload:mt,complete:Fn}=Zr(P),un=P.id,Hr=()=>{var mn;return(mn=Pt.current)==null?void 0:mn.getMessages().find(Wn=>Wn.id===un)};an=at.renderAskUserQuestion({message:P,payload:mt,complete:Fn,resolve:mn=>{var ur;let Wn=Hr();Wn&&((ur=Pt.current)==null||ur.resolveAskUserQuestion(Wn,mn))},dismiss:()=>{var Wn,ur,Oo;let mn=Hr();(Wn=mn==null?void 0:mn.agentMetadata)!=null&&Wn.awaitingLocalTool&&((ur=Pt.current)==null||ur.markAskUserQuestionResolved(mn),(Oo=Pt.current)==null||Oo.resolveAskUserQuestion(mn,"(dismissed)"))},config:r})}let ut=vn!=null;if(In&&an===null&&!ut){((Qt=P.agentMetadata)==null?void 0:Qt.awaitingLocalTool)===!0&&!((No=P.agentMetadata)!=null&&No.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Is(P,r,De.composerOverlay));return}let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${P.id}`,yt.setAttribute("data-wrapper-id",P.id),yt.setAttribute("data-ask-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),y.appendChild(yt),me.push({messageId:P.id,fingerprint:Ot,bubble:an});return}else{((ho=P.agentMetadata)==null?void 0:ho.awaitingLocalTool)===!0&&!((bo=P.agentMetadata)!=null&&bo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Is(P,r,De.composerOverlay));return}}else if(Oe){let at=o.find(ut=>typeof ut.renderApproval=="function"),In=yr.get(P.id)!==Ot,an=null;if(In&&(at!=null&&at.renderApproval)){let ut=P.id,yt=(mt,Fn)=>{var Hr,mn,Wn;let un=(Hr=Pt.current)==null?void 0:Hr.getMessages().find(ur=>ur.id===ut);un!=null&&un.approval&&(un.approval.toolType==="webmcp"?(mn=Pt.current)==null||mn.resolveWebMcpApproval(un.id,mt):(Wn=Pt.current)==null||Wn.resolveApproval(un.approval,mt,Fn))};an=at.renderApproval({message:P,defaultRenderer:()=>Oi(P,r),config:r,approve:mt=>yt("approved",mt),deny:mt=>yt("denied",mt)})}if(In&&an===null){let ut=c.querySelector(`#wrapper-${P.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),yr.delete(P.id),At=Oi(P,r)}else{let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${P.id}`,ut.setAttribute("data-wrapper-id",P.id),ut.setAttribute("data-approval-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),Te.push({messageId:P.id,fingerprint:Ot,bubble:an});return}}else if(Vt)if(P.variant==="reasoning"&&P.reasoning&&Vt.renderReasoning){if(!ze)return;At=Vt.renderReasoning({message:P,defaultRenderer:()=>Wl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&Vt.renderToolCall){if(!Ae)return;At=Vt.renderToolCall({message:P,defaultRenderer:()=>Rl(P,r),config:r})}else Vt.renderMessage&&(At=Vt.renderMessage({message:P,defaultRenderer:()=>{let at=Es(P,b,Qn,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r});return P.role!=="user"&&ql(at,P,r,_),at},config:r}));if(!At&&he){let at=Vi(P);if(at){let vn=Pr.get(P.id),In=vn!==Ot,an=r.wrapComponentDirectiveInBubble!==!1,ut=null;if(In){let yt=qi(at,{config:r,message:P,transform:b});if(yt)if(an){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-${P.id}`,mt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let Fn=document.createElement("div");Fn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Fn.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),mt.appendChild(Fn)}mt.appendChild(yt),ut=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-${P.id}`,mt.setAttribute("data-message-id",P.id),mt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let Fn=document.createElement("div");Fn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Fn.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),mt.appendChild(Fn)}mt.appendChild(yt),ut=mt}}if(ut||vn!=null){let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${P.id}`,yt.setAttribute("data-wrapper-id",P.id),yt.setAttribute("data-component-directive-stub","true"),yt.setAttribute("data-preserve-runtime","true"),an||yt.classList.add("persona-w-full"),y.appendChild(yt),ne.push({messageId:P.id,fingerprint:Ot,bubble:ut});return}}}if(!At)if(P.variant==="reasoning"&&P.reasoning){if(!ze)return;At=Wl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ae)return;At=Rl(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;At=Oi(P,r)}else{let at=(Vr=r.layout)==null?void 0:Vr.messages;at!=null&&at.renderUserMessage&&P.role==="user"?At=at.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):at!=null&&at.renderAssistantMessage&&P.role==="assistant"?At=at.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):At=Es(P,b,at,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r}),P.role!=="user"&&At&&ql(At,P,r,_)}let sn=document.createElement("div");sn.className="persona-flex",sn.id=`wrapper-${P.id}`,sn.setAttribute("data-wrapper-id",P.id),P.role==="user"&&sn.classList.add("persona-justify-end"),(At==null?void 0:At.getAttribute("data-persona-component-directive"))==="true"&&sn.classList.add("persona-w-full"),sn.appendChild(At),im(_r,P.id,Ot,sn),y.appendChild(sn)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Oe=Be.getAttribute("data-persona-ask-sheet-for");Oe&&!B.has(Oe)&&Eo(De.composerOverlay,Oe)}),(Ie=(pt=r.features)==null?void 0:pt.toolCallDisplay)!=null&&Ie.grouped){let P=[],Be=[];g.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&Ae){Be.push(Oe);return}Be.length>1&&P.push(Be),Be=[]}),Be.length>1&&P.push(Be),P.forEach((Oe,he)=>{var Ye,Wt;let _t=Oe.map(pn=>Array.from(y.children).find(pr=>pr instanceof HTMLElement&&pr.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if(_t.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${he}-${Oe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${he}-${Oe[0].id}`);let Xt=document.createElement("div");Xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Xt.setAttribute("data-persona-tool-group","true");let At=document.createElement("div");At.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Vt=`Called ${Oe.length} tools`,Qn=(Wt=(Ye=r.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Wt.call(Ye,{messages:Oe,toolCalls:Oe.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:Vt,config:r});F(At,Qn)||(At.textContent=Vt);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",Xt.append(At,sn),Ot.appendChild(Xt),_t[0].before(Ot),_t.forEach((pn,pr)=>{let Yn=document.createElement("div");Yn.className="persona-tool-group-item persona-relative",Yn.setAttribute("data-persona-tool-group-item","true"),pr<_t.length-1&&Yn.setAttribute("data-persona-tool-group-connector","true"),Yn.appendChild(pn),sn.appendChild(Yn)})})}lm(_r,q);let ot=g.some(P=>P.role==="assistant"&&P.streaming),Ke=g[g.length-1],dt=(Ke==null?void 0:Ke.role)==="assistant"&&!Ke.streaming&&Ke.variant!=="approval";if(Lr&&g.some(P=>P.role==="user")&&!ot&&!dt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:Yo},Be=o.find(he=>he.renderLoadingIndicator),Oe=null;if(Be!=null&&Be.renderLoadingIndicator&&(Oe=Be.renderLoadingIndicator(P)),Oe===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Oe=r.loadingIndicator.render(P)),Oe===null&&(Oe=Yo()),Oe){let he=document.createElement("div"),_t=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;he.className=_t?["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(" "),he.setAttribute("data-typing-indicator","true"),he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",he.appendChild(Oe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(he),y.appendChild(Ot)}}if(!Lr&&g.length>0){let P=g[g.length-1],Be={config:r,lastMessage:P,messageCount:g.length},Oe=o.find(_t=>_t.renderIdleIndicator),he=null;if(Oe!=null&&Oe.renderIdleIndicator&&(he=Oe.renderIdleIndicator(Be)),he===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(he=r.loadingIndicator.renderIdle(Be)),he){let _t=document.createElement("div"),Ot=((Ct=r.loadingIndicator)==null?void 0:Ct.showBubble)!==!1;_t.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(" "),_t.setAttribute("data-idle-indicator","true"),_t.appendChild(he);let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id="wrapper-idle-indicator",Xt.setAttribute("data-wrapper-id","idle-indicator"),Xt.appendChild(_t),y.appendChild(Xt)}}if(fi(c,y),me.length>0)for(let{messageId:P,fingerprint:Be,bubble:Oe}of me){let he=c.querySelector(`#wrapper-${P}`);he&&Oe!==null&&(he.replaceChildren(Oe),he.setAttribute("data-bubble-fp",Be),jr.set(P,Be))}if(jr.size>0)for(let P of jr.keys())q.has(P)||jr.delete(P);if(ne.length>0)for(let{messageId:P,fingerprint:Be,bubble:Oe}of ne){let he=c.querySelector(`#wrapper-${P}`);he&&Oe!==null&&(he.replaceChildren(Oe),he.setAttribute("data-bubble-fp",Be),Pr.set(P,Be))}if(Pr.size>0)for(let P of Pr.keys())q.has(P)||Pr.delete(P);if(Te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Oe}of Te){let he=c.querySelector(`#wrapper-${P}`);he&&Oe!==null&&(he.replaceChildren(Oe),he.setAttribute("data-bubble-fp",Be),yr.set(P,Be))}if(yr.size>0)for(let P of yr.keys())q.has(P)||yr.delete(P)},co=null,Na=()=>{var b;if(co)return;let c=y=>{let E=y.composedPath();E.includes(ve)||Je&&E.includes(Je)||Nt(!1,"user")};co=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},zs=()=>{var g;if(!co)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",co,!0),co=null};bt.push(()=>zs());let po=null,Oa=()=>{var b;if(po)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Nt(!1,"user"))};po=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Vs=()=>{var g;if(!po)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",po,!0),po=null};bt.push(()=>Vs());let uo=!1,Ks=new Set,Fa=()=>{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)},zr=()=>{var dt,pt,Ie,Le;if(!$())return;let c=De.peekBanner,g=De.peekTextNode;if(!c||!g)return;if(H){c.classList.remove("persona-pill-peek--visible");return}let b=(dt=_==null?void 0:_.getMessages())!=null?dt:[],y;for(let qe=b.length-1;qe>=0;qe--){let Qe=b[qe];if(Qe.role==="assistant"&&Qe.content){y=Qe;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let E=y.content,D=!!y.streaming,F=Fa(),q=vi(F),B=q.type!=="none"?ua(q.type,F==null?void 0:F.plugins):null,xe=((pt=B==null?void 0:B.isAnimating)==null?void 0:pt.call(B,y))===!0,me=B!==null&&(D||xe);me&&B&&!Ks.has(B.name)&&(Cl(B,e),Ks.add(B.name));let ne=me&&(B!=null&&B.containerClass)?B.containerClass:null,Ee=(Ie=g.dataset.personaPeekStreamClass)!=null?Ie:null;Ee&&Ee!==ne&&(g.classList.remove(Ee),delete g.dataset.personaPeekStreamClass),ne&&Ee!==ne&&(g.classList.add(ne),g.dataset.personaPeekStreamClass=ne),me?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let _e=me?wi(E,q.buffer,B,y,D):E;if(me&&q.placeholder==="skeleton"&&D&&(!_e||!_e.trim())){let qe=document.createElement("div"),Qe=ga();Qe.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Qe),fi(g,qe)}else{let qe=Math.max(0,_e.length-100),Qe=_e.length>100?_e.slice(-100):_e,Ct=Uo(Qe);if(!me||!B){let P=_e.length>100?`\u2026${Qe}`:Qe;g.textContent!==P&&(g.textContent=P)}else{let P=Ct;(B.wrap==="char"||B.wrap==="word")&&(P=ma(Ct,B.wrap,`peek-${y.id}`,{skipTags:B.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=P,B.useCaret&&Qe.length>0){let Oe=Ci(),he=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),_t=he[he.length-1];_t!=null&&_t.parentNode?_t.parentNode.insertBefore(Oe,_t.nextSibling):Be.appendChild(Oe)}fi(g,Be),(Le=B.onAfterRender)==null||Le.call(B,{container:g,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Ke=Lr||uo;c.classList.toggle("persona-pill-peek--visible",Ke)};if($()){let c=De.peekBanner;if(c){let y=E=>{E.preventDefault(),E.stopPropagation(),Nt(!0,"user")};c.addEventListener("pointerdown",y),bt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{uo||(uo=!0,zr())},b=()=>{uo&&(uo=!1,zr())};fe.addEventListener("pointerenter",g),fe.addEventListener("pointerleave",b),bt.push(()=>{fe.removeEventListener("pointerenter",g),fe.removeEventListener("pointerleave",b)}),Je&&(Je.addEventListener("pointerenter",g),Je.addEventListener("pointerleave",b),bt.push(()=>{Je.removeEventListener("pointerenter",g),Je.removeEventListener("pointerleave",b)}))}let $a=c=>{var Ee,_e,Te,ot,Ke,dt,pt,Ie;let g=(_e=(Ee=r.launcher)==null?void 0:Ee.composerBar)!=null?_e:{},b=(Te=g.expandedSize)!=null?Te:"anchored",y=(ot=g.bottomOffset)!=null?ot:"16px",E=g.collapsedMaxWidth,D=(Ke=g.expandedMaxWidth)!=null?Ke:"880px",F=(dt=g.expandedTopOffset)!=null?dt:"5vh",q=(pt=g.modalMaxWidth)!=null?pt:"880px",B=(Ie=g.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",xe="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",ne=ve.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Je){let Le=Je.style;Le.bottom=y,Le.width=E!=null?E:""}if(c&&b!=="fullscreen"){if(b==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=q,ne.maxWidth=xe,ne.maxHeight=B,ne.height=B;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${y} + ${me})`,ne.top=F,ne.width=D,ne.maxWidth=xe}},mo=()=>{var B,xe,me,ne,Ee,_e,Te,ot;if(!O())return;if($()){let dt=(me=((xe=(B=r.launcher)==null?void 0:B.composerBar)!=null?xe:{}).expandedSize)!=null?me:"anchored",pt=H?"expanded":"collapsed";ve.dataset.state=pt,ve.dataset.expandedSize=dt,Je&&(Je.dataset.state=pt,Je.dataset.expandedSize=dt),ve.style.removeProperty("display"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),$a(H),z.style.display=H?"flex":"none",br(),H?(Na(),Oa()):(zs(),Vs()),zr();return}let c=gn(r),g=(ne=e.ownerDocument.defaultView)!=null?ne:window,b=(_e=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?_e:640,y=(ot=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?ot:!0,E=g.innerWidth<=b,D=y&&E&&T,F=mr(r).reveal;H?(ve.style.removeProperty("display"),ve.style.display=c?"flex":"",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),nn?nn.element.style.display="none":rn&&(rn.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!D?(ve.style.removeProperty("display"),ve.style.display="flex",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.setProperty("display","none","important"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.display="",ve.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),nn?nn.element.style.display=c?"none":"":rn&&(rn.style.display=c?"none":""))},Nt=(c,g="user")=>{var D,F;if(!O()||H===c)return;let b=H;H=c,mo();let y=(()=>{var Te,ot,Ke,dt,pt,Ie,Le,qe,Qe,Ct;let q=(ot=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?ot:!1,B=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,xe=(pt=(dt=r.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,me=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,ne=B.innerWidth<=me,Ee=gn(r)&&xe&&ne,_e=$()&&((Ct=(Qe=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Qe.expandedSize)!=null?Ct:"fullscreen")==="fullscreen";return q||xe&&ne&&T||Ee||_e})();if(H&&y){if(!en){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(en=Al(B,(F=(D=r.launcher)==null?void 0:D.zIndex)!=null?F:Mn))}tn||(tn=Sl(e.ownerDocument))}else H||(en==null||en(),en=null,tn==null||tn(),tn=null);H&&(Xs(),ft()==="follow"?Rr(!0):Us());let E={open:H,source:g,timestamp:Date.now()};H&&!b?s.emit("widget:opened",E):!H&&b&&s.emit("widget:closed",E),s.emit("widget:state",{open:H,launcherEnabled:T,voiceActive:xt.active,streaming:_.isStreaming()})},ds=c=>{Yt(c?"stop":"send"),K&&(K.disabled=c),ar.buttons.forEach(g=>{g.disabled=c}),je.dataset.personaComposerStreaming=c?"true":"false",je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},ps=()=>{xt.active||te&&te.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ps(),200)});let Js=()=>{var b,y,E,D,F,q,B,xe,me,ne,Ee;nr.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",Tr.textContent=(D=(E=r.copy)==null?void 0:E.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",te.placeholder=(q=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?q:"How can I help...";let c=ue.querySelector("[data-persona-intro-card]");if(c){let _e=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!((me=(xe=r.sendButton)==null?void 0:xe.useIcon)!=null&&me)&&!(_!=null&&_.isStreaming())&&(Ve.textContent=(Ee=(ne=r.copy)==null?void 0:ne.sendButtonLabel)!=null?Ee:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.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 cr=null,Xe=()=>{cr==null&&(cr=setInterval(()=>{let c=rt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(cr),cr=null;return}let g=Date.now();c.forEach(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=Ga(g-y))})},100))};if(_=new vs(r,{onMessagesChanged(c){var y;Ho(rt,c,Me),Xe(),_&&(c.some(D=>D.role==="user")?ar.render([],_,te,c):ar.render(r.suggestionChips,_,te,c,r.suggestionChipsConfig)),Rr(!Lr),Da(c);let g=[...c].reverse().find(E=>E.role==="user");c.length===0&&Ro(),!os||Wo?(os=!0,ss=(y=g==null?void 0:g.id)!=null?y:null):g&&g.id!==ss&&(ss=g.id,Ba(g.id));let b=xt.lastUserMessageId;g&&g.id!==b&&(xt.lastUserMessageId=g.id,s.emit("user:message",g)),xt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ls(c),zr()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};Ze(ln,(E=>{var D,F,q,B;return E==="idle"?(D=g.idleText)!=null?D:En.idle:E==="connecting"?(F=g.connectingText)!=null?F:En.connecting:E==="connected"?(q=g.connectedText)!=null?q:En.connected:E==="error"?(B=g.errorText)!=null?B:En.error:En[E]})(c),g,c)},onStreamingChanged(c){Lr=c,ds(c),_&&Ho(rt,_.getMessages(),Me),c||Rr(!0),zr()},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":go(),Yg();break;case"speaking":go(),Zg();break;default:c==="idle"&&_.isBargeInActive()?(go(),Gs(),K==null||K.setAttribute("aria-label","End voice session")):(xt.active=!1,go(),lr("system"),Nn());break}},onArtifactsState(c){qn=c,Kn(),ls()}}),Pt.current=_,os=!0,((md=(ud=r.voiceRecognition)==null?void 0:ud.provider)==null?void 0:md.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)}),(le||r.onSSEEvent)&&_.setSSEEventCallback((c,g)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,g),ge==null||ge.processEvent(c,g),le==null||le.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;if(c){if(c.metadata&&(d=Kl(c.metadata),w.syncFromMetadata()),(g=c.messages)!=null&&g.length){Wo=!0;try{_.hydrateMessages(c.messages)}finally{Wo=!1}}(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 A=()=>{var g,b,y;!$()||H||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||Nt(!0,"auto")},j=c=>{var E;if(c.preventDefault(),_.isStreaming()){_.cancel(),ge==null||ge.reset(),V==null||V.update();return}let g=te.value.trim(),b=(E=St==null?void 0:St.hasAttachments())!=null?E:!1;if(!g&&!b)return;A();let y;b&&(y=[],y.push(...St.getContentParts()),g&&y.push(oa(g))),te.value="",te.style.height="auto",G(),_.sendMessage(g,{contentParts:y}),b&&St.clearAttachments()},L=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Y={...hi},oe=!1,G=()=>{Y={...hi}},Pe=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Fe=c=>{if(!te)return;oe=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),oe=!1;let g=te.value.length;te.setSelectionRange(g,g)},lt=()=>{oe||G()},tt=c=>{if(te){if(L()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=te.selectionStart===0&&te.selectionEnd===0,b=rm({direction:c.key==="ArrowUp"?"up":"down",history:Pe(),currentValue:te.value,atStart:g,state:Y});if(Y=b.state,b.handled){c.preventDefault(),b.value!==void 0&&Fe(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}G(),c.preventDefault(),Ve.click()}}},Ht=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(z)&&(_.cancel(),ge==null||ge.reset(),V==null||V.update(),G(),c.preventDefault(),c.stopImmediatePropagation())},jt=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!St)return;let g=Mb(c.clipboardData);g.length!==0&&(c.preventDefault(),await St.handleFiles(g))},$t=null,ct=!1,Et=null,Ue=null,Sn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fn=(c="user")=>{var D,F,q,B,xe,me,ne;if(ct||_.isStreaming())return;let g=Sn();if(!g)return;$t=new g;let y=(F=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?F:2e3;$t.continuous=!0,$t.interimResults=!0,$t.lang="en-US";let E=te.value;$t.onresult=Ee=>{let _e="",Te="";for(let Ke=0;Ke<Ee.results.length;Ke++){let dt=Ee.results[Ke],pt=dt[0].transcript;dt.isFinal?_e+=pt+" ":Te=pt}let ot=E+_e+Te;te.value=ot,Et&&clearTimeout(Et),(_e||Te)&&(Et=window.setTimeout(()=>{let Ke=te.value.trim();Ke&&$t&&ct&&(Ut(),te.value="",te.style.height="auto",_.sendMessage(Ke,{viaVoice:!0}))},y))},$t.onerror=Ee=>{Ee.error!=="no-speech"&&Ut()},$t.onend=()=>{if(ct){let Ee=te.value.trim();Ee&&Ee!==E.trim()&&(te.value="",te.style.height="auto",_.sendMessage(Ee,{viaVoice:!0})),Ut()}};try{if($t.start(),ct=!0,xt.active=!0,c!=="system"&&(xt.manuallyDeactivated=!1),lr(c),Nn(),K){let Ee=(q=r.voiceRecognition)!=null?q:{};Ue={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(B=Ee.iconName)!=null?B:"mic",iconSize:parseFloat((ne=(me=Ee.iconSize)!=null?me:(xe=r.sendButton)==null?void 0:xe.size)!=null?ne:"40")||24};let _e=Ee.recordingBackgroundColor,Te=Ee.recordingIconColor,ot=Ee.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let Ke=K.querySelector("svg");Ke&&Ke.setAttribute("stroke",Te)}ot&&(K.style.borderColor=ot),K.setAttribute("aria-label","Stop voice recognition")}}catch{Ut("system")}},Ut=(c="user")=>{if(ct){if(ct=!1,Et&&(clearTimeout(Et),Et=null),$t){try{$t.stop()}catch{}$t=null}if(xt.active=!1,lr(c),Nn(),K){if(K.classList.remove("persona-voice-recording"),Ue){K.style.backgroundColor=Ue.backgroundColor,K.style.color=Ue.color,K.style.borderColor=Ue.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",Ue.color||"currentColor"),Ue=null}K.setAttribute("aria-label","Start voice recognition")}}},wr=(c,g)=>{var dt,pt,Ie,Le,qe,Qe,Ct,P;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((dt=c==null?void 0:c.provider)==null?void 0:dt.type)==="runtype";if(!(b||y))return null;let D=h("div","persona-send-button-wrapper"),F=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",B=(Ie=g==null?void 0:g.size)!=null?Ie:"40px",xe=(Le=c==null?void 0:c.iconSize)!=null?Le:B,me=parseFloat(xe)||24,ne=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,Ee=(Qe=c==null?void 0:c.iconColor)!=null?Qe:g==null?void 0:g.textColor;F.style.width=xe,F.style.height=xe,F.style.minWidth=xe,F.style.minHeight=xe,F.style.fontSize="18px",F.style.lineHeight="1",Ee?F.style.color=Ee:F.style.color="var(--persona-text, #111827)";let Te=Ce(q,me,Ee||"currentColor",1.5);Te?F.appendChild(Te):F.textContent="\u{1F3A4}",ne?F.style.backgroundColor=ne:F.style.backgroundColor="",c!=null&&c.borderWidth&&(F.style.borderWidth=c.borderWidth,F.style.borderStyle="solid"),c!=null&&c.borderColor&&(F.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(F.style.paddingLeft=c.paddingX,F.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(F.style.paddingTop=c.paddingY,F.style.paddingBottom=c.paddingY),D.appendChild(F);let ot=(Ct=c==null?void 0:c.tooltipText)!=null?Ct:"Start voice recognition";if(((P=c==null?void 0:c.showTooltip)!=null?P:!1)&&ot){let Be=h("div","persona-send-button-tooltip");Be.textContent=ot,D.appendChild(Be)}return{micButton:F,micButtonWrapper:D}},sl=()=>{var g,b,y,E,D;if(!K||Ue)return;let c=(g=r.voiceRecognition)!=null?g:{};Ue={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((D=(E=c.iconSize)!=null?E:(y=r.sendButton)==null?void 0:y.size)!=null?D:"40")||24}},al=(c,g)=>{var D,F,q,B,xe;if(!K)return;let b=K.querySelector("svg");b&&b.remove();let y=(xe=Ue==null?void 0:Ue.iconSize)!=null?xe:parseFloat((B=(q=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(F=r.sendButton)==null?void 0:F.size)!=null?B:"40")||24,E=Ce(c,y,g,1.5);E&&K.appendChild(E)},_a=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gs=()=>{var E;if(!K)return;sl();let c=(E=r.voiceRecognition)!=null?E:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,y=c.recordingBorderColor;if(_a(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let D=K.querySelector("svg");D&&D.setAttribute("stroke",b)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},Yg=()=>{var q,B,xe,me,ne,Ee,_e,Te;if(!K)return;sl();let c=(q=r.voiceRecognition)!=null?q:{},g=_.getVoiceInterruptionMode(),b=(B=c.processingIconName)!=null?B:"loader",y=(me=(xe=c.processingIconColor)!=null?xe:Ue==null?void 0:Ue.color)!=null?me:"",E=(Ee=(ne=c.processingBackgroundColor)!=null?ne:Ue==null?void 0:Ue.backgroundColor)!=null?Ee:"",D=(Te=(_e=c.processingBorderColor)!=null?_e:Ue==null?void 0:Ue.borderColor)!=null?Te:"";_a(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=E,K.style.borderColor=D;let F=y||"currentColor";K.style.color=F,al(b,F),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},Zg=()=>{var xe,me,ne,Ee,_e,Te,ot,Ke,dt,pt,Ie,Le;if(!K)return;sl();let c=(xe=r.voiceRecognition)!=null?xe:{},g=_.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(me=c.speakingIconName)!=null?me:b,E=(Te=c.speakingIconColor)!=null?Te:g==="barge-in"?(Ee=(ne=c.recordingIconColor)!=null?ne:Ue==null?void 0:Ue.color)!=null?Ee:"":(_e=Ue==null?void 0:Ue.color)!=null?_e:"",D=(dt=c.speakingBackgroundColor)!=null?dt:g==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(Ke=Ue==null?void 0:Ue.backgroundColor)!=null?Ke:"",F=(Le=c.speakingBorderColor)!=null?Le:g==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(Ie=Ue==null?void 0:Ue.borderColor)!=null?Ie:"";_a(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=D,K.style.borderColor=F;let q=E||"currentColor";K.style.color=q,al(y,q);let B=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",B),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},go=()=>{var c,g,b;K&&(_a(),Ue&&(K.style.backgroundColor=(c=Ue.backgroundColor)!=null?c:"",K.style.color=(g=Ue.color)!=null?g:"",K.style.borderColor=(b=Ue.borderColor)!=null?b:"",al(Ue.iconName,Ue.color||"currentColor"),Ue=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},ja=()=>{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(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Nn(),lr("user"),go()});return}_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),xt.manuallyDeactivated=!_.isVoiceActive(),Nn(),lr("user"),_.isVoiceActive()?Gs():go()});return}if(ct){let b=te.value.trim();xt.manuallyDeactivated=!0,Nn(),Ut("user"),b&&(te.value="",te.style.height="auto",_.sendMessage(b))}else xt.manuallyDeactivated=!1,Nn(),fn("user")};_n=ja,K&&(K.addEventListener("click",ja),bt.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),go()):Ut("system"),K&&K.removeEventListener("click",ja)}));let ef=s.on("assistant:complete",()=>{Ds&&(xt.active||xt.manuallyDeactivated||Ds==="assistant"&&!xt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!xt.active&&!xt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),lr("auto"),_.isVoiceActive()&&Gs()}):fn("auto"))},600))});bt.push(ef);let tf=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});bt.push(tf);let us=()=>{Nt(!H,"user")},nn=null,rn=null;if(T&&!$()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>ha(r,us).element,onToggle:us});g&&(rn=g)}rn||(nn=ha(r,us))}nn?e.appendChild(nn.element):rn&&e.appendChild(rn),mo(),ar.render(r.suggestionChips,_,te,void 0,r.suggestionChipsConfig),Js(),ds(_.isStreaming()),ft()==="follow"?Rr(!0):Us(),Pa(),M&&(!T||$()?setTimeout(()=>ps(),0):H&&setTimeout(()=>ps(),200));let Xs=()=>{var B,xe,me,ne,Ee,_e,Te,ot,Ke,dt,pt,Ie,Le,qe,Qe,Ct,P,Be,Oe,he,_t,Ot;if($()){yn(),mo();return}let c=gn(r),g=(xe=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?xe:!1,b=c||g||((ne=(me=r.launcher)==null?void 0:me.fullHeight)!=null?ne:!1),y=(Ee=e.ownerDocument.defaultView)!=null?Ee:window,E=(Te=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?Te:!0,D=(Ke=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?Ke:640,F=y.innerWidth<=D,q=E&&F&&T;try{if(q){br(),xo(e,r);return}if(k&&(k=!1,br(),xo(e,r)),!T&&!c){fe.style.height="",fe.style.width="";return}if(!g&&!c){let Xt=(pt=(dt=r==null?void 0:r.launcher)==null?void 0:dt.width)!=null?pt:r==null?void 0:r.launcherWidth,At=Xt!=null?Xt:er;fe.style.width=At,fe.style.maxWidth=At}if(kr(),!b){let Xt=y.innerHeight,At=64,Vt=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Qn=Math.max(200,Xt-At),sn=Math.min(640,Qn),Ye=Math.max(200,sn-Vt);fe.style.height=`${Ye}px`}}finally{if(yn(),mo(),H&&T){let At=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Ct=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?Ct:640),Vt=(Be=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Be:!1,Qn=(he=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?he:!0,sn=gn(r)&&Qn&&At,Ye=Vt||Qn&&At&&T||sn;if(Ye&&!tn){let Wt=e.getRootNode(),pn=Wt instanceof ShadowRoot?Wt.host:e.closest(".persona-host");pn&&!en&&(en=Al(pn,(Ot=(_t=r.launcher)==null?void 0:_t.zIndex)!=null?Ot:Mn)),tn=Sl(e.ownerDocument)}else Ye||(en==null||en(),en=null,tn==null||tn(),tn=null)}}};Xs();let pc=(gd=e.ownerDocument.defaultView)!=null?gd:window;if(pc.addEventListener("resize",Xs),bt.push(()=>pc.removeEventListener("resize",Xs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe(je),bt.push(()=>c.disconnect())}Xn=ue.scrollTop;let uc=Xr(ue),nf=()=>{let c=ue.getRootNode(),g=typeof c.getSelection=="function"?c.getSelection():null;return g!=null?g:ue.ownerDocument.getSelection()},il=()=>cm(nf(),ue),mc=()=>{let c=ue.scrollTop,g=Xr(ue),b=g<uc;if(uc=g,ft()!=="follow"){Xn=c,On();return}let{action:y,nextLastScrollTop:E}=yi({following:Gn.isFollowing(),currentScrollTop:c,lastScrollTop:Xn,nearBottom:Xo(ue,as),userScrollThreshold:ka,isAutoScrolling:vr||Io||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=E,y==="resume"){il()||Wr();return}y==="pause"&&cs()};if(ue.addEventListener("scroll",mc,{passive:!0}),bt.push(()=>ue.removeEventListener("scroll",mc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ha()});c.observe(rt),c.observe(ue),bt.push(()=>c.disconnect())}let gc=()=>{ft()==="follow"&&Gn.isFollowing()&&il()&&cs()},fc=ue.ownerDocument;fc.addEventListener("selectionchange",gc),bt.push(()=>{fc.removeEventListener("selectionchange",gc)});let hc=c=>{if(ft()!=="follow")return;let g=xi({following:Gn.isFollowing(),deltaY:c.deltaY,nearBottom:Xo(ue,as),resumeWhenNearBottom:!0});g==="pause"?cs():g==="resume"&&!il()&&Wr()};ue.addEventListener("wheel",hc,{passive:!0}),bt.push(()=>ue.removeEventListener("wheel",hc)),et.addEventListener("click",()=>{Ro(),ue.scrollTop=ue.scrollHeight,Xn=ue.scrollTop,Wr(),Rr(!0),On()}),bt.push(()=>et.remove()),bt.push(()=>{Os(),Ro()});let bc=()=>{R&&(ir&&(R.removeEventListener("click",ir),ir=null),O()?(R.style.display="",ir=()=>{Nt(!1,"user")},R.addEventListener("click",ir)):R.style.display="none")};bc(),(()=>{let{clearChatButton:c}=De;c&&c.addEventListener("click",()=>{_.clearMessages(),_r.clear(),Wr(),Eo(De.composerOverlay);try{localStorage.removeItem(Hs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hs}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Hs)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(),le==null||le.clear(),ge==null||ge.reset(),V==null||V.update()})})(),Bt&&Bt.addEventListener("submit",j),te==null||te.addEventListener("keydown",tt),te==null||te.addEventListener("input",lt),te==null||te.addEventListener("paste",jt);let yc=(fd=e.ownerDocument)!=null?fd:document;yc.addEventListener("keydown",Ht,!0);let xc="persona-attachment-drop-active",Qs=0,ll=()=>{Qs=0,z.classList.remove(xc)},ms=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&St!==null},vc=c=>{!Gi(c.dataTransfer)||!ms()||(Qs++,Qs===1&&z.classList.add(xc))},wc=c=>{!Gi(c.dataTransfer)||!ms()||(Qs--,Qs<=0&&ll())},Cc=c=>{!Gi(c.dataTransfer)||!ms()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Ac=c=>{var b;if(!Gi(c.dataTransfer)||!ms())return;c.preventDefault(),c.stopPropagation(),ll();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&St.handleFiles(g)},fo=!0;z.addEventListener("dragenter",vc,fo),z.addEventListener("dragleave",wc,fo),e.addEventListener("dragover",Cc,fo),e.addEventListener("drop",Ac,fo);let Ua=e.ownerDocument,Sc=c=>{ms()&&c.preventDefault()},Tc=c=>{ms()&&c.preventDefault()};Ua.addEventListener("dragover",Sc),Ua.addEventListener("drop",Tc),bt.push(()=>{Bt&&Bt.removeEventListener("submit",j),te==null||te.removeEventListener("keydown",tt),te==null||te.removeEventListener("input",lt),te==null||te.removeEventListener("paste",jt),yc.removeEventListener("keydown",Ht,!0)}),bt.push(()=>{z.removeEventListener("dragenter",vc,fo),z.removeEventListener("dragleave",wc,fo),e.removeEventListener("dragover",Cc,fo),e.removeEventListener("drop",Ac,fo),Ua.removeEventListener("dragover",Sc),Ua.removeEventListener("drop",Tc),ll()}),bt.push(()=>{_.cancel()}),nn?bt.push(()=>{nn==null||nn.destroy()}):rn&&bt.push(()=>{rn==null||rn.remove()});let dn={update(c){var Hr,mn,Wn,ur,Oo,Fo,qa,Ys,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,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,xu,vu;let g=r.toolCall,b=r.messageActions,y=(Hr=r.layout)==null?void 0:Hr.messages,E=r.colorScheme,D=r.loadingIndicator,F=r.iterationDisplay,q=(mn=r.features)==null?void 0:mn.showReasoning,B=(Wn=r.features)==null?void 0:Wn.showToolCalls,xe=(ur=r.features)==null?void 0:ur.toolCallDisplay,me=(Oo=r.features)==null?void 0:Oo.reasoningDisplay;r={...r,...c},br(),xo(e,r),$i(e,r),_i(e,r),Kn(),r.colorScheme!==E&&io();let ne=Aa.getForInstance(r.plugins);o.length=0,o.push(...ne),T=(qa=(Fo=r.launcher)==null?void 0:Fo.enabled)!=null?qa:!0,N=(Cd=(Ys=r.launcher)==null?void 0:Ys.autoExpand)!=null?Cd:!1,ze=(Sd=(Ad=r.features)==null?void 0:Ad.showReasoning)!=null?Sd:!0,Ae=(Ed=(Td=r.features)==null?void 0:Td.showToolCalls)!=null?Ed:!0,be=(kd=(Md=r.features)==null?void 0:Md.scrollToBottom)!=null?kd:{};let Ee=ft();ke=(Pd=(Ld=r.features)==null?void 0:Ld.scrollBehavior)!=null?Pd:{},Ee!==ft()&&(Ro(),Wr()),Er(),On();let _e=We;if(We=(Wd=(Id=r.features)==null?void 0:Id.showEventStreamToggle)!=null?Wd:!1,We&&!_e){if(le||(Q=new wa(de),le=new va(re,Q),ge=ge!=null?ge:new Ca,Q.open().then(()=>le==null?void 0:le.restore()).catch(()=>{}),_.setSSEEventCallback((X,Mt)=>{var qt;(qt=r.onSSEEvent)==null||qt.call(r,X,Mt),ge==null||ge.processEvent(X,Mt),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(Mt)})})),!wt&&$e){let X=(Hd=(Rd=r.features)==null?void 0:Rd.eventStream)==null?void 0:Hd.classNames,Mt="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:"");wt=h("button",Mt),wt.style.width="28px",wt.style.height="28px",wt.style.color=Hn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let qt=Ce("activity","18px","currentColor",1.5);qt&&wt.appendChild(qt);let gt=De.clearChatButtonWrapper,Rt=De.closeButtonWrapper,hn=gt||Rt;hn&&hn.parentNode===$e?$e.insertBefore(wt,hn):$e.appendChild(wt),wt.addEventListener("click",()=>{se?hr():Nr()})}}else!We&&_e&&(hr(),wt&&(wt.remove(),wt=null),le==null||le.clear(),Q==null||Q.destroy(),le=null,Q=null,ge==null||ge.reset(),ge=null);if(((Bd=r.launcher)==null?void 0:Bd.enabled)===!1&&nn&&(nn.destroy(),nn=null),((Dd=r.launcher)==null?void 0:Dd.enabled)===!1&&rn&&(rn.remove(),rn=null),((Nd=r.launcher)==null?void 0:Nd.enabled)!==!1&&!nn&&!rn){let X=o.find(Mt=>Mt.renderLauncher);if(X!=null&&X.renderLauncher){let Mt=X.renderLauncher({config:r,defaultRenderer:()=>ha(r,us).element,onToggle:us});Mt&&(rn=Mt,e.appendChild(rn))}rn||(nn=ha(r,us),e.appendChild(nn.element))}nn&&nn.update(r),Ne&&((Od=r.launcher)==null?void 0:Od.title)!==void 0&&(Ne.textContent=r.launcher.title),Ge&&((Fd=r.launcher)==null?void 0:Fd.subtitle)!==void 0&&(Ge.textContent=r.launcher.subtitle);let Te=($d=r.layout)==null?void 0:$d.header;if((Te==null?void 0:Te.layout)!==S&&$e){let X=Te?Ss(r,Te,{showClose:O(),onClose:()=>Nt(!1,"user")}):Qr({config:r,showClose:O(),onClose:()=>Nt(!1,"user")});$e.replaceWith(X.header),$e=X.header,pe=X.iconHolder,Ne=X.headerTitle,Ge=X.headerSubtitle,R=X.closeButton,S=Te==null?void 0:Te.layout}else if(Te&&(pe&&(pe.style.display=Te.showIcon===!1?"none":""),Ne&&(Ne.style.display=Te.showTitle===!1?"none":""),Ge&&(Ge.style.display=Te.showSubtitle===!1?"none":""),R&&(R.style.display=Te.showCloseButton===!1?"none":""),De.clearChatButtonWrapper)){let X=Te.showClearChat;if(X!==void 0){De.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:Mt}=De;Mt&&!Mt.classList.contains("persona-absolute")&&(X?Mt.classList.remove("persona-ml-auto"):Mt.classList.add("persona-ml-auto"))}}let Ke=((_d=r.layout)==null?void 0:_d.showHeader)!==!1;$e&&($e.style.display=Ke?"":"none");let dt=((jd=r.layout)==null?void 0:jd.showFooter)!==!1;je&&(je.style.display=dt?"":"none"),yn(),On(),T!==W?T?Nt(N,"auto"):(H=!0,mo()):N!==I&&Nt(N,"auto"),I=N,W=T,Xs(),bc();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(g),qe=JSON.stringify(r.messageActions)!==JSON.stringify(b),Qe=JSON.stringify((Ud=r.layout)==null?void 0:Ud.messages)!==JSON.stringify(y),Ct=((qd=r.loadingIndicator)==null?void 0:qd.render)!==(D==null?void 0:D.render)||((zd=r.loadingIndicator)==null?void 0:zd.renderIdle)!==(D==null?void 0:D.renderIdle)||((Vd=r.loadingIndicator)==null?void 0:Vd.showBubble)!==(D==null?void 0:D.showBubble),P=r.iterationDisplay!==F,Be=((Jd=(Kd=r.features)==null?void 0:Kd.showReasoning)!=null?Jd:!0)!==(q!=null?q:!0)||((Xd=(Gd=r.features)==null?void 0:Gd.showToolCalls)!=null?Xd:!0)!==(B!=null?B:!0)||JSON.stringify((Qd=r.features)==null?void 0:Qd.toolCallDisplay)!==JSON.stringify(xe)||JSON.stringify((Yd=r.features)==null?void 0:Yd.reasoningDisplay)!==JSON.stringify(me);(Le||qe||Qe||Ct||P||Be)&&_&&(Bs++,Ho(rt,_.getMessages(),Me));let he=(Zd=r.launcher)!=null?Zd:{},_t=(ep=he.headerIconHidden)!=null?ep:!1,Ot=(np=(tp=r.layout)==null?void 0:tp.header)==null?void 0:np.showIcon,Xt=_t||Ot===!1,At=he.headerIconName,Vt=(rp=he.headerIconSize)!=null?rp:"48px";if(pe){let X=z.querySelector(".persona-border-b-persona-divider"),Mt=X==null?void 0:X.querySelector(".persona-flex-col");if(Xt)pe.style.display="none",X&&Mt&&!X.contains(Mt)&&X.insertBefore(Mt,X.firstChild);else{if(pe.style.display="",pe.style.height=Vt,pe.style.width=Vt,X&&Mt&&(X.contains(pe)?pe.nextSibling!==Mt&&(pe.remove(),X.insertBefore(pe,Mt)):X.insertBefore(pe,Mt)),At){let gt=parseFloat(Vt)||24,Rt=Ce(At,gt*.6,"#ffffff",2);Rt?pe.replaceChildren(Rt):pe.textContent=(op=he.agentIconText)!=null?op:"\u{1F4AC}"}else if(he.iconUrl){let gt=pe.querySelector("img");if(gt)gt.src=he.iconUrl,gt.style.height=Vt,gt.style.width=Vt;else{let Rt=document.createElement("img");Rt.src=he.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=Vt,Rt.style.width=Vt,pe.replaceChildren(Rt)}}else{let gt=pe.querySelector("svg"),Rt=pe.querySelector("img");(gt||Rt)&&pe.replaceChildren(),pe.textContent=(sp=he.agentIconText)!=null?sp:"\u{1F4AC}"}let qt=pe.querySelector("img");qt&&(qt.style.height=Vt,qt.style.width=Vt)}}let Qn=(ip=(ap=r.layout)==null?void 0:ap.header)==null?void 0:ip.showTitle,sn=(cp=(lp=r.layout)==null?void 0:lp.header)==null?void 0:cp.showSubtitle;if(Ne&&(Ne.style.display=Qn===!1?"none":""),Ge&&(Ge.style.display=sn===!1?"none":""),R){((pp=(dp=r.layout)==null?void 0:dp.header)==null?void 0:pp.showCloseButton)===!1?R.style.display="none":R.style.display="";let Mt=(up=he.closeButtonSize)!=null?up:"32px",qt=(mp=he.closeButtonPlacement)!=null?mp:"inline";R.style.height=Mt,R.style.width=Mt;let{closeButtonWrapper:gt}=De,Rt=qt==="top-right",hn=gt==null?void 0:gt.classList.contains("persona-absolute");if(gt&&Rt!==hn)if(gt.remove(),Rt)gt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",z.style.position="relative",z.appendChild(gt);else{let ht=(fp=(gp=he.clearChat)==null?void 0:gp.placement)!=null?fp:"inline",bn=(bp=(hp=he.clearChat)==null?void 0:hp.enabled)!=null?bp:!0;gt.className=bn&&ht==="inline"?"":"persona-ml-auto";let $n=z.querySelector(".persona-border-b-persona-divider");$n&&$n.appendChild(gt)}if(R.style.color=he.closeButtonColor||Hn.actionIconColor,he.closeButtonBackgroundColor?(R.style.backgroundColor=he.closeButtonBackgroundColor,R.classList.remove("hover:persona-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let ht=he.closeButtonBorderWidth||"0px",bn=he.closeButtonBorderColor||"transparent";R.style.border=`${ht} solid ${bn}`,R.classList.remove("persona-border-none")}else R.style.border="",R.classList.add("persona-border-none");he.closeButtonBorderRadius?(R.style.borderRadius=he.closeButtonBorderRadius,R.classList.remove("persona-rounded-full")):(R.style.borderRadius="",R.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(R.style.paddingLeft=he.closeButtonPaddingX,R.style.paddingRight=he.closeButtonPaddingX):(R.style.paddingLeft="",R.style.paddingRight=""),he.closeButtonPaddingY?(R.style.paddingTop=he.closeButtonPaddingY,R.style.paddingBottom=he.closeButtonPaddingY):(R.style.paddingTop="",R.style.paddingBottom="");let Tn=(yp=he.closeButtonIconName)!=null?yp:"x",Cr=(xp=he.closeButtonIconText)!=null?xp:"\xD7";R.innerHTML="";let Rn=Ce(Tn,"28px","currentColor",1);Rn?R.appendChild(Rn):R.textContent=Cr;let on=(vp=he.closeButtonTooltipText)!=null?vp:"Close chat",Zn=(wp=he.closeButtonShowTooltip)!=null?wp:!0;if(R.setAttribute("aria-label",on),gt&&(gt._cleanupTooltip&&(gt._cleanupTooltip(),delete gt._cleanupTooltip),Zn&&on)){let ht=null,bn=()=>{if(ht||!R)return;let $o=R.ownerDocument,Zs=$o.body;if(!Zs)return;ht=Br($o,"div","persona-clear-chat-tooltip"),ht.textContent=on;let ea=Br($o,"div");ea.className="persona-clear-chat-tooltip-arrow",ht.appendChild(ea);let _o=R.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(vo),ht.style.left=`${_o.left+_o.width/2}px`,ht.style.top=`${_o.top-8}px`,ht.style.transform="translate(-50%, -100%)",Zs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};gt.addEventListener("mouseenter",bn),gt.addEventListener("mouseleave",$n),R.addEventListener("focus",bn),R.addEventListener("blur",$n),gt._cleanupTooltip=()=>{$n(),gt&&(gt.removeEventListener("mouseenter",bn),gt.removeEventListener("mouseleave",$n)),R&&(R.removeEventListener("focus",bn),R.removeEventListener("blur",$n))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Wt}=De;if(Ye){let X=(Cp=he.clearChat)!=null?Cp:{},Mt=(Ap=X.enabled)!=null?Ap:!0,qt=(Tp=(Sp=r.layout)==null?void 0:Sp.header)==null?void 0:Tp.showClearChat,gt=qt!==void 0?qt:Mt,Rt=(Ep=X.placement)!=null?Ep:"inline";if(Wt){Wt.style.display=gt?"":"none";let{closeButtonWrapper:hn}=De;!$()&&hn&&!hn.classList.contains("persona-absolute")&&(gt?hn.classList.remove("persona-ml-auto"):hn.classList.add("persona-ml-auto"));let Tn=Rt==="top-right",Cr=Wt.classList.contains("persona-absolute");if(!$()&&Tn!==Cr&&gt){if(Wt.remove(),Tn)Wt.className="persona-absolute persona-top-4 persona-z-50",Wt.style.right="48px",z.style.position="relative",z.appendChild(Wt);else{Wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wt.style.right="";let on=z.querySelector(".persona-border-b-persona-divider"),Zn=De.closeButtonWrapper;on&&Zn&&Zn.parentElement===on?on.insertBefore(Wt,Zn):on&&on.appendChild(Wt)}let Rn=De.closeButtonWrapper;Rn&&!Rn.classList.contains("persona-absolute")&&(Tn?Rn.classList.add("persona-ml-auto"):Rn.classList.remove("persona-ml-auto"))}}if(gt){if(!$()){let ht=(Mp=X.size)!=null?Mp:"32px";Ye.style.height=ht,Ye.style.width=ht}let hn=(kp=X.iconName)!=null?kp:"refresh-cw",Tn=(Lp=X.iconColor)!=null?Lp:"";Ye.style.color=Tn||Hn.actionIconColor,Ye.innerHTML="";let Cr=$()?"14px":"20px",Rn=Ce(hn,Cr,"currentColor",2);if(Rn&&Ye.appendChild(Rn),X.backgroundColor?(Ye.style.backgroundColor=X.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let ht=X.borderWidth||"0px",bn=X.borderColor||"transparent";Ye.style.border=`${ht} solid ${bn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");X.borderRadius?(Ye.style.borderRadius=X.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),X.paddingX?(Ye.style.paddingLeft=X.paddingX,Ye.style.paddingRight=X.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),X.paddingY?(Ye.style.paddingTop=X.paddingY,Ye.style.paddingBottom=X.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let on=(Pp=X.tooltipText)!=null?Pp:"Clear chat",Zn=(Ip=X.showTooltip)!=null?Ip:!0;if(Ye.setAttribute("aria-label",on),Wt&&(Wt._cleanupTooltip&&(Wt._cleanupTooltip(),delete Wt._cleanupTooltip),Zn&&on)){let ht=null,bn=()=>{if(ht||!Ye)return;let $o=Ye.ownerDocument,Zs=$o.body;if(!Zs)return;ht=Br($o,"div","persona-clear-chat-tooltip"),ht.textContent=on;let ea=Br($o,"div");ea.className="persona-clear-chat-tooltip-arrow",ht.appendChild(ea);let _o=Ye.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(vo),ht.style.left=`${_o.left+_o.width/2}px`,ht.style.top=`${_o.top-8}px`,ht.style.transform="translate(-50%, -100%)",Zs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Wt.addEventListener("mouseenter",bn),Wt.addEventListener("mouseleave",$n),Ye.addEventListener("focus",bn),Ye.addEventListener("blur",$n),Wt._cleanupTooltip=()=>{$n(),Wt&&(Wt.removeEventListener("mouseenter",bn),Wt.removeEventListener("mouseleave",$n)),Ye&&(Ye.removeEventListener("focus",bn),Ye.removeEventListener("blur",$n))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Sa],pr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ts.message,ts.messageAndClick];w=Ta({parsers:pn,handlers:pr,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Me=dg(r,w,ce),_.updateConfig(r),Ho(rt,_.getMessages(),Me),ar.render(r.suggestionChips,_,te,void 0,r.suggestionChipsConfig),Js(),ds(_.isStreaming());let Yn=((Wp=r.voiceRecognition)==null?void 0:Wp.enabled)===!0,Bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Do=((Hp=(Rp=r.voiceRecognition)==null?void 0:Rp.provider)==null?void 0:Hp.type)==="runtype";if(Yn&&(Bo||Do))if(!K||!vt){let X=wr(r.voiceRecognition,r.sendButton);X&&(K=X.micButton,vt=X.micButtonWrapper,Jt.insertBefore(vt,Bn),K.addEventListener("click",ja),K.disabled=_.isStreaming())}else{let X=(Bp=r.voiceRecognition)!=null?Bp:{},Mt=(Dp=r.sendButton)!=null?Dp:{},qt=(Np=X.iconName)!=null?Np:"mic",gt=(Op=Mt.size)!=null?Op:"40px",Rt=(Fp=X.iconSize)!=null?Fp:gt,hn=parseFloat(Rt)||24;K.style.width=Rt,K.style.height=Rt,K.style.minWidth=Rt,K.style.minHeight=Rt;let Tn=(_p=($p=X.iconColor)!=null?$p:Mt.textColor)!=null?_p:"currentColor";K.innerHTML="";let Cr=Ce(qt,hn,Tn,2);Cr?K.appendChild(Cr):K.textContent="\u{1F3A4}";let Rn=(jp=X.backgroundColor)!=null?jp:Mt.backgroundColor;Rn?K.style.backgroundColor=Rn:K.style.backgroundColor="",Tn?K.style.color=Tn:K.style.color="var(--persona-text, #111827)",X.borderWidth?(K.style.borderWidth=X.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),X.borderColor?K.style.borderColor=X.borderColor:K.style.borderColor="",X.paddingX?(K.style.paddingLeft=X.paddingX,K.style.paddingRight=X.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),X.paddingY?(K.style.paddingTop=X.paddingY,K.style.paddingBottom=X.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let on=vt==null?void 0:vt.querySelector(".persona-send-button-tooltip"),Zn=(Up=X.tooltipText)!=null?Up:"Start voice recognition";if(((qp=X.showTooltip)!=null?qp:!1)&&Zn)if(on)on.textContent=Zn,on.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=Zn,vt==null||vt.insertBefore(bn,K)}else on&&(on.style.display="none");vt.style.display="",K.disabled=_.isStreaming()}else K&&vt&&(vt.style.display="none",((Vp=(zp=r.voiceRecognition)==null?void 0:zp.provider)==null?void 0:Vp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():ct&&Ut());if(((Kp=r.attachments)==null?void 0:Kp.enabled)===!0)if(!we||!it){let X=(Jp=r.attachments)!=null?Jp:{},qt=(Xp=((Gp=r.sendButton)!=null?Gp:{}).size)!=null?Xp:"40px";nt||(nt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),nt.style.display="none",Bt.insertBefore(nt,te)),ie||(ie=document.createElement("input"),ie.type="file",ie.accept=((Qp=X.allowedTypes)!=null?Qp:Gr).join(","),ie.multiple=((Yp=X.maxFiles)!=null?Yp:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Bt.insertBefore(ie,te)),we=h("div","persona-send-button-wrapper"),it=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",(Zp=X.buttonTooltipText)!=null?Zp:"Attach file");let gt=(eu=X.buttonIconName)!=null?eu:"paperclip",Rt=qt,hn=parseFloat(Rt)||40,Tn=Math.round(hn*.6);it.style.width=Rt,it.style.height=Rt,it.style.minWidth=Rt,it.style.minHeight=Rt,it.style.fontSize="18px",it.style.lineHeight="1",it.style.backgroundColor="transparent",it.style.color="var(--persona-primary, #111827)",it.style.border="none",it.style.borderRadius="6px",it.style.transition="background-color 0.15s ease",it.addEventListener("mouseenter",()=>{it.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),it.addEventListener("mouseleave",()=>{it.style.backgroundColor="transparent"});let Cr=Ce(gt,Tn,"currentColor",1.5);Cr?it.appendChild(Cr):it.textContent="\u{1F4CE}",it.addEventListener("click",Zn=>{Zn.preventDefault(),ie==null||ie.click()}),we.appendChild(it);let Rn=(tu=X.buttonTooltipText)!=null?tu:"Attach file",on=h("div","persona-send-button-tooltip");on.textContent=Rn,we.appendChild(on),It.append(we),!St&&ie&&nt&&(St=Go.fromConfig(X),St.setPreviewsContainer(nt),ie.addEventListener("change",async()=>{St&&(ie!=null&&ie.files)&&(await St.handleFileSelect(ie.files),ie.value="")})),z.querySelector(".persona-attachment-drop-overlay")||z.appendChild(pg(X.dropOverlay))}else{we.style.display="";let X=(nu=r.attachments)!=null?nu:{};ie&&(ie.accept=((ru=X.allowedTypes)!=null?ru:Gr).join(","),ie.multiple=((ou=X.maxFiles)!=null?ou:4)>1),St&&St.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else we&&(we.style.display="none"),St&&St.clearAttachments(),(su=z.querySelector(".persona-attachment-drop-overlay"))==null||su.remove();let Qt=(au=r.sendButton)!=null?au:{},No=(iu=Qt.useIcon)!=null?iu:!1,ho=(lu=Qt.iconText)!=null?lu:"\u2191",bo=Qt.iconName,Vr=(cu=Qt.tooltipText)!=null?cu:"Send message",at=(du=Qt.showTooltip)!=null?du:!1,vn=(pu=Qt.size)!=null?pu:"40px",In=Qt.backgroundColor,an=Qt.textColor;if(No){if(Ve.style.width=vn,Ve.style.height=vn,Ve.style.minWidth=vn,Ve.style.minHeight=vn,Ve.style.fontSize="18px",Ve.style.lineHeight="1",Ve.innerHTML="",an?Ve.style.color=an:Ve.style.color="var(--persona-button-primary-fg, #ffffff)",bo){let X=parseFloat(vn)||24,Mt=(an==null?void 0:an.trim())||"currentColor",qt=Ce(bo,X,Mt,2);qt?Ve.appendChild(qt):Ve.textContent=ho}else Ve.textContent=ho;Ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",In?(Ve.style.backgroundColor=In,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=(mu=(uu=r.copy)==null?void 0:uu.sendButtonLabel)!=null?mu:"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.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",In?(Ve.style.backgroundColor=In,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),an?Ve.style.color=an:Ve.classList.add("persona-text-white");Qt.borderWidth?(Ve.style.borderWidth=Qt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),Qt.borderColor?Ve.style.borderColor=Qt.borderColor:Ve.style.borderColor="",Qt.paddingX?(Ve.style.paddingLeft=Qt.paddingX,Ve.style.paddingRight=Qt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Qt.paddingY?(Ve.style.paddingTop=Qt.paddingY,Ve.style.paddingBottom=Qt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let ut=Bn==null?void 0:Bn.querySelector(".persona-send-button-tooltip");if(at&&Vr)if(ut)ut.textContent=Vr,ut.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Vr,Bn==null||Bn.insertBefore(X,Ve)}else ut&&(ut.style.display="none");let yt=(yu=(gu=r.layout)==null?void 0:gu.contentMaxWidth)!=null?yu:$()?(bu=(hu=(fu=r.launcher)==null?void 0:fu.composerBar)==null?void 0:hu.contentMaxWidth)!=null?bu:"720px":void 0;yt?(rt.style.maxWidth=yt,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%",Bt&&(Bt.style.maxWidth=yt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),kt&&(kt.style.maxWidth=yt,kt.style.marginLeft="auto",kt.style.marginRight="auto")):(rt.style.maxWidth="",rt.style.marginLeft="",rt.style.marginRight="",rt.style.width="",Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""),kt&&(kt.style.maxWidth="",kt.style.marginLeft="",kt.style.marginRight=""));let mt=(xu=r.statusIndicator)!=null?xu:{},Fn=(vu=mt.visible)!=null?vu:!0;if(ln.style.display=Fn?"":"none",_){let X=_.getStatus();Ze(ln,(qt=>{var gt,Rt,hn,Tn;return qt==="idle"?(gt=mt.idleText)!=null?gt:En.idle:qt==="connecting"?(Rt=mt.connectingText)!=null?Rt:En.connecting:qt==="connected"?(hn=mt.connectedText)!=null?hn:En.connected:qt==="error"?(Tn=mt.errorText)!=null?Tn:En.error:En[qt]})(X),mt,X)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let un=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(un)},open(){O()&&Nt(!0,"api")},close(){O()&&Nt(!1,"api")},toggle(){O()&&Nt(!H,"api")},clearChat(){Ln=!1,_.clearMessages(),_r.clear(),Wr();try{localStorage.removeItem(Hs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Hs)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(),le==null||le.clear(),ge==null||ge.reset(),V==null||V.update()},setMessage(c){return!te||_.isStreaming()?!1:(!H&&O()&&Nt(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let g=(c==null?void 0:c.trim())||te.value.trim();return g?(!H&&O()&&Nt(!0,"system"),te.value="",te.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()||(!H&&O()&&Nt(!0,"system"),xt.manuallyDeactivated=!1,Nn(),_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),lr("user"),_.isVoiceActive()&&Gs()})),!0):ct?!0:Sn()?(!H&&O()&&Nt(!0,"system"),xt.manuallyDeactivated=!1,Nn(),fn("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(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Nn(),lr("user"),go()}),!0):!1:ct?(xt.manuallyDeactivated=!0,Nn(),Ut("user"),!0):!1},injectMessage(c){return!H&&O()&&Nt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!H&&O()&&Nt(!0,"system");let g=_.injectAssistantMessage(c);return U&&(U=!1,J&&(clearTimeout(J),J=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(c){return!H&&O()&&Nt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!H&&O()&&Nt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!H&&O()&&Nt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!H&&O()&&Nt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!H&&O()&&Nt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,g){return _.connectStream(c,g)},__pushEventStreamEvent(c){le&&(ge==null||ge.processEvent(c.type,c.payload),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!We||!le||Nr()},hideEventStream(){se&&hr()},isEventStreamVisible(){return se},showArtifacts(){fr(r)&&(Ln=!1,Kn(),Tt==null||Tt.setMobileOpen(!0))},hideArtifacts(){fr(r)&&(Ln=!0,Kn())},upsertArtifact(c){return fr(r)?(Ln=!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&&!H&&!$()||!te?!1:(te.focus(),!0)},async resolveApproval(c,g,b){let E=_.getMessages().find(D=>{var F;return D.variant==="approval"&&((F=D.approval)==null?void 0:F.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 s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return O()&&H},isVoiceActive(){return xt.active},getState(){return{open:O()&&H,launcherEnabled:T,voiceActive:xt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!H&&O()&&Nt(!0,"system");let g=rt.querySelector(".persona-feedback-container");g&&g.remove();let b=Ki({onSubmit:async(y,E)=>{var D;_.isClientTokenMode()&&await _.submitCSATFeedback(y,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!H&&O()&&Nt(!0,"system");let g=rt.querySelector(".persona-feedback-container");g&&g.remove();let b=Ji({onSubmit:async(y,E)=>{var D;_.isClientTokenMode()&&await _.submitNPSFeedback(y,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.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(){cr!=null&&(clearInterval(cr),cr=null),bt.forEach(c=>c()),ve.remove(),Je==null||Je.remove(),nn==null||nn.destroy(),rn==null||rn.remove(),ir&&R.removeEventListener("click",ir)}};if((((hd=n==null?void 0:n.debugTools)!=null?hd:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:b=>b?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,bt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",g),bt.push(()=>{window.removeEventListener("persona:focusInput",g)}),We){let q=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&dn.showEventStream()},B=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),bt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let b=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.showArtifacts()},y=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.hideArtifacts()},E=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||B!=null&&B.artifact&&dn.upsertArtifact(B.artifact)},D=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||typeof(B==null?void 0:B.id)=="string"&&dn.selectArtifact(B.id)},F=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",F),bt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",F)})}let dr=kb(r.persistState);if(dr&&O()){let c=Lb(dr.storage),g=`${dr.keyPrefix}widget-open`,b=`${dr.keyPrefix}widget-voice`,y=`${dr.keyPrefix}widget-voice-mode`;if(c){let E=((bd=dr.persist)==null?void 0:bd.openState)&&c.getItem(g)==="true",D=((yd=dr.persist)==null?void 0:yd.voiceState)&&c.getItem(b)==="true",F=((xd=dr.persist)==null?void 0:xd.voiceState)&&c.getItem(y)==="true";if(E&&setTimeout(()=>{dn.open(),setTimeout(()=>{var q;if(D||F)dn.startVoiceRecognition();else if((q=dr.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(vd=dr.persist)!=null&&vd.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(wd=dr.persist)!=null&&wd.voiceState&&(s.on("voice:state",q=>{c.setItem(b,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),dr.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},B=()=>q();window.addEventListener("persona:clear-chat",B),bt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&O()&&setTimeout(()=>{dn.open()},0),zr(),dn};var Pb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},ug=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},Ql=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=""},mg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Ql(e)},Jl=e=>{e.style.transition=""},Gl=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=""},Xl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Qi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ib=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Wb=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},gg=(e,t,n,r,o,s,a)=>{var v,x,w,T,N,M;let i=mr(s),d=i.reveal==="push";Ib(e,t,n,r,d),Wb(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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(T=(w=s==null?void 0:s.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"),Gl(t),Jl(r),mg(r),Xl(n),Qi(o,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((M=(N=s==null?void 0:s.launcher)==null?void 0:N.zIndex)!=null?M:Mn),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"),mg(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gl(t),Jl(r),Xl(n),Qi(o,r);let I=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=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",Jl(r),Ql(r),Qi(o,r);let I=Pb(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",k=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=`${W+I}px`,t.style.transition=S,t.style.transform=k,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="",Gl(t),Ql(r),Xl(n),Qi(o,r);let I=i.reveal==="emerge";I?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",k=!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=I||k?"hidden":"visible",r.style.transition=S,I&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Rb=(e,t)=>{let n=e.ownerDocument.createElement("div");return ug(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){ug(n,r)},destroy(){n.remove()}}},Hb=(e,t)=>{var N,M,I,W;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(M=(N=t==null?void 0:t.launcher)==null?void 0:N.enabled)==null||M?(W=(I=t==null?void 0:t.launcher)==null?void 0:I.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(()=>{gg(a,i,d,l,p,t,u)}),f.observe(a))},x=()=>{gg(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 k=S.launcherEnabled?S.open:!0;u!==k&&(u=k,x())},updateConfig(S){var k,$;t=S,(($=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)!=null?$:!0)===!1&&(u=!0),x()},destroy(){w==null||w.removeEventListener("resize",T),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Ea=(e,t)=>gn(t)?Hb(e,t):Rb(e,t);var Yl={},fg=!1,Bb=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},Db=()=>{try{if(typeof Yl!="undefined"&&Yl.url)return new URL("../widget.css",Yl.url).href}catch{}return null},hg=(e,t)=>{let n=Db(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Zl=e=>{let t=Bb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Ea(t,o),a,i=[],d=(w,T)=>{var W,S;let M=!((S=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?S:!0)||gn(T),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),M&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let k=w.attachShadow({mode:"open"});k.appendChild(I),hg(k,r)}else w.appendChild(I),hg(w,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(s.host,o);a=Xi(w,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(fg||(fg=!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(),s.destroy(),s=Ea(t,w),o=w,u()},v={update(w){var S,k,$,O,H,U;let T={...o,...w,launcher:{...(S=o==null?void 0:o.launcher)!=null?S:{},...(k=w==null?void 0:w.launcher)!=null?k:{},dock:{...(O=($=o==null?void 0:o.launcher)==null?void 0:$.dock)!=null?O:{},...(U=(H=w==null?void 0:w.launcher)==null?void 0:H.dock)!=null?U:{}}}},N=gn(o),M=gn(T),I=Co(o),W=Co(T);if(N!==M||I!==W){m(T);return}o=T,s.updateConfig(o),a.update(w),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,T,N){if(T==="host")return s.host;if(T in w)return Reflect.get(w,T,N);let M=a[T];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var wg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Nb=new Set(["button","a","input","select","textarea","details","summary"]),Ob=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ec=/\b(product|card|item|listing|result)\b/i,nc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Fb=3e3,$b=100;function Cg(e){let t=typeof e.className=="string"?e.className:"";if(ec.test(t)||e.id&&ec.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ec.test(r.value))return!0}return!1}function Ag(e){var t;return nc.test(((t=e.textContent)!=null?t:"").trim())}function Sg(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function _b(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bg(e){let t=e.match(nc);return t?t[0]:null}function yg(e){var r,o,s;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&&((o=t.textContent)!=null&&o.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(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function jb(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Ub="commerce-card",qb="result-card";function xg(e){return!Cg(e)||!Ag(e)||!Sg(e)&&!_b(e)?0:5200}function vg(e){var r;return!Cg(e)||Ag(e)||!Sg(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 rc=[{id:Ub,scoreElement(e){return xg(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||nc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(xg(e)===0)return null;let{title:n,href:r}=yg(e),o=(p=(l=bg(((d=e.textContent)!=null?d:"").trim()))!=null?l:bg(t.text))!=null?p:"",s=jb(e);return[r&&n?`[${n}](${r})${o?` \u2014 ${o}`:""}`:n?`${n}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
108
+ `)}},{id:qb,scoreElement(e){return vg(e)},formatSummary(e,t){if(vg(e)===0)return null;let{title:n,href:r}=yg(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
+ `)}}];function zb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Vb(e){var p,u,f,m,v,x,w,T,N,M,I,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",o=(w=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?w:200,s=(N=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?N:!0,a=(M=t.root)!=null?M:e.root,i=(I=t.mode)!=null?I:"structured",d=(W=t.maxCandidates)!=null?W:Math.max(500,n*10),l=(S=e.rules)!=null?S:rc;return i==="simple"&&e.rules&&e.rules.length>0?(zb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function tc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Kb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Jb(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"||Nb.has(t)||n&&Ob.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Tg(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 Gb(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);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 oc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${tc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Kb){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${tc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>tc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function Xb(e){return e==="static"?$b:Fb}function Eg(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:oc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Jb(e),attributes:Gb(e)}}function Qb(e,t,n,r){let o=Xb(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function Yb(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 Zb(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(wg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Tg(l)){i=a.nextNode();continue}let u=Eg(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}=Qb(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:x}),s+=1}i=a.nextNode()}o.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 o){if(d.length>=e.maxElements)break;Yb(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 ey(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(wg.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Tg(d)){s=o.nextNode();continue}let p=Eg(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){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.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 Mg(e={}){var r;let t=Vb(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?ey(t,n):Zb(t,n):[]}var Yi=100;function kg(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"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 o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Yi)}" (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(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Yi)}" (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(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Yi)}" (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(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Yi)}"`);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 Lg={name:"@runtypelabs/persona",version:"3.31.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 ns=Lg.version;function Pg(){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 Ig(){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 Wg(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:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function Rg(){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 Hg(){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 Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Bg(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var ny={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"}}},Dg={components:{panel:{borderRadius:"0",shadow:"none"}}},sc={id:"shop",label:"Shopping Assistant",config:{theme:ny,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:er},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?"]}},ac={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Dg}},ic={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Dg}},lc={shop:sc,minimal:ac,fullscreen:ic};function Ng(e){return lc[e]}var Og=Zl;function to(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function ry(e){if(e)return{getHeaders:to(e.getHeaders),onFeedback:to(e.onFeedback),onCopy:to(e.onCopy),requestMiddleware:to(e.requestMiddleware),actionHandlers:to(e.actionHandlers),actionParsers:to(e.actionParsers),postprocessMessage:to(e.postprocessMessage),contextProviders:to(e.contextProviders),streamParser:to(e.streamParser)}}var Fg=`({ 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
+ }`,$g=`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
+ }`,_g=`(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
+ }`,jg=`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
+ }`,oy=`(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
+ }`,sy=`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 ay(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:ay(e.streamParser))!=null?n:"plain"}function el(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function tl(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(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 nl(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function rl(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="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} },`)):s==="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} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function cc(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 Ug(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),Ug(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function ko(e,t,n,r){n&&(e.push(`${r}${t}: {`),Ug(e,n,`${r} `),e.push(`${r}},`))}function Ma(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function qg(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:ry(n.hooks)}:void 0;return t==="esm"?iy(r,o):t==="script-installer"?dy(r,o):t==="script-advanced"?uy(r,o):t==="react-component"?ly(r,o):t==="react-advanced"?cy(r,o):py(r,o)}function iy(e,t){let n=t==null?void 0:t.hooks,r=Zi(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ma(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...el(e," ")),s.push(...tl(e," ",n)),s.push(...nl(e," ")),s.push(...rl(e," ")),s.push(...cc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
196
+ `)}function ly(e,t){let n=t==null?void 0:t.hooks,r=Zi(e),o=r!=="plain",s=["// 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: '${Ma(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...el(e," ")),s.push(...tl(e," ",n)),s.push(...nl(e," ")),s.push(...rl(e," ")),s.push(...cc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.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: '${Ma(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&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),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(...el(e," ")),r.push(...tl(e," ",n)),r.push(...nl(e," ")),r.push(...rl(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(${oy}),`)),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(` ${Fg}`),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(` ${Fg}`),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(` ${_g}`),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(` ${_g}`),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 zg(e){var o;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),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};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&&(s.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&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function dy(e,t){let n=zg(e),o=!!(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,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ns}/dist/install.global.js" data-config='${s}'></script>`}function py(e,t){let n=t==null?void 0:t.hooks,r=Zi(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ns}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ns}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ma(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...el(e," ")),s.push(...tl(e," ",n)),s.push(...nl(e," ")),s.push(...rl(e," ")),s.push(...cc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
199
+ `)}function uy(e,t){let n=t==null?void 0:t.hooks,r=zg(e),s=["<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@${ns}/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&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${sy});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${$g}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${$g}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${jg}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${jg}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.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: '${Ma(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>"),s.join(`
202
+ `)}var Vg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Kg=.1,Jg=.15,Gg=1.5,dc=24,Xg=40,my=`
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: ${dc}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 gy(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=my,document.head.appendChild(e)}function fy(e,t){let n=e.clientWidth-dc*2-Xg,r=e.clientHeight-dc*2-Xg;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function hy(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="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 Qg(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="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");gy();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,m=null,v=1,x=!1,w=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),N=h("div","persona-dc-toolbar-lead"),M=h("div","persona-dc-toolbar-trail"),I=Kt({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 k=h("span","persona-dc-title-text"),$=h("span","persona-dc-title-chevron"),O=Ce("chevron-down",12,"currentColor",2);O&&$.appendChild(O),S.append(k,$);let H=h("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let U=!1;function J(){H.innerHTML="";for(let Se=0;Se<n.length;Se++){let Ze=n[Se],ve=h("button","persona-dc-dropdown-item");ve.type="button",ve.setAttribute("role","option"),ve.setAttribute("aria-current",Se===p?"true":"false");let fe=h("span");if(fe.textContent=Ze.title,ve.appendChild(fe),Ze.description){let Je=h("span","persona-dc-dropdown-desc");Je.textContent=Ze.description,ve.appendChild(Je)}ve.addEventListener("click",()=>{Me(),He(Se)}),H.appendChild(ve)}}function ce(){U=!U,H.style.display=U?"":"none",S.setAttribute("aria-expanded",U?"true":"false"),U&&J()}function Me(){U&&(U=!1,H.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",Se=>{Se.stopPropagation(),ce()});let ze=()=>Me();document.addEventListener("click",ze),W.append(S,H);let Ae=Kt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>se(1)}),We=h("span","persona-dc-counter");N.append(I,W,Ae,We);let be=null;i&&(be=ya({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:Se=>{u=Se,re.dataset.device=u,m=null,Z()}}),M.appendChild(be.element));let ke=null;if(a){let Se=h("div","persona-dc-zoom-controls"),Ze=Kt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Je=m!=null?m:v;m=Math.max(Jg,Je-Kg),Z()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{m=1,Z()});let ve=Kt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Je=m!=null?m:v;m=Math.min(Gg,Je+Kg),Z()}}),fe=Kt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,Z()}});Se.append(Ze,ke,ve,fe),M.appendChild(Se)}if(d){let Se=h("div","persona-dc-separator");M.appendChild(Se);let Ze=ya({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ve=>{f=ve,re.dataset.colorScheme=f,ge()}});M.appendChild(Ze.element)}let Re=h("div","persona-dc-separator");M.appendChild(Re);let de=Kt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});M.appendChild(de),T.append(N,M);let Q=h("div","persona-dc-stage"),re=h("div","persona-dc-iframe-wrapper");re.dataset.device=u,re.dataset.colorScheme=f;let le=h("iframe","persona-dc-iframe");le.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),le.setAttribute("loading","lazy"),le.title=n[p].title,re.appendChild(le),Q.appendChild(re),w.append(T,Q),e.appendChild(w);function ge(){var Se;try{let Ze=(Se=le.contentDocument)==null?void 0:Se.body;if(!Ze)return;f==="dark"?Ze.classList.add("theme-dark"):Ze.classList.remove("theme-dark")}catch{}}le.addEventListener("load",()=>ge());function V(){let Se=n[p];k.textContent=Se.title,We.textContent=`${p+1} / ${n.length}`,le.title=Se.title}function se(Se){let Ze=((p+Se)%n.length+n.length)%n.length;He(Ze)}function He(Se){Se<0||Se>=n.length||(p=Se,le.src=n[p].url,V(),l==null||l(p,n[p]))}function Z(){var ve;if(x)return;let Se=(ve=Vg[u])!=null?ve:Vg.desktop;v=fy(Q,Se);let Ze=Math.max(Jg,Math.min(Gg,m!=null?m:v));hy(re,le,Se,Ze,u),ke&&(ke.textContent=`${Math.round(Ze*100)}%`)}let ee=new ResizeObserver(()=>Z());ee.observe(Q),V(),le.src=n[p].url,requestAnimationFrame(()=>Z());function ae(){x||(x=!0,ee.disconnect(),document.removeEventListener("click",ze),w.remove())}return{element:w,goTo:He,next:()=>se(1),prev:()=>se(-1),getIndex:()=>p,setDevice(Se){u=Se,re.dataset.device=Se,be==null||be.setSelected(Se),m=null,Z()},setColorScheme(Se){f=Se,re.dataset.colorScheme=Se},setZoom(Se){m=Se,Z()},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});
444
444
  //# sourceMappingURL=index.cjs.map