@runtypelabs/persona 3.34.1 → 3.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-CthJFfNx.d.cts → types-DgYsuwXL.d.cts} +15 -14
- package/dist/animations/{types-CthJFfNx.d.ts → types-DgYsuwXL.d.ts} +15 -14
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +11 -11
- package/dist/codegen.js +10 -10
- package/dist/index.cjs +46 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +514 -158
- package/dist/index.d.ts +514 -158
- package/dist/index.global.js +41 -89
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +46 -44
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +53 -0
- package/dist/plugin-kit.d.cts +4 -4
- package/dist/plugin-kit.d.ts +4 -4
- package/dist/runtype-tts.js +1 -0
- package/dist/smart-dom-reader.cjs +1 -1
- package/dist/smart-dom-reader.d.cts +352 -103
- package/dist/smart-dom-reader.d.ts +352 -103
- package/dist/smart-dom-reader.js +1 -1
- package/dist/theme-editor-preview.cjs +203 -0
- package/dist/theme-editor-preview.d.cts +5748 -0
- package/dist/theme-editor-preview.d.ts +5748 -0
- package/dist/theme-editor-preview.js +203 -0
- package/dist/theme-editor.cjs +14 -131
- package/dist/theme-editor.d.cts +362 -574
- package/dist/theme-editor.d.ts +362 -574
- package/dist/theme-editor.js +14 -131
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +1 -1
- package/dist/theme-reference.d.ts +1 -1
- package/dist/theme-reference.js +1 -1
- package/dist/voice-worklet-player.cjs +80 -0
- package/dist/voice-worklet-player.d.cts +215 -0
- package/dist/voice-worklet-player.d.ts +215 -0
- package/dist/voice-worklet-player.js +80 -0
- package/dist/widget.css +54 -36
- package/package.json +16 -2
- package/src/animations/glyph-cycle.ts +11 -14
- package/src/animations/wipe.ts +1 -1
- package/src/ask-user-question-tool.test.ts +1 -1
- package/src/ask-user-question-tool.ts +6 -8
- package/src/client.test.ts +56 -12
- package/src/client.ts +35 -31
- package/src/codegen.test.ts +1 -1
- package/src/codegen.ts +1 -1
- package/src/components/approval-bubble.test.ts +1 -1
- package/src/components/approval-bubble.ts +3 -3
- package/src/components/artifact-pane.ts +3 -3
- package/src/components/ask-user-question-bubble.test.ts +14 -14
- package/src/components/ask-user-question-bubble.ts +10 -10
- package/src/components/composer-builder.ts +17 -16
- package/src/components/composer-parts.test.ts +54 -0
- package/src/components/composer-parts.ts +95 -126
- package/src/components/demo-carousel.ts +1 -1
- package/src/components/event-stream-view.test.ts +7 -7
- package/src/components/event-stream-view.ts +5 -5
- package/src/components/header-builder.ts +33 -27
- package/src/components/header-layouts.ts +1 -1
- package/src/components/header-parts.test.ts +90 -0
- package/src/components/header-parts.ts +62 -93
- package/src/components/launcher.test.ts +11 -0
- package/src/components/launcher.ts +1 -1
- package/src/components/message-bubble.test.ts +74 -2
- package/src/components/message-bubble.ts +25 -11
- package/src/components/messages.ts +2 -2
- package/src/components/panel.test.ts +1 -1
- package/src/components/panel.ts +92 -97
- package/src/components/pill-composer-builder.ts +28 -24
- package/src/components/reasoning-bubble.ts +2 -2
- package/src/components/suggestions.ts +1 -1
- package/src/components/tool-bubble.ts +1 -1
- package/src/components/widget-view.test.ts +181 -0
- package/src/components/widget-view.ts +234 -0
- package/src/defaults.ts +54 -51
- package/src/generated/runtype-openapi-contract.ts +5 -0
- package/src/index-core.ts +30 -4
- package/src/index-global.ts +73 -6
- package/src/index.ts +7 -1
- package/src/install.test.ts +11 -11
- package/src/install.ts +28 -18
- package/src/launcher-global.ts +25 -14
- package/src/markdown-parsers-eager.ts +20 -0
- package/src/markdown-parsers-entry.ts +4 -0
- package/src/markdown-parsers-loader.ts +49 -0
- package/src/plugin-kit.test.ts +1 -1
- package/src/plugin-kit.ts +7 -7
- package/src/plugins/types.ts +5 -5
- package/src/postprocessors.ts +27 -14
- package/src/runtime/host-layout.test.ts +1 -1
- package/src/runtime/host-layout.ts +4 -5
- package/src/runtime/init.ts +2 -2
- package/src/session.test.ts +5 -6
- package/src/session.ts +333 -227
- package/src/session.voice.test.ts +146 -0
- package/src/session.webmcp.test.ts +24 -25
- package/src/smart-dom-reader.ts +3 -4
- package/src/styles/widget.css +54 -36
- package/src/suggest-replies-tool.test.ts +3 -3
- package/src/suggest-replies-tool.ts +5 -5
- package/src/testing/index.ts +1 -1
- package/src/theme-editor/color-utils.ts +2 -2
- package/src/theme-editor/index.ts +4 -13
- package/src/theme-editor/presets.ts +1 -1
- package/src/theme-editor/preview-utils.ts +22 -20
- package/src/theme-editor/preview.ts +4 -1
- package/src/theme-editor/role-mappings.ts +3 -3
- package/src/theme-editor/sections.ts +21 -20
- package/src/theme-editor/types.ts +1 -1
- package/src/theme-editor/webmcp/index.ts +1 -1
- package/src/theme-editor/webmcp/summary.ts +1 -2
- package/src/theme-editor/webmcp/tools.ts +30 -30
- package/src/theme-editor/webmcp/types.ts +2 -2
- package/src/theme-editor-preview.ts +10 -0
- package/src/theme-reference.ts +26 -26
- package/src/types.ts +368 -99
- package/src/ui.approval-plugin.test.ts +3 -3
- package/src/ui.ask-user-question-plugin.test.ts +9 -9
- package/src/ui.component-directive.test.ts +4 -4
- package/src/ui.composer-bar.test.ts +10 -11
- package/src/ui.composer-keyboard.test.ts +5 -5
- package/src/ui.header-icon-color.test.ts +59 -0
- package/src/ui.scroll.test.ts +5 -6
- package/src/ui.stop-button.test.ts +3 -4
- package/src/ui.suggest-replies.test.ts +2 -2
- package/src/ui.ts +292 -131
- package/src/utils/buttons.ts +1 -1
- package/src/utils/code-generators.ts +1 -1
- package/src/utils/composer-history.ts +3 -3
- package/src/utils/dom-context.test.ts +2 -2
- package/src/utils/dom-context.ts +7 -7
- package/src/utils/dom.test.ts +67 -0
- package/src/utils/dom.ts +75 -0
- package/src/utils/dropdown.ts +2 -2
- package/src/utils/event-stream-buffer.test.ts +2 -2
- package/src/utils/message-fingerprint.test.ts +9 -0
- package/src/utils/message-fingerprint.ts +5 -0
- package/src/utils/morph.ts +1 -1
- package/src/utils/sanitize.ts +32 -16
- package/src/utils/sequence-buffer.test.ts +8 -8
- package/src/utils/sequence-buffer.ts +4 -4
- package/src/utils/smart-dom-adapter.test.ts +1 -1
- package/src/utils/smart-dom-adapter.ts +4 -5
- package/src/utils/speech-text.test.ts +122 -0
- package/src/utils/speech-text.ts +101 -0
- package/src/utils/stream-animation.test.ts +3 -3
- package/src/utils/stream-animation.ts +6 -6
- package/src/utils/theme.test.ts +1 -1
- package/src/utils/throughput-tracker.test.ts +11 -11
- package/src/utils/throughput-tracker.ts +9 -9
- package/src/utils/tokens.ts +13 -13
- package/src/utils/virtual-scroller.ts +1 -1
- package/src/vendor/smart-dom-reader/README.md +4 -4
- package/src/vendor/smart-dom-reader/index.d.ts +1 -1
- package/src/vendor/smart-dom-reader/index.js +2 -2
- package/src/version.ts +1 -1
- package/src/voice/audio-playback-manager.test.ts +159 -0
- package/src/voice/audio-playback-manager.ts +145 -30
- package/src/voice/browser-speech-engine.ts +130 -0
- package/src/voice/fallback-speech-engine.ts +89 -0
- package/src/voice/index.ts +21 -0
- package/src/voice/read-aloud-controller.test.ts +143 -0
- package/src/voice/read-aloud-controller.ts +136 -0
- package/src/voice/runtype-speech-engine.test.ts +280 -0
- package/src/voice/runtype-speech-engine.ts +211 -0
- package/src/voice/runtype-tts-entry.ts +10 -0
- package/src/voice/runtype-tts-loader.test.ts +47 -0
- package/src/voice/runtype-tts-loader.ts +42 -0
- package/src/voice/runtype-voice-provider.ts +332 -537
- package/src/voice/voice-factory.ts +26 -4
- package/src/voice/voice.test.ts +321 -7
- package/src/voice/worklet-playback-engine.ts +272 -0
- package/src/voice-worklet-player.ts +39 -0
- package/src/webmcp-bridge.test.ts +6 -6
- package/src/webmcp-bridge.ts +24 -25
- package/src/webmcp-polyfill.ts +1 -1
- package/src/voice/voice-activity-detector.ts +0 -90
package/dist/index.global.js
CHANGED
|
@@ -1,66 +1,21 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(r[o]);)o++};return s()},V0=Dh;Qr.parse=V0});var Kw={};mb(Kw,{ASK_USER_QUESTION_CLIENT_TOOL:()=>$d,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>zd,ASK_USER_QUESTION_TOOL_NAME:()=>$s,AgentWidgetClient:()=>ya,AgentWidgetSession:()=>Za,AttachmentManager:()=>wa,DEFAULT_COMPONENTS:()=>$p,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Sl,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Wo,DEFAULT_PALETTE:()=>qp,DEFAULT_SEMANTIC:()=>zp,DEFAULT_WIDGET_CONFIG:()=>Xt,PRESETS:()=>Lu,PRESET_FULLSCREEN:()=>Eu,PRESET_MINIMAL:()=>ku,PRESET_SHOP:()=>Mu,SUGGEST_REPLIES_CLIENT_TOOL:()=>Qi,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Fd,SUGGEST_REPLIES_TOOL_NAME:()=>en,THEME_ZONES:()=>bx,VERSION:()=>By,WEBMCP_TOOL_PREFIX:()=>Cn,WebMcpBridge:()=>Ga,accessibilityPlugin:()=>Dy,animationsPlugin:()=>Oy,applyThemeVariables:()=>Vn,attachHeaderToContainer:()=>Ta,brandPlugin:()=>_y,buildComposer:()=>ns,buildDefaultHeader:()=>eu,buildHeader:()=>kn,buildHeaderWithLayout:()=>os,buildMinimalHeader:()=>tu,builtInClientToolsForDispatch:()=>Gs,collectEnrichedPageContext:()=>Iy,componentRegistry:()=>En,createActionManager:()=>hi,createAgentExperience:()=>sd,createAskUserQuestionBubble:()=>Xh,createBestAvailableVoiceProvider:()=>ul,createBubbleWithLayout:()=>Ux,createCSATFeedback:()=>od,createComboButton:()=>Nl,createComponentMiddleware:()=>py,createComponentStreamParser:()=>Zl,createDefaultSanitizer:()=>Pd,createDirectivePostprocessor:()=>uh,createDropdownMenu:()=>Xn,createFlexibleJsonStreamParser:()=>Zh,createIconButton:()=>Br,createImagePart:()=>sx,createJsonStreamParser:()=>nl,createLabelButton:()=>ci,createLocalStorageAdapter:()=>Jl,createMarkdownProcessor:()=>_s,createMarkdownProcessorFromConfig:()=>ua,createMessageActions:()=>su,createNPSFeedback:()=>nd,createPlainTextParser:()=>rl,createPlugin:()=>Uy,createRegexJsonParser:()=>ol,createStandardBubble:()=>as,createTextPart:()=>Qs,createTheme:()=>ts,createThemeObserver:()=>El,createToggleGroup:()=>Wx,createTypingIndicator:()=>Ma,createVoiceProvider:()=>Ca,createWidgetHostLayout:()=>xi,createXmlParser:()=>al,defaultActionHandlers:()=>Ea,defaultJsonActionParser:()=>gi,defaultParseRules:()=>Su,detectColorScheme:()=>ti,directivePostprocessor:()=>fh,ensureAskUserQuestionSheet:()=>Qa,escapeHtml:()=>fa,extractComponentDirectiveFromMessage:()=>rd,fileToImagePart:()=>ix,formatEnrichedContext:()=>Hy,generateAssistantMessageId:()=>ba,generateMessageId:()=>tx,generateStableSelector:()=>Tu,generateUserMessageId:()=>Ja,getActiveTheme:()=>rs,getColorScheme:()=>jp,getDisplayText:()=>ox,getHeaderLayout:()=>ru,getImageParts:()=>ax,getPreset:()=>zy,hasComponentDirective:()=>td,hasImages:()=>nx,headerLayouts:()=>Fl,highContrastPlugin:()=>Fy,initAgentWidget:()=>Cy,isAskUserQuestionMessage:()=>wn,isComponentDirectiveType:()=>cy,isDockedMountMode:()=>Lr,isSuggestRepliesMessage:()=>js,isVoiceSupported:()=>Js,isWebMcpToolName:()=>ga,latestAgentSuggestions:()=>Yi,listRegisteredStreamAnimations:()=>Qp,markdownPostprocessor:()=>wd,mergeWithDefaults:()=>Tl,normalizeContent:()=>rx,parseAskUserQuestionPayload:()=>An,parseSuggestRepliesPayload:()=>qd,pluginRegistry:()=>mi,reducedMotionPlugin:()=>Ny,registerStreamAnimationPlugin:()=>Sa,removeAskUserQuestionSheet:()=>zn,renderComponentDirective:()=>ed,renderLoadingIndicatorWithFallback:()=>au,renderLucideIcon:()=>Ee,resolveDockConfig:()=>Bo,resolveSanitizer:()=>ja,resolveTokens:()=>Ml,stripWebMcpPrefix:()=>zi,themeToCssVariables:()=>kl,unregisterStreamAnimationPlugin:()=>Xp,validateImageFile:()=>lx,validateTheme:()=>Vp});function hd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var pa=hd();function Jg(r){pa=r}var Zg=/[&<>"']/,xb=new RegExp(Zg.source,"g"),eh=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,yb=new RegExp(eh.source,"g"),bb={"&":"&","<":"<",">":">",'"':""","'":"'"},Gg=r=>bb[r];function Ho(r,e){if(e){if(Zg.test(r))return r.replace(xb,Gg)}else if(eh.test(r))return r.replace(yb,Gg);return r}var vb=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Cb(r){return r.replace(vb,(e,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}var wb=/(^|[^\[])\^/g;function rr(r,e){let t=typeof r=="string"?r:r.source;e=e||"";let o={replace:(n,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(wb,"$1"),t=t.replace(n,s),o},getRegex:()=>new RegExp(t,e)};return o}function Kg(r){try{r=encodeURI(r).replace(/%25/g,"%")}catch{return null}return r}var Hs={exec:()=>null};function Xg(r,e){let t=r.replace(/\|/g,(a,s,i)=>{let d=!1,l=s;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),o=t.split(/ \|/),n=0;if(o[0].trim()||o.shift(),o.length>0&&!o[o.length-1].trim()&&o.pop(),e)if(o.length>e)o.splice(e);else for(;o.length<e;)o.push("");for(;n<o.length;n++)o[n]=o[n].trim().replace(/\\\|/g,"|");return o}function Oi(r,e,t){let o=r.length;if(o===0)return"";let n=0;for(;n<o;){let a=r.charAt(o-n-1);if(a===e&&!t)n++;else if(a!==e&&t)n++;else break}return r.slice(0,o-n)}function Ab(r,e){if(r.indexOf(e[1])===-1)return-1;let t=0;for(let o=0;o<r.length;o++)if(r[o]==="\\")o++;else if(r[o]===e[0])t++;else if(r[o]===e[1]&&(t--,t<0))return o;return-1}function Qg(r,e,t,o){let n=e.href,a=e.title?Ho(e.title):null,s=r[1].replace(/\\([\[\]])/g,"$1");if(r[0].charAt(0)!=="!"){o.state.inLink=!0;let i={type:"link",raw:t,href:n,title:a,text:s,tokens:o.inlineTokens(s)};return o.state.inLink=!1,i}return{type:"image",raw:t,href:n,title:a,text:Ho(s)}}function Sb(r,e){let t=r.match(/^(\s+)(?:```)/);if(t===null)return e;let o=t[1];return e.split(`
|
|
3
|
-
`).map(n=>{let a=n.match(/^\s+/);if(a===null)return n;let[s]=a;return s.length>=o.length?n.slice(o.length):n}).join(`
|
|
4
|
-
`)}var qa=class{constructor(e){lr(this,"options");lr(this,"rules");lr(this,"lexer");this.options=e||pa}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let o=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?o:Oi(o,`
|
|
5
|
-
`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let o=t[0],n=Sb(o,t[3]||"");return{type:"code",raw:o,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let o=t[2].trim();if(/#$/.test(o)){let n=Oi(o,"#");(this.options.pedantic||!n||/ $/.test(n))&&(o=n.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:o,tokens:this.lexer.inline(o)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let o=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
|
|
6
|
-
$1`);o=Oi(o.replace(/^ *>[ \t]?/gm,""),`
|
|
7
|
-
`);let n=this.lexer.state.top;this.lexer.state.top=!0;let a=this.lexer.blockTokens(o);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:a,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let o=t[1].trim(),n=o.length>1,a={type:"list",raw:"",ordered:n,start:n?+o.slice(0,-1):"",loose:!1,items:[]};o=n?`\\d{1,9}\\${o.slice(-1)}`:`\\${o}`,this.options.pedantic&&(o=n?o:"[*+-]");let s=new RegExp(`^( {0,3}${o})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;e;){let u=!1;if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;i=t[0],e=e.substring(i.length);let f=t[2].split(`
|
|
8
|
-
`,1)[0].replace(/^\t+/,M=>" ".repeat(3*M.length)),p=e.split(`
|
|
9
|
-
`,1)[0],m=0;this.options.pedantic?(m=2,d=f.trimStart()):(m=t[2].search(/[^ ]/),m=m>4?1:m,d=f.slice(m),m+=t[1].length);let y=!1;if(!f&&/^ *$/.test(p)&&(i+=p+`
|
|
10
|
-
`,e=e.substring(p.length+1),u=!0),!u){let M=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),k=new RegExp(`^ {0,${Math.min(3,m-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),L=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:\`\`\`|~~~)`),x=new RegExp(`^ {0,${Math.min(3,m-1)}}#`);for(;e;){let w=e.split(`
|
|
11
|
-
`,1)[0];if(p=w,this.options.pedantic&&(p=p.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),L.test(p)||x.test(p)||M.test(p)||k.test(e))break;if(p.search(/[^ ]/)>=m||!p.trim())d+=`
|
|
12
|
-
`+p.slice(m);else{if(y||f.search(/[^ ]/)>=4||L.test(f)||x.test(f)||k.test(f))break;d+=`
|
|
13
|
-
`+p}!y&&!p.trim()&&(y=!0),i+=w+`
|
|
14
|
-
`,e=e.substring(w.length+1),f=p.slice(m)}}a.loose||(l?a.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let h=null,T;this.options.gfm&&(h=/^\[[ xX]\] /.exec(d),h&&(T=h[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),a.items.push({type:"list_item",raw:i,task:!!h,checked:T,loose:!1,text:d,tokens:[]}),a.raw+=i}a.items[a.items.length-1].raw=i.trimEnd(),a.items[a.items.length-1].text=d.trimEnd(),a.raw=a.raw.trimEnd();for(let u=0;u<a.items.length;u++)if(this.lexer.state.top=!1,a.items[u].tokens=this.lexer.blockTokens(a.items[u].text,[]),!a.loose){let f=a.items[u].tokens.filter(m=>m.type==="space"),p=f.length>0&&f.some(m=>/\n.*\n/.test(m.raw));a.loose=p}if(a.loose)for(let u=0;u<a.items.length;u++)a.items[u].loose=!0;return a}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let o=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:o,raw:t[0],href:n,title:a}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!/[:|]/.test(t[2]))return;let o=Xg(t[1]),n=t[2].replace(/^\||\| *$/g,"").split("|"),a=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(`
|
|
15
|
-
`):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(o.length===n.length){for(let i of n)/^ *-+: *$/.test(i)?s.align.push("right"):/^ *:-+: *$/.test(i)?s.align.push("center"):/^ *:-+ *$/.test(i)?s.align.push("left"):s.align.push(null);for(let i of o)s.header.push({text:i,tokens:this.lexer.inline(i)});for(let i of a)s.rows.push(Xg(i,s.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let o=t[1].charAt(t[1].length-1)===`
|
|
16
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:o,tokens:this.lexer.inline(o)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:Ho(t[1])}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let o=t[2].trim();if(!this.options.pedantic&&/^</.test(o)){if(!/>$/.test(o))return;let s=Oi(o.slice(0,-1),"\\");if((o.length-s.length)%2===0)return}else{let s=Ab(t[2],"()");if(s>-1){let d=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,d).trim(),t[3]=""}}let n=t[2],a="";if(this.options.pedantic){let s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);s&&(n=s[1],a=s[3])}else a=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(this.options.pedantic&&!/>$/.test(o)?n=n.slice(1):n=n.slice(1,-1)),Qg(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer)}}reflink(e,t){let o;if((o=this.rules.inline.reflink.exec(e))||(o=this.rules.inline.nolink.exec(e))){let n=(o[2]||o[1]).replace(/\s+/g," "),a=t[n.toLowerCase()];if(!a){let s=o[0].charAt(0);return{type:"text",raw:s,text:s}}return Qg(o,a,o[0],this.lexer)}}emStrong(e,t,o=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!n||n[3]&&o.match(/[\p{L}\p{N}]/u))return;if(!(n[1]||n[2]||"")||!o||this.rules.inline.punctuation.exec(o)){let s=[...n[0]].length-1,i,d,l=s,u=0,f=n[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+s);(n=f.exec(t))!=null;){if(i=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!i)continue;if(d=[...i].length,n[3]||n[4]){l+=d;continue}else if((n[5]||n[6])&&s%3&&!((s+d)%3)){u+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+u);let p=[...n[0]][0].length,m=e.slice(0,s+n.index+p+d);if(Math.min(s,d)%2){let h=m.slice(1,-1);return{type:"em",raw:m,text:h,tokens:this.lexer.inlineTokens(h)}}let y=m.slice(2,-2);return{type:"strong",raw:m,text:y,tokens:this.lexer.inlineTokens(y)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let o=t[2].replace(/\n/g," "),n=/[^ ]/.test(o),a=/^ /.test(o)&&/ $/.test(o);return n&&a&&(o=o.substring(1,o.length-1)),o=Ho(o,!0),{type:"codespan",raw:t[0],text:o}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let o,n;return t[2]==="@"?(o=Ho(t[1]),n="mailto:"+o):(o=Ho(t[1]),n=o),{type:"link",raw:t[0],text:o,href:n,tokens:[{type:"text",raw:o,text:o}]}}}url(e){var o,n;let t;if(t=this.rules.inline.url.exec(e)){let a,s;if(t[2]==="@")a=Ho(t[0]),s="mailto:"+a;else{let i;do i=t[0],t[0]=(n=(o=this.rules.inline._backpedal.exec(t[0]))==null?void 0:o[0])!=null?n:"";while(i!==t[0]);a=Ho(t[0]),t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:a,href:s,tokens:[{type:"text",raw:a,text:a}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let o;return this.lexer.state.inRawBlock?o=t[0]:o=Ho(t[0]),{type:"text",raw:t[0],text:o}}}},Tb=/^(?: *(?:\n|$))+/,Mb=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,kb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ds=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Eb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,th=/(?:[*+-]|\d{1,9}[.)])/,rh=rr(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,th).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),xd=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Lb=/^[^\n]+/,yd=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Pb=rr(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",yd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Rb=rr(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,th).getRegex(),Fi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",bd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ib=rr("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",bd).replace("tag",Fi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),oh=rr(xd).replace("hr",Ds).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex(),Hb=rr(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",oh).getRegex(),vd={blockquote:Hb,code:Mb,def:Pb,fences:kb,heading:Eb,hr:Ds,html:Ib,lheading:rh,list:Rb,newline:Tb,paragraph:oh,table:Hs,text:Lb},Yg=rr("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ds).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex(),Wb={...vd,table:Yg,paragraph:rr(xd).replace("hr",Ds).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Yg).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex()},Bb={...vd,html:rr(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",bd).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Hs,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:rr(xd).replace("hr",Ds).replace("heading",` *#{1,6} *[^
|
|
17
|
-
]`).replace("lheading",rh).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},nh=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Db=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ah=/^( {2,}|\\)\n(?!\s*$)/,Ob=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Os="\\p{P}\\p{S}",_b=rr(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Os).getRegex(),Nb=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,Fb=rr(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Os).getRegex(),Ub=rr("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Os).getRegex(),qb=rr("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Os).getRegex(),zb=rr(/\\([punct])/,"gu").replace(/punct/g,Os).getRegex(),$b=rr(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Vb=rr(bd).replace("(?:-->|$)","-->").getRegex(),jb=rr("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Vb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ni=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Gb=rr(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",Ni).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),sh=rr(/^!?\[(label)\]\[(ref)\]/).replace("label",Ni).replace("ref",yd).getRegex(),ih=rr(/^!?\[(ref)\](?:\[\])?/).replace("ref",yd).getRegex(),Kb=rr("reflink|nolink(?!\\()","g").replace("reflink",sh).replace("nolink",ih).getRegex(),Cd={_backpedal:Hs,anyPunctuation:zb,autolink:$b,blockSkip:Nb,br:ah,code:Db,del:Hs,emStrongLDelim:Fb,emStrongRDelimAst:Ub,emStrongRDelimUnd:qb,escape:nh,link:Gb,nolink:ih,punctuation:_b,reflink:sh,reflinkSearch:Kb,tag:jb,text:Ob,url:Hs},Xb={...Cd,link:rr(/^!?\[(label)\]\((.*?)\)/).replace("label",Ni).getRegex(),reflink:rr(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ni).getRegex()},md={...Cd,escape:rr(nh).replace("])","~|])").getRegex(),url:rr(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Qb={...md,br:rr(ah).replace("{2,}","*").getRegex(),text:rr(md.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},_i={normal:vd,gfm:Wb,pedantic:Bb},Is={normal:Cd,gfm:md,breaks:Qb,pedantic:Xb},bn=class r{constructor(e){lr(this,"tokens");lr(this,"options");lr(this,"state");lr(this,"tokenizer");lr(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||pa,this.options.tokenizer=this.options.tokenizer||new qa,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={block:_i.normal,inline:Is.normal};this.options.pedantic?(t.block=_i.pedantic,t.inline=Is.pedantic):this.options.gfm&&(t.block=_i.gfm,this.options.breaks?t.inline=Is.breaks:t.inline=Is.gfm),this.tokenizer.rules=t}static get rules(){return{block:_i,inline:Is}}static lex(e,t){return new r(t).lex(e)}static lexInline(e,t){return new r(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,`
|
|
18
|
-
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let o=this.inlineQueue[t];this.inlineTokens(o.src,o.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let o,n,a,s;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(o=i.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))){if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length),o.raw.length===1&&t.length>0?t[t.length-1].raw+=`
|
|
19
|
-
`:t.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length),n=t[t.length-1],n&&(n.type==="paragraph"||n.type==="text")?(n.raw+=`
|
|
20
|
-
`+o.raw,n.text+=`
|
|
21
|
-
`+o.text,this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length),n=t[t.length-1],n&&(n.type==="paragraph"||n.type==="text")?(n.raw+=`
|
|
22
|
-
`+o.raw,n.text+=`
|
|
23
|
-
`+o.raw,this.inlineQueue[this.inlineQueue.length-1].src=n.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title});continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),t.push(o);continue}if(a=e,this.options.extensions&&this.options.extensions.startBlock){let i=1/0,d=e.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},d),typeof l=="number"&&l>=0&&(i=Math.min(i,l))}),i<1/0&&i>=0&&(a=e.substring(0,i+1))}if(this.state.top&&(o=this.tokenizer.paragraph(a))){n=t[t.length-1],s&&n.type==="paragraph"?(n.raw+=`
|
|
24
|
-
`+o.raw,n.text+=`
|
|
25
|
-
`+o.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(o),s=a.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length),n=t[t.length-1],n&&n.type==="text"?(n.raw+=`
|
|
26
|
-
`+o.raw,n.text+=`
|
|
27
|
-
`+o.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(o);continue}if(e){let i="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let o,n,a,s=e,i,d,l;if(this.tokens.links){let u=Object.keys(this.tokens.links);if(u.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)u.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(o=u.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))){if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),n=t[t.length-1],n&&o.type==="text"&&n.type==="text"?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length),n=t[t.length-1],n&&o.type==="text"&&n.type==="text"?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,s,l)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}if(a=e,this.options.extensions&&this.options.extensions.startInline){let u=1/0,f=e.slice(1),p;this.options.extensions.startInline.forEach(m=>{p=m.call({lexer:this},f),typeof p=="number"&&p>=0&&(u=Math.min(u,p))}),u<1/0&&u>=0&&(a=e.substring(0,u+1))}if(o=this.tokenizer.inlineText(a)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(l=o.raw.slice(-1)),d=!0,n=t[t.length-1],n&&n.type==="text"?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(e){let u="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}},za=class{constructor(e){lr(this,"options");this.options=e||pa}code(e,t,o){var a;let n=(a=(t||"").match(/^\S*/))==null?void 0:a[0];return e=e.replace(/\n$/,"")+`
|
|
28
|
-
`,n?'<pre><code class="language-'+Ho(n)+'">'+(o?e:Ho(e,!0))+`</code></pre>
|
|
29
|
-
`:"<pre><code>"+(o?e:Ho(e,!0))+`</code></pre>
|
|
30
|
-
`}blockquote(e){return`<blockquote>
|
|
31
|
-
${e}</blockquote>
|
|
32
|
-
`}html(e,t){return e}heading(e,t,o){return`<h${t}>${e}</h${t}>
|
|
33
|
-
`}hr(){return`<hr>
|
|
34
|
-
`}list(e,t,o){let n=t?"ol":"ul",a=t&&o!==1?' start="'+o+'"':"";return"<"+n+a+`>
|
|
35
|
-
`+e+"</"+n+`>
|
|
36
|
-
`}listitem(e,t,o){return`<li>${e}</li>
|
|
37
|
-
`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>
|
|
38
|
-
`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),`<table>
|
|
39
|
-
<thead>
|
|
40
|
-
`+e+`</thead>
|
|
41
|
-
`+t+`</table>
|
|
42
|
-
`}tablerow(e){return`<tr>
|
|
43
|
-
${e}</tr>
|
|
44
|
-
`}tablecell(e,t){let o=t.header?"th":"td";return(t.align?`<${o} align="${t.align}">`:`<${o}>`)+e+`</${o}>
|
|
45
|
-
`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,t,o){let n=Kg(e);if(n===null)return o;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+t+'"'),a+=">"+o+"</a>",a}image(e,t,o){let n=Kg(e);if(n===null)return o;e=n;let a=`<img src="${e}" alt="${o}"`;return t&&(a+=` title="${t}"`),a+=">",a}text(e){return e}},Ws=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,o){return""+o}image(e,t,o){return""+o}br(){return""}},vn=class r{constructor(e){lr(this,"options");lr(this,"renderer");lr(this,"textRenderer");this.options=e||pa,this.options.renderer=this.options.renderer||new za,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Ws}static parse(e,t){return new r(t).parse(e)}static parseInline(e,t){return new r(t).parseInline(e)}parse(e,t=!0){let o="";for(let n=0;n<e.length;n++){let a=e[n];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=a,i=this.options.extensions.renderers[s.type].call({parser:this},s);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(s.type)){o+=i||"";continue}}switch(a.type){case"space":continue;case"hr":{o+=this.renderer.hr();continue}case"heading":{let s=a;o+=this.renderer.heading(this.parseInline(s.tokens),s.depth,Cb(this.parseInline(s.tokens,this.textRenderer)));continue}case"code":{let s=a;o+=this.renderer.code(s.text,s.lang,!!s.escaped);continue}case"table":{let s=a,i="",d="";for(let u=0;u<s.header.length;u++)d+=this.renderer.tablecell(this.parseInline(s.header[u].tokens),{header:!0,align:s.align[u]});i+=this.renderer.tablerow(d);let l="";for(let u=0;u<s.rows.length;u++){let f=s.rows[u];d="";for(let p=0;p<f.length;p++)d+=this.renderer.tablecell(this.parseInline(f[p].tokens),{header:!1,align:s.align[p]});l+=this.renderer.tablerow(d)}o+=this.renderer.table(i,l);continue}case"blockquote":{let s=a,i=this.parse(s.tokens);o+=this.renderer.blockquote(i);continue}case"list":{let s=a,i=s.ordered,d=s.start,l=s.loose,u="";for(let f=0;f<s.items.length;f++){let p=s.items[f],m=p.checked,y=p.task,h="";if(p.task){let T=this.renderer.checkbox(!!m);l?p.tokens.length>0&&p.tokens[0].type==="paragraph"?(p.tokens[0].text=T+" "+p.tokens[0].text,p.tokens[0].tokens&&p.tokens[0].tokens.length>0&&p.tokens[0].tokens[0].type==="text"&&(p.tokens[0].tokens[0].text=T+" "+p.tokens[0].tokens[0].text)):p.tokens.unshift({type:"text",text:T+" "}):h+=T+" "}h+=this.parse(p.tokens,l),u+=this.renderer.listitem(h,y,!!m)}o+=this.renderer.list(u,i,d);continue}case"html":{let s=a;o+=this.renderer.html(s.text,s.block);continue}case"paragraph":{let s=a;o+=this.renderer.paragraph(this.parseInline(s.tokens));continue}case"text":{let s=a,i=s.tokens?this.parseInline(s.tokens):s.text;for(;n+1<e.length&&e[n+1].type==="text";)s=e[++n],i+=`
|
|
46
|
-
`+(s.tokens?this.parseInline(s.tokens):s.text);o+=t?this.renderer.paragraph(i):i;continue}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return o}parseInline(e,t){t=t||this.renderer;let o="";for(let n=0;n<e.length;n++){let a=e[n];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){o+=s||"";continue}}switch(a.type){case"escape":{let s=a;o+=t.text(s.text);break}case"html":{let s=a;o+=t.html(s.text);break}case"link":{let s=a;o+=t.link(s.href,s.title,this.parseInline(s.tokens,t));break}case"image":{let s=a;o+=t.image(s.href,s.title,s.text);break}case"strong":{let s=a;o+=t.strong(this.parseInline(s.tokens,t));break}case"em":{let s=a;o+=t.em(this.parseInline(s.tokens,t));break}case"codespan":{let s=a;o+=t.codespan(s.text);break}case"br":{o+=t.br();break}case"del":{let s=a;o+=t.del(this.parseInline(s.tokens,t));break}case"text":{let s=a;o+=t.text(s.text);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return o}},la=class{constructor(e){lr(this,"options");this.options=e||pa}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}};lr(la,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var ca,gd,lh,Bs=class{constructor(...e){jg(this,ca);lr(this,"defaults",hd());lr(this,"options",this.setOptions);lr(this,"parse",Di(this,ca,gd).call(this,bn.lex,vn.parse));lr(this,"parseInline",Di(this,ca,gd).call(this,bn.lexInline,vn.parseInline));lr(this,"Parser",vn);lr(this,"Renderer",za);lr(this,"TextRenderer",Ws);lr(this,"Lexer",bn);lr(this,"Tokenizer",qa);lr(this,"Hooks",la);this.use(...e)}walkTokens(e,t){var n,a;let o=[];for(let s of e)switch(o=o.concat(t.call(this,s)),s.type){case"table":{let i=s;for(let d of i.header)o=o.concat(this.walkTokens(d.tokens,t));for(let d of i.rows)for(let l of d)o=o.concat(this.walkTokens(l.tokens,t));break}case"list":{let i=s;o=o.concat(this.walkTokens(i.items,t));break}default:{let i=s;(a=(n=this.defaults.extensions)==null?void 0:n.childTokens)!=null&&a[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);o=o.concat(this.walkTokens(l,t))}):i.tokens&&(o=o.concat(this.walkTokens(i.tokens,t)))}}return o}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(o=>{let n={...o};if(n.async=this.defaults.async||n.async||!1,o.extensions&&(o.extensions.forEach(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let s=t.renderers[a.name];s?t.renderers[a.name]=function(...i){let d=a.renderer.apply(this,i);return d===!1&&(d=s.apply(this,i)),d}:t.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[a.level];s?s.unshift(a.tokenizer):t[a.level]=[a.tokenizer],a.start&&(a.level==="block"?t.startBlock?t.startBlock.push(a.start):t.startBlock=[a.start]:a.level==="inline"&&(t.startInline?t.startInline.push(a.start):t.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(t.childTokens[a.name]=a.childTokens)}),n.extensions=t),o.renderer){let a=this.defaults.renderer||new za(this.defaults);for(let s in o.renderer){if(!(s in a))throw new Error(`renderer '${s}' does not exist`);if(s==="options")continue;let i=s,d=o.renderer[i],l=a[i];a[i]=(...u)=>{let f=d.apply(a,u);return f===!1&&(f=l.apply(a,u)),f||""}}n.renderer=a}if(o.tokenizer){let a=this.defaults.tokenizer||new qa(this.defaults);for(let s in o.tokenizer){if(!(s in a))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,d=o.tokenizer[i],l=a[i];a[i]=(...u)=>{let f=d.apply(a,u);return f===!1&&(f=l.apply(a,u)),f}}n.tokenizer=a}if(o.hooks){let a=this.defaults.hooks||new la;for(let s in o.hooks){if(!(s in a))throw new Error(`hook '${s}' does not exist`);if(s==="options")continue;let i=s,d=o.hooks[i],l=a[i];la.passThroughHooks.has(s)?a[i]=u=>{if(this.defaults.async)return Promise.resolve(d.call(a,u)).then(p=>l.call(a,p));let f=d.call(a,u);return l.call(a,f)}:a[i]=(...u)=>{let f=d.apply(a,u);return f===!1&&(f=l.apply(a,u)),f}}n.hooks=a}if(o.walkTokens){let a=this.defaults.walkTokens,s=o.walkTokens;n.walkTokens=function(i){let d=[];return d.push(s.call(this,i)),a&&(d=d.concat(a.call(this,i))),d}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return bn.lex(e,t!=null?t:this.defaults)}parser(e,t){return vn.parse(e,t!=null?t:this.defaults)}};ca=new WeakSet,gd=function(e,t){return(o,n)=>{let a={...n},s={...this.defaults,...a};this.defaults.async===!0&&a.async===!1&&(s.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),s.async=!0);let i=Di(this,ca,lh).call(this,!!s.silent,!!s.async);if(typeof o=="undefined"||o===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof o!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(o)+", string expected"));if(s.hooks&&(s.hooks.options=s),s.async)return Promise.resolve(s.hooks?s.hooks.preprocess(o):o).then(d=>e(d,s)).then(d=>s.hooks?s.hooks.processAllTokens(d):d).then(d=>s.walkTokens?Promise.all(this.walkTokens(d,s.walkTokens)).then(()=>d):d).then(d=>t(d,s)).then(d=>s.hooks?s.hooks.postprocess(d):d).catch(i);try{s.hooks&&(o=s.hooks.preprocess(o));let d=e(o,s);s.hooks&&(d=s.hooks.processAllTokens(d)),s.walkTokens&&this.walkTokens(d,s.walkTokens);let l=t(d,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(d){return i(d)}}},lh=function(e,t){return o=>{if(o.message+=`
|
|
47
|
-
Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+Ho(o.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(o);throw o}};var da=new Bs;function tr(r,e){return da.parse(r,e)}tr.options=tr.setOptions=function(r){return da.setOptions(r),tr.defaults=da.defaults,Jg(tr.defaults),tr};tr.getDefaults=hd;tr.defaults=pa;tr.use=function(...r){return da.use(...r),tr.defaults=da.defaults,Jg(tr.defaults),tr};tr.walkTokens=function(r,e){return da.walkTokens(r,e)};tr.parseInline=da.parseInline;tr.Parser=vn;tr.parser=vn.parse;tr.Renderer=za;tr.TextRenderer=Ws;tr.Lexer=bn;tr.lexer=bn.lex;tr.Tokenizer=qa;tr.Hooks=la;tr.parse=tr;var Jw=tr.options,Zw=tr.setOptions,eA=tr.use,tA=tr.walkTokens,rA=tr.parseInline;var oA=vn.parse,nA=bn.lex;var Yb=r=>{if(r)return r},_s=r=>{var n,a;let e=r==null?void 0:r.markedOptions,t=new Bs({gfm:(n=e==null?void 0:e.gfm)!=null?n:!0,breaks:(a=e==null?void 0:e.breaks)!=null?a:!0,pedantic:e==null?void 0:e.pedantic,silent:e==null?void 0:e.silent}),o=Yb(r==null?void 0:r.renderer);return o&&t.use({renderer:o}),s=>t.parse(s)},ua=r=>r?_s({markedOptions:r.options,renderer:r.renderer}):_s(),Jb=_s(),wd=r=>Jb(r),fa=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ch=r=>r.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),dh=r=>`%%FORM_PLACEHOLDER_${r}%%`,ph=(r,e)=>{let t=r;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,n)=>{try{let a=JSON.parse(n.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=dh(e.length);return e.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,n)=>{let a=dh(e.length);return e.push({token:a,type:n}),a}),t},uh=r=>{let e=ua(r);return t=>{let o=[],n=ph(t,o),a=e(n);return o.forEach(({token:s,type:i})=>{let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ch(i)}"></div>`;a=a.replace(d,u)}),a}},fh=r=>{let e=[],t=ph(r,e),o=wd(t);return e.forEach(({token:n,type:a})=>{let s=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ch(a)}"></div>`;o=o.replace(s,d)}),o};function mh(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,o=Array(e);t<e;t++)o[t]=r[t];return o}function Zb(r){if(Array.isArray(r))return r}function e0(r,e){var t=r==null?null:typeof Symbol!="undefined"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var o,n,a,s,i=[],d=!0,l=!1;try{if(a=(t=t.call(r)).next,e!==0)for(;!(d=(o=a.call(t)).done)&&(i.push(o.value),i.length!==e);d=!0);}catch(u){l=!0,n=u}finally{try{if(!d&&t.return!=null&&(s=t.return(),Object(s)!==s))return}finally{if(l)throw n}}return i}}function t0(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
48
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function r0(r,e){return Zb(r)||e0(r,e)||o0(r,e)||t0()}function o0(r,e){if(r){if(typeof r=="string")return mh(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?mh(r,e):void 0}}var Eh=Object.entries,gh=Object.setPrototypeOf,n0=Object.isFrozen,a0=Object.getPrototypeOf,s0=Object.getOwnPropertyDescriptor,Kr=Object.freeze,Xr=Object.seal,Va=Object.create,Lh=typeof Reflect!="undefined"&&Reflect,Ed=Lh.apply,Ld=Lh.construct;Kr||(Kr=function(e){return e});Xr||(Xr=function(e){return e});Ed||(Ed=function(e,t){for(var o=arguments.length,n=new Array(o>2?o-2:0),a=2;a<o;a++)n[a-2]=arguments[a];return e.apply(t,n)});Ld||(Ld=function(e){for(var t=arguments.length,o=new Array(t>1?t-1:0),n=1;n<t;n++)o[n-1]=arguments[n];return new e(...o)});var Ns=Er(Array.prototype.forEach),i0=Er(Array.prototype.lastIndexOf),hh=Er(Array.prototype.pop),$a=Er(Array.prototype.push),l0=Er(Array.prototype.splice),Fn=Array.isArray,qs=Er(String.prototype.toLowerCase),Ad=Er(String.prototype.toString),xh=Er(String.prototype.match),Fs=Er(String.prototype.replace),yh=Er(String.prototype.indexOf),d0=Er(String.prototype.trim),c0=Er(Number.prototype.toString),p0=Er(Boolean.prototype.toString),bh=typeof BigInt=="undefined"?null:Er(BigInt.prototype.toString),vh=typeof Symbol=="undefined"?null:Er(Symbol.prototype.toString),Co=Er(Object.prototype.hasOwnProperty),Us=Er(Object.prototype.toString),Gr=Er(RegExp.prototype.test),ma=u0(TypeError);function Er(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,o=new Array(t>1?t-1:0),n=1;n<t;n++)o[n-1]=arguments[n];return Ed(r,e,o)}}function u0(r){return function(){for(var e=arguments.length,t=new Array(e),o=0;o<e;o++)t[o]=arguments[o];return Ld(r,t)}}function Nt(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:qs;if(gh&&gh(r,null),!Fn(e))return r;let o=e.length;for(;o--;){let n=e[o];if(typeof n=="string"){let a=t(n);a!==n&&(n0(e)||(e[o]=a),n=a)}r[n]=!0}return r}function f0(r){for(let e=0;e<r.length;e++)Co(r,e)||(r[e]=null);return r}function vo(r){let e=Va(null);for(let o of Eh(r)){var t=r0(o,2);let n=t[0],a=t[1];Co(r,n)&&(Fn(a)?e[n]=f0(a):a&&typeof a=="object"&&a.constructor===Object?e[n]=vo(a):e[n]=a)}return e}function m0(r){switch(typeof r){case"string":return r;case"number":return c0(r);case"boolean":return p0(r);case"bigint":return bh?bh(r):"0";case"symbol":return vh?vh(r):"Symbol()";case"undefined":return Us(r);case"function":case"object":{if(r===null)return Us(r);let e=r,t=pn(e,"toString");if(typeof t=="function"){let o=t(e);return typeof o=="string"?o:Us(o)}return Us(r)}default:return Us(r)}}function pn(r,e){for(;r!==null;){let o=s0(r,e);if(o){if(o.get)return Er(o.get);if(typeof o.value=="function")return Er(o.value)}r=a0(r)}function t(){return null}return t}function g0(r){try{return Gr(r,""),!0}catch{return!1}}var Ch=Kr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Sd=Kr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Td=Kr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),h0=Kr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Md=Kr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),x0=Kr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),wh=Kr(["#text"]),Ah=Kr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),kd=Kr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Sh=Kr(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Ui=Kr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),y0=Xr(/{{[\w\W]*|^[\w\W]*}}/g),b0=Xr(/<%[\w\W]*|^[\w\W]*%>/g),v0=Xr(/\${[\w\W]*/g),C0=Xr(/^data-[\-\w.\u00B7-\uFFFF]+$/),w0=Xr(/^aria-[\-\w]+$/),Th=Xr(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),A0=Xr(/^(?:\w+script|data):/i),S0=Xr(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),T0=Xr(/^html$/i),M0=Xr(/^[a-z][.\w]*(-[.\w]+)+$/i),Mh=Xr(/<[/\w!]/g),k0=Xr(/<[/\w]/g),E0=Xr(/<\/no(script|embed|frames)/i),L0=Xr(/\/>/i),cn={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},P0=function(){return typeof window=="undefined"?null:window},R0=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let o=null,n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(o=t.getAttribute(n));let a="dompurify"+(o?"#"+o:"");try{return e.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},kh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Nn=function(e,t,o,n){return Co(e,t)&&Fn(e[t])?Nt(n.base?vo(n.base):{},e[t],n.transform):o};function Ph(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:P0(),e=re=>Ph(re);if(e.version="3.4.10",e.removed=[],!r||!r.document||r.document.nodeType!==cn.document||!r.Element)return e.isSupported=!1,e;let t=r.document,o=t,n=o.currentScript;r.DocumentFragment;let a=r.HTMLTemplateElement,s=r.Node,i=r.Element,d=r.NodeFilter,l=r.NamedNodeMap;l===void 0&&(r.NamedNodeMap||r.MozNamedAttrMap),r.HTMLFormElement;let u=r.DOMParser,f=r.trustedTypes,p=i.prototype,m=pn(p,"cloneNode"),y=pn(p,"remove"),h=pn(p,"nextSibling"),T=pn(p,"childNodes"),M=pn(p,"parentNode"),k=pn(p,"shadowRoot"),L=pn(p,"attributes"),x=s&&s.prototype?pn(s.prototype,"nodeType"):null,w=s&&s.prototype?pn(s.prototype,"nodeName"):null;if(typeof a=="function"){let re=t.createElement("template");re.content&&re.content.ownerDocument&&(t=re.content.ownerDocument)}let v,E="",H,I=!1,P=0,z=function(){if(P>0)throw ma('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},j=function(A){z(),P++;try{return v.createHTML(A)}finally{P--}},ie=function(A){z(),P++;try{return v.createScriptURL(A)}finally{P--}},ve=function(){return I||(H=R0(f,n),I=!0),H},Xe=t,Ae=Xe.implementation,We=Xe.createNodeIterator,Me=Xe.createDocumentFragment,Ue=Xe.getElementsByTagName,Be=o.importNode,Z=kh();e.isSupported=typeof Eh=="function"&&typeof M=="function"&&Ae&&Ae.createHTMLDocument!==void 0;let ne=y0,me=b0,be=v0,ye=C0,Y=w0,ge=A0,Oe=S0,ce=M0,ae=Th,Q=null,Tt=Nt({},[...Ch,...Sd,...Td,...Md,...wh]),Ye=null,De=Nt({},[...Ah,...kd,...Sh,...Ui]),le=Object.seal(Va(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),nt=null,Re=null,K=Object.seal(Va(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),he=!0,it=!0,Pt=!1,te=!0,_e=!1,Ar=!0,Rt=!1,dr=!1,Yr=!1,zr=!1,O=!1,fe=!1,Ie=!0,Je=!1,qe="user-content-",ze=!0,lt=!1,Mt={},Dt=null,or=Nt({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),X=null,wt=Nt({},["audio","video","img","source","image","track"]),ct=null,Ce=Nt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),de="http://www.w3.org/1998/Math/MathML",rt="http://www.w3.org/2000/svg",Ft="http://www.w3.org/1999/xhtml",zt=Ft,Pr=!1,vr=null,xt=Nt({},[de,rt,Ft],Ad),It=Kr(["mi","mo","mn","ms","mtext"]),tt=Nt({},It),jt=Kr(["annotation-xml"]),cr=Nt({},jt),Dr=Nt({},["title","style","font","a","script"]),hr=null,Sr=["application/xhtml+xml","text/html"],Oo="text/html",je=null,Tr=null,io=t.createElement("form"),_o=function(A){return A instanceof RegExp||A instanceof Function},lo=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Tr&&Tr===A)return;(!A||typeof A!="object")&&(A={}),A=vo(A),hr=Sr.indexOf(A.PARSER_MEDIA_TYPE)===-1?Oo:A.PARSER_MEDIA_TYPE,je=hr==="application/xhtml+xml"?Ad:qs,Q=Nn(A,"ALLOWED_TAGS",Tt,{transform:je}),Ye=Nn(A,"ALLOWED_ATTR",De,{transform:je}),vr=Nn(A,"ALLOWED_NAMESPACES",xt,{transform:Ad}),ct=Nn(A,"ADD_URI_SAFE_ATTR",Ce,{transform:je,base:Ce}),X=Nn(A,"ADD_DATA_URI_TAGS",wt,{transform:je,base:wt}),Dt=Nn(A,"FORBID_CONTENTS",or,{transform:je}),nt=Nn(A,"FORBID_TAGS",vo({}),{transform:je}),Re=Nn(A,"FORBID_ATTR",vo({}),{transform:je}),Mt=Co(A,"USE_PROFILES")?A.USE_PROFILES&&typeof A.USE_PROFILES=="object"?vo(A.USE_PROFILES):A.USE_PROFILES:!1,he=A.ALLOW_ARIA_ATTR!==!1,it=A.ALLOW_DATA_ATTR!==!1,Pt=A.ALLOW_UNKNOWN_PROTOCOLS||!1,te=A.ALLOW_SELF_CLOSE_IN_ATTR!==!1,_e=A.SAFE_FOR_TEMPLATES||!1,Ar=A.SAFE_FOR_XML!==!1,Rt=A.WHOLE_DOCUMENT||!1,zr=A.RETURN_DOM||!1,O=A.RETURN_DOM_FRAGMENT||!1,fe=A.RETURN_TRUSTED_TYPE||!1,Yr=A.FORCE_BODY||!1,Ie=A.SANITIZE_DOM!==!1,Je=A.SANITIZE_NAMED_PROPS||!1,ze=A.KEEP_CONTENT!==!1,lt=A.IN_PLACE||!1,ae=g0(A.ALLOWED_URI_REGEXP)?A.ALLOWED_URI_REGEXP:Th,zt=typeof A.NAMESPACE=="string"?A.NAMESPACE:Ft,tt=Co(A,"MATHML_TEXT_INTEGRATION_POINTS")&&A.MATHML_TEXT_INTEGRATION_POINTS&&typeof A.MATHML_TEXT_INTEGRATION_POINTS=="object"?vo(A.MATHML_TEXT_INTEGRATION_POINTS):Nt({},It),cr=Co(A,"HTML_INTEGRATION_POINTS")&&A.HTML_INTEGRATION_POINTS&&typeof A.HTML_INTEGRATION_POINTS=="object"?vo(A.HTML_INTEGRATION_POINTS):Nt({},jt);let _=Co(A,"CUSTOM_ELEMENT_HANDLING")&&A.CUSTOM_ELEMENT_HANDLING&&typeof A.CUSTOM_ELEMENT_HANDLING=="object"?vo(A.CUSTOM_ELEMENT_HANDLING):Va(null);if(le=Va(null),Co(_,"tagNameCheck")&&_o(_.tagNameCheck)&&(le.tagNameCheck=_.tagNameCheck),Co(_,"attributeNameCheck")&&_o(_.attributeNameCheck)&&(le.attributeNameCheck=_.attributeNameCheck),Co(_,"allowCustomizedBuiltInElements")&&typeof _.allowCustomizedBuiltInElements=="boolean"&&(le.allowCustomizedBuiltInElements=_.allowCustomizedBuiltInElements),Xr(le),_e&&(it=!1),O&&(zr=!0),Mt&&(Q=Nt({},wh),Ye=Va(null),Mt.html===!0&&(Nt(Q,Ch),Nt(Ye,Ah)),Mt.svg===!0&&(Nt(Q,Sd),Nt(Ye,kd),Nt(Ye,Ui)),Mt.svgFilters===!0&&(Nt(Q,Td),Nt(Ye,kd),Nt(Ye,Ui)),Mt.mathMl===!0&&(Nt(Q,Md),Nt(Ye,Sh),Nt(Ye,Ui))),K.tagCheck=null,K.attributeCheck=null,Co(A,"ADD_TAGS")&&(typeof A.ADD_TAGS=="function"?K.tagCheck=A.ADD_TAGS:Fn(A.ADD_TAGS)&&(Q===Tt&&(Q=vo(Q)),Nt(Q,A.ADD_TAGS,je))),Co(A,"ADD_ATTR")&&(typeof A.ADD_ATTR=="function"?K.attributeCheck=A.ADD_ATTR:Fn(A.ADD_ATTR)&&(Ye===De&&(Ye=vo(Ye)),Nt(Ye,A.ADD_ATTR,je))),Co(A,"ADD_URI_SAFE_ATTR")&&Fn(A.ADD_URI_SAFE_ATTR)&&Nt(ct,A.ADD_URI_SAFE_ATTR,je),Co(A,"FORBID_CONTENTS")&&Fn(A.FORBID_CONTENTS)&&(Dt===or&&(Dt=vo(Dt)),Nt(Dt,A.FORBID_CONTENTS,je)),Co(A,"ADD_FORBID_CONTENTS")&&Fn(A.ADD_FORBID_CONTENTS)&&(Dt===or&&(Dt=vo(Dt)),Nt(Dt,A.ADD_FORBID_CONTENTS,je)),ze&&(Q["#text"]=!0),Rt&&Nt(Q,["html","head","body"]),Q.table&&(Nt(Q,["tbody"]),delete nt.tbody),A.TRUSTED_TYPES_POLICY){if(typeof A.TRUSTED_TYPES_POLICY.createHTML!="function")throw ma('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof A.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ma('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let ue=v;v=A.TRUSTED_TYPES_POLICY;try{E=j("")}catch($){throw v=ue,$}}else A.TRUSTED_TYPES_POLICY===null?(v=void 0,E=""):(v===void 0&&(v=ve()),v&&typeof E=="string"&&(E=j("")));(Z.uponSanitizeElement.length>0||Z.uponSanitizeAttribute.length>0)&&Q===Tt&&(Q=vo(Q)),Z.uponSanitizeAttribute.length>0&&Ye===De&&(Ye=vo(Ye)),Kr&&Kr(A),Tr=A},At=Nt({},[...Sd,...Td,...h0]),rn=Nt({},[...Md,...x0]),No=function(A,_,ue){return _.namespaceURI===Ft?A==="svg":_.namespaceURI===de?A==="svg"&&(ue==="annotation-xml"||tt[ue]):!!At[A]},mn=function(A,_,ue){return _.namespaceURI===Ft?A==="math":_.namespaceURI===rt?A==="math"&&cr[ue]:!!rn[A]},Jr=function(A,_,ue){return _.namespaceURI===rt&&!cr[ue]||_.namespaceURI===de&&!tt[ue]?!1:!rn[A]&&(Dr[A]||!At[A])},Ln=function(A){let _=M(A);(!_||!_.tagName)&&(_={namespaceURI:zt,tagName:"template"});let ue=qs(A.tagName),$=qs(_.tagName);return vr[A.namespaceURI]?A.namespaceURI===rt?No(ue,_,$):A.namespaceURI===de?mn(ue,_,$):A.namespaceURI===Ft?Jr(ue,_,$):!!(hr==="application/xhtml+xml"&&vr[A.namespaceURI]):!1},$r=function(A){$a(e.removed,{element:A});try{M(A).removeChild(A)}catch{if(y(A),!M(A))throw ma("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Fo=function(A){let _=T(A);if(_){let $=[];Ns(_,at=>{$a($,at)}),Ns($,at=>{try{y(at)}catch{}})}let ue=L(A);if(ue)for(let $=ue.length-1;$>=0;--$){let at=ue[$],ut=at&&at.name;if(typeof ut=="string")try{A.removeAttribute(ut)}catch{}}},mt=function(A,_){try{$a(e.removed,{attribute:_.getAttributeNode(A),from:_})}catch{$a(e.removed,{attribute:null,from:_})}if(_.removeAttribute(A),A==="is")if(zr||O)try{$r(_)}catch{}else try{_.setAttribute(A,"")}catch{}},co=function(A){let _=L(A);if(_)for(let ue=_.length-1;ue>=0;--ue){let $=_[ue],at=$&&$.name;if(!(typeof at!="string"||Ye[je(at)]))try{A.removeAttribute(at)}catch{}}},po=function(A){let _=[A];for(;_.length>0;){let ue=_.pop();(x?x(ue):ue.nodeType)===cn.element&&co(ue);let at=T(ue);if(at)for(let ut=at.length-1;ut>=0;--ut)_.push(at[ut])}},Or=function(A){let _=null,ue=null;if(Yr)A="<remove></remove>"+A;else{let ut=xh(A,/^[\r\n\t ]+/);ue=ut&&ut[0]}hr==="application/xhtml+xml"&&zt===Ft&&(A='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+A+"</body></html>");let $=v?j(A):A;if(zt===Ft)try{_=new u().parseFromString($,hr)}catch{}if(!_||!_.documentElement){_=Ae.createDocument(zt,"template",null);try{_.documentElement.innerHTML=Pr?E:$}catch{}}let at=_.body||_.documentElement;return A&&ue&&at.insertBefore(t.createTextNode(ue),at.childNodes[0]||null),zt===Ft?Ue.call(_,Rt?"html":"body")[0]:Rt?_.documentElement:at},Wt=function(A){return We.call(A.ownerDocument||A,A,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Vr=function(A){return A=Fs(A,ne," "),A=Fs(A,me," "),A=Fs(A,be," "),A},Zr=function(A){var _;A.normalize();let ue=We.call(A.ownerDocument||A,A,d.SHOW_TEXT|d.SHOW_COMMENT|d.SHOW_CDATA_SECTION|d.SHOW_PROCESSING_INSTRUCTION,null),$=ue.nextNode();for(;$;)$.data=Vr($.data),$=ue.nextNode();let at=(_=A.querySelectorAll)===null||_===void 0?void 0:_.call(A,"template");at&&Ns(at,ut=>{uo(ut.content)&&Zr(ut.content)})},_r=function(A){let _=w?w(A):null;return typeof _!="string"||je(_)!=="form"?!1:typeof A.nodeName!="string"||typeof A.textContent!="string"||typeof A.removeChild!="function"||A.attributes!==L(A)||typeof A.removeAttribute!="function"||typeof A.setAttribute!="function"||typeof A.namespaceURI!="string"||typeof A.insertBefore!="function"||typeof A.hasChildNodes!="function"||A.nodeType!==x(A)||A.childNodes!==T(A)},uo=function(A){if(!x||typeof A!="object"||A===null)return!1;try{return x(A)===cn.documentFragment}catch{return!1}},fo=function(A){if(!x||typeof A!="object"||A===null)return!1;try{return typeof x(A)=="number"}catch{return!1}};function Nr(re,A,_){re.length!==0&&Ns(re,ue=>{ue.call(e,A,_,Tr)})}let mo=function(A,_){return!!(Ar&&A.hasChildNodes()&&!fo(A.firstElementChild)&&Gr(Mh,A.textContent)&&Gr(Mh,A.innerHTML)||Ar&&A.namespaceURI===Ft&&_==="style"&&fo(A.firstElementChild)||A.nodeType===cn.processingInstruction||Ar&&A.nodeType===cn.comment&&Gr(k0,A.data))},$t=function(A,_){if(!nt[_]&&Uo(_)&&(le.tagNameCheck instanceof RegExp&&Gr(le.tagNameCheck,_)||le.tagNameCheck instanceof Function&&le.tagNameCheck(_)))return!1;if(ze&&!Dt[_]){let ue=M(A),$=T(A);if($&&ue){let at=$.length;for(let ut=at-1;ut>=0;--ut){let U=lt?$[ut]:m($[ut],!0);ue.insertBefore(U,h(A))}}}return $r(A),!0},Fr=function(A){if(Nr(Z.beforeSanitizeElements,A,null),_r(A))return $r(A),!0;let _=je(w?w(A):A.nodeName);if(Nr(Z.uponSanitizeElement,A,{tagName:_,allowedTags:Q}),mo(A,_))return $r(A),!0;if(nt[_]||!(K.tagCheck instanceof Function&&K.tagCheck(_))&&!Q[_])return $t(A,_);if((x?x(A):A.nodeType)===cn.element&&!Ln(A)||(_==="noscript"||_==="noembed"||_==="noframes")&&Gr(E0,A.innerHTML))return $r(A),!0;if(_e&&A.nodeType===cn.text){let $=Vr(A.textContent);A.textContent!==$&&($a(e.removed,{element:A.cloneNode()}),A.textContent=$)}return Nr(Z.afterSanitizeElements,A,null),!1},go=function(A,_,ue){if(Re[_]||Ie&&(_==="id"||_==="name")&&(ue in t||ue in io))return!1;let $=Ye[_]||K.attributeCheck instanceof Function&&K.attributeCheck(_,A);if(!(it&&Gr(ye,_))){if(!(he&&Gr(Y,_))){if($){if(!ct[_]){if(!Gr(ae,Fs(ue,Oe,""))){if(!((_==="src"||_==="xlink:href"||_==="href")&&A!=="script"&&yh(ue,"data:")===0&&X[A])){if(!(Pt&&!Gr(ge,Fs(ue,Oe,"")))){if(ue)return!1}}}}}else if(!(Uo(A)&&(le.tagNameCheck instanceof RegExp&&Gr(le.tagNameCheck,A)||le.tagNameCheck instanceof Function&&le.tagNameCheck(A))&&(le.attributeNameCheck instanceof RegExp&&Gr(le.attributeNameCheck,_)||le.attributeNameCheck instanceof Function&&le.attributeNameCheck(_,A))||_==="is"&&le.allowCustomizedBuiltInElements&&(le.tagNameCheck instanceof RegExp&&Gr(le.tagNameCheck,ue)||le.tagNameCheck instanceof Function&&le.tagNameCheck(ue))))return!1}}return!0},on=Nt({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Uo=function(A){return!on[qs(A)]&&Gr(ce,A)},nn=function(A,_,ue,$){if(v&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!ue)switch(f.getAttributeType(A,_)){case"TrustedHTML":return j($);case"TrustedScriptURL":return ie($)}return $},qo=function(A,_,ue,$){try{ue?A.setAttributeNS(ue,_,$):A.setAttribute(_,$),_r(A)?$r(A):hh(e.removed)}catch{mt(_,A)}},eo=function(A){Nr(Z.beforeSanitizeAttributes,A,null);let _=A.attributes;if(!_||_r(A))return;let ue={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ye,forceKeepAttr:void 0},$=_.length,at=je(A.nodeName);for(;$--;){let ut=_[$],U=ut.name,nr=ut.namespaceURI,mr=ut.value,Cr=je(U),ko=mr,sr=U==="value"?ko:d0(ko);if(ue.attrName=Cr,ue.attrValue=sr,ue.keepAttr=!0,ue.forceKeepAttr=void 0,Nr(Z.uponSanitizeAttribute,A,ue),sr=ue.attrValue,Je&&(Cr==="id"||Cr==="name")&&yh(sr,qe)!==0&&(mt(U,A),sr=qe+sr),Ar&&Gr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,sr)){mt(U,A);continue}if(Cr==="attributename"&&xh(sr,"href")){mt(U,A);continue}if(!ue.forceKeepAttr){if(!ue.keepAttr){mt(U,A);continue}if(!te&&Gr(L0,sr)){mt(U,A);continue}if(_e&&(sr=Vr(sr)),!go(at,Cr,sr)){mt(U,A);continue}sr=nn(at,Cr,nr,sr),sr!==ko&&qo(A,U,nr,sr)}}Nr(Z.afterSanitizeAttributes,A,null)},to=function(A){let _=null,ue=Wt(A);for(Nr(Z.beforeSanitizeShadowDOM,A,null);_=ue.nextNode();)if(Nr(Z.uponSanitizeShadowNode,_,null),Fr(_),eo(_),uo(_.content)&&to(_.content),(x?x(_):_.nodeType)===cn.element){let at=k(_);uo(at)&&(gt(at),to(at))}Nr(Z.afterSanitizeShadowDOM,A,null)},gt=function(A){let _=[{node:A,shadow:null}];for(;_.length>0;){let ue=_.pop();if(ue.shadow){to(ue.shadow);continue}let $=ue.node,ut=(x?x($):$.nodeType)===cn.element,U=T($);if(U)for(let nr=U.length-1;nr>=0;--nr)_.push({node:U[nr],shadow:null});if(ut){let nr=w?w($):null;if(typeof nr=="string"&&je(nr)==="template"){let mr=$.content;uo(mr)&&_.push({node:mr,shadow:null})}}if(ut){let nr=k($);uo(nr)&&_.push({node:null,shadow:nr},{node:nr,shadow:null})}}};return e.sanitize=function(re){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},_=null,ue=null,$=null,at=null;if(Pr=!re,Pr&&(re="<!-->"),typeof re!="string"&&!fo(re)&&(re=m0(re),typeof re!="string"))throw ma("dirty is not a string, aborting");if(!e.isSupported)return re;dr||lo(A),e.removed=[];let ut=lt&&typeof re!="string"&&fo(re);if(ut){let mr=w?w(re):re.nodeName;if(typeof mr=="string"){let Cr=je(mr);if(!Q[Cr]||nt[Cr])throw ma("root node is forbidden and cannot be sanitized in-place")}if(_r(re))throw ma("root node is clobbered and cannot be sanitized in-place");try{gt(re)}catch(Cr){throw Fo(re),Cr}}else if(fo(re))_=Or("<!---->"),ue=_.ownerDocument.importNode(re,!0),ue.nodeType===cn.element&&ue.nodeName==="BODY"||ue.nodeName==="HTML"?_=ue:_.appendChild(ue),gt(ue);else{if(!zr&&!_e&&!Rt&&re.indexOf("<")===-1)return v&&fe?j(re):re;if(_=Or(re),!_)return zr?null:fe?E:""}_&&Yr&&$r(_.firstChild);let U=Wt(ut?re:_);try{for(;$=U.nextNode();)Fr($),eo($),uo($.content)&&to($.content)}catch(mr){throw ut&&Fo(re),mr}if(ut)return Ns(e.removed,mr=>{mr.element&&po(mr.element)}),_e&&Zr(re),re;if(zr){if(_e&&Zr(_),O)for(at=Me.call(_.ownerDocument);_.firstChild;)at.appendChild(_.firstChild);else at=_;return(Ye.shadowroot||Ye.shadowrootmode)&&(at=Be.call(o,at,!0)),at}let nr=Rt?_.outerHTML:_.innerHTML;return Rt&&Q["!doctype"]&&_.ownerDocument&&_.ownerDocument.doctype&&_.ownerDocument.doctype.name&&Gr(T0,_.ownerDocument.doctype.name)&&(nr="<!DOCTYPE "+_.ownerDocument.doctype.name+`>
|
|
49
|
-
`+nr),_e&&(nr=Vr(nr)),v&&fe?j(nr):nr},e.setConfig=function(){let re=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};lo(re),dr=!0},e.clearConfig=function(){Tr=null,dr=!1,v=H,E=""},e.isValidAttribute=function(re,A,_){Tr||lo({});let ue=je(re),$=je(A);return go(ue,$,_)},e.addHook=function(re,A){typeof A=="function"&&$a(Z[re],A)},e.removeHook=function(re,A){if(A!==void 0){let _=i0(Z[re],A);return _===-1?void 0:l0(Z[re],_,1)[0]}return hh(Z[re])},e.removeHooks=function(re){Z[re]=[]},e.removeAllHooks=function(){Z=kh()},e}var Rh=Ph();var I0={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"]},H0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pd=()=>{let r=Rh(typeof window!="undefined"?window:void 0);return r.addHook("uponSanitizeAttribute",(e,t)=>{if(t.attrName==="src"||t.attrName==="href"){let o=t.attrValue;o.toLowerCase().startsWith("data:")&&!H0.test(o)&&(t.attrValue="",t.keepAttr=!1)}}),e=>r.sanitize(e,I0)},ja=r=>r===!1?null:typeof r=="function"?r:Pd();var Cn="webmcp:",Rd=new Map,Ih=r=>{var e;Rd.clear();for(let t of r){let o=(e=t.title)==null?void 0:e.trim();o&&Rd.set(t.name,o)}},Hd=r=>Rd.get(zi(r)),qi={warn(r,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${r}`,...e)}},Id=null,Wh=r=>{Id=r};function Bh(r){if(r.length===0)return"0:empty";let e=r.map(t=>{var o,n;return[t.name,(o=t.description)!=null?o:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(n=t.origin)!=null?n:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${r.length}:${W0(e.join(""))}`}function Hh(r,e){let t=3735928559^e,o=1103547991^e;for(let n=0;n<r.length;n++){let a=r.charCodeAt(n);t=Math.imul(t^a,2654435761),o=Math.imul(o^a,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&o)+(t>>>0)}function W0(r){let e=Hh(r,0).toString(36),t=Hh(r,2654435761).toString(36);return`${e}.${t}`}var Ga=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let t;try{t=await e.getTools()}catch(n){return qi.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",n),[]}Ih(t);let o=typeof location!="undefined"?location.origin:"";return t.filter(n=>this.passesClientAllowlist(n.name)).map(n=>{let a={name:n.name,description:n.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=D0(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(e,t,o){if(await this.ensureReady(),this.config.enabled!==!0)return Zo("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let y=typeof document!="undefined"&&!!document.modelContext;return Zo(y?"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 a=zi(e),s;try{s=await n.getTools()}catch(y){let h=y instanceof Error?y.message:String(y);return Zo(`Failed to read WebMCP registry: ${h}`)}Ih(s);let i=s.find(y=>y.name===a);if(!i)return Zo(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Zo(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return Zo("Aborted by cancel()");let d=Hd(a),l={toolName:a,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Zo("User declined the tool call.");if(o!=null&&o.aborted)return Zo("Aborted by cancel()");let u=new AbortController,f=!1,p=setTimeout(()=>{f=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let y=await n.executeTool(i,F0(t),{signal:u.signal});return O0(y)}catch(y){if(f)return Zo(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Zo("Aborted by cancel()");let h=y instanceof Error?y.message:String(y);return Zo(h)}finally{clearTimeout(p),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Id?await Id():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){qi.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,qi.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):e}async requestConfirm(e){var o;let t=(o=this.confirmHandler)!=null?o:_0;try{return await t(e)}catch(n){return qi.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,n),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(o=>B0(e,o))}},zi=r=>r.startsWith(Cn)?r.slice(Cn.length):r,ga=r=>r.startsWith(Cn),B0=(r,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(r)},D0=r=>{if(!(r===void 0||r===""))try{let e=JSON.parse(r);return e!==null&&typeof e=="object"?e:void 0}catch{return}},O0=r=>{if(r==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(r)}catch{return{content:[{type:"text",text:r}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:U0(e)}]}},Zo=r=>({isError:!0,content:[{type:"text",text:r}]}),_0=async r=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=N0(r.args),t=`Allow the AI to call ${r.toolName}`+(e?`
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var Xx=Object.create;var fi=Object.defineProperty;var Qx=Object.getOwnPropertyDescriptor;var Jx=Object.getOwnPropertyNames;var Yx=Object.getPrototypeOf,Zx=Object.prototype.hasOwnProperty;var Ol=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,r)=>(typeof require!="undefined"?require:t)[r]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var dg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ey=(e,t)=>{for(var r in t)fi(e,r,{get:t[r],enumerable:!0})},cg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jx(t))!Zx.call(e,n)&&n!==r&&fi(e,n,{get:()=>t[n],enumerable:!(o=Qx(t,n))||o.enumerable});return e};var Pa=(e,t,r)=>(r=e!=null?Xx(Yx(e)):{},cg(t||!e||!e.__esModule?fi(r,"default",{value:e,enumerable:!0}):r,e)),ty=e=>cg(fi({},"__esModule",{value:!0}),e);var jl=dg(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.Allow=Fe.ALL=Fe.COLLECTION=Fe.ATOM=Fe.SPECIAL=Fe.INF=Fe._INFINITY=Fe.INFINITY=Fe.NAN=Fe.BOOL=Fe.NULL=Fe.OBJ=Fe.ARR=Fe.NUM=Fe.STR=void 0;Fe.STR=1;Fe.NUM=2;Fe.ARR=4;Fe.OBJ=8;Fe.NULL=16;Fe.BOOL=32;Fe.NAN=64;Fe.INFINITY=128;Fe._INFINITY=256;Fe.INF=Fe.INFINITY|Fe._INFINITY;Fe.SPECIAL=Fe.NULL|Fe.BOOL|Fe.INF|Fe.NAN;Fe.ATOM=Fe.STR|Fe.NUM|Fe.SPECIAL;Fe.COLLECTION=Fe.ARR|Fe.OBJ;Fe.ALL=Fe.ATOM|Fe.COLLECTION;Fe.Allow={STR:Fe.STR,NUM:Fe.NUM,ARR:Fe.ARR,OBJ:Fe.OBJ,NULL:Fe.NULL,BOOL:Fe.BOOL,NAN:Fe.NAN,INFINITY:Fe.INFINITY,_INFINITY:Fe._INFINITY,INF:Fe.INF,SPECIAL:Fe.SPECIAL,ATOM:Fe.ATOM,COLLECTION:Fe.COLLECTION,ALL:Fe.ALL};Fe.default=Fe.Allow});var bi=dg(Ar=>{"use strict";var my=Ar&&Ar.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),gy=Ar&&Ar.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&my(t,e,r)};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.Allow=Ar.MalformedJSON=Ar.PartialJSON=Ar.parseJSON=Ar.parse=void 0;var Or=jl();Object.defineProperty(Ar,"Allow",{enumerable:!0,get:function(){return Or.Allow}});gy(jl(),Ar);var xi=class extends Error{};Ar.PartialJSON=xi;var yi=class extends Error{};Ar.MalformedJSON=yi;function Cg(e,t=Or.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return hy(e.trim(),t)}Ar.parseJSON=Cg;var hy=(e,t)=>{let r=e.length,o=0,n=p=>{throw new xi(`${p} at position ${o}`)},a=p=>{throw new yi(`${p} at position ${o}`)},s=()=>(g(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?d():e.substring(o,o+4)==="null"||Or.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Or.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Or.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Or.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Or.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Or.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):u()),i=()=>{let p=o,m=!1;for(o++;o<r&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(p,++o-Number(m)))}catch(x){a(String(x))}else if(Or.Allow.STR&t)try{return JSON.parse(e.substring(p,o-Number(m))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,g();let p={};try{for(;e[o]!=="}";){if(g(),o>=r&&Or.Allow.OBJ&t)return p;let m=i();g(),o++;try{let x=s();p[m]=x}catch(x){if(Or.Allow.OBJ&t)return p;throw x}g(),e[o]===","&&o++}}catch{if(Or.Allow.OBJ&t)return p;n("Expected '}' at end of object")}return o++,p},d=()=>{o++;let p=[];try{for(;e[o]!=="]";)p.push(s()),g(),e[o]===","&&o++}catch{if(Or.Allow.ARR&t)return p;n("Expected ']' at end of array")}return o++,p},u=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Or.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let p=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Or.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(p,o))}catch{e.substring(p,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(x){a(String(x))}}},g=()=>{for(;o<r&&`
|
|
2
|
+
\r `.includes(e[o]);)o++};return s()},xy=Cg;Ar.parse=xy});var E0={};ey(E0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>rd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>td,ASK_USER_QUESTION_TOOL_NAME:()=>ws,AgentWidgetClient:()=>na,AgentWidgetSession:()=>Ua,AttachmentManager:()=>la,BrowserSpeechEngine:()=>In,DEFAULT_COMPONENTS:()=>ap,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Qi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>oo,DEFAULT_PALETTE:()=>op,DEFAULT_SEMANTIC:()=>np,DEFAULT_WIDGET_CONFIG:()=>_t,PRESETS:()=>jp,PRESET_FULLSCREEN:()=>zp,PRESET_MINIMAL:()=>$p,PRESET_SHOP:()=>Vp,ReadAloudController:()=>ia,SUGGEST_REPLIES_CLIENT_TOOL:()=>Si,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Yl,SUGGEST_REPLIES_TOOL_NAME:()=>Mo,THEME_ZONES:()=>lh,VERSION:()=>oa,WEBMCP_TOOL_PREFIX:()=>tn,WebMcpBridge:()=>Ha,accessibilityPlugin:()=>Ax,animationsPlugin:()=>Mx,applyThemeVariables:()=>Wn,attachHeaderToContainer:()=>pa,brandPlugin:()=>Tx,buildComposer:()=>ja,buildDefaultHeader:()=>gp,buildHeader:()=>ln,buildHeaderWithLayout:()=>za,buildMinimalHeader:()=>hp,builtInClientToolsForDispatch:()=>Ms,collectEnrichedPageContext:()=>wx,componentRegistry:()=>dn,createActionManager:()=>Gs,createAgentExperience:()=>Il,createAskUserQuestionBubble:()=>Hg,createBestAvailableVoiceProvider:()=>Ni,createBubbleWithLayout:()=>Rh,createCSATFeedback:()=>Ll,createComboButton:()=>pl,createComponentMiddleware:()=>tx,createComponentStreamParser:()=>Ml,createDefaultSanitizer:()=>ql,createDirectivePostprocessor:()=>gg,createDropdownMenu:()=>Fn,createFlexibleJsonStreamParser:()=>Ng,createIconButton:()=>yr,createImagePart:()=>jg,createJsonStreamParser:()=>Ri,createLabelButton:()=>Us,createLocalStorageAdapter:()=>Al,createMarkdownProcessor:()=>bs,createMarkdownProcessorFromConfig:()=>Zn,createMessageActions:()=>Sp,createNPSFeedback:()=>Pl,createPlainTextParser:()=>Li,createPlugin:()=>Lx,createRegexJsonParser:()=>Pi,createStandardBubble:()=>Ga,createTextPart:()=>ks,createTheme:()=>Va,createThemeObserver:()=>el,createToggleGroup:()=>Sh,createTypingIndicator:()=>ua,createVoiceProvider:()=>Rn,createWidgetHostLayout:()=>Ks,createXmlParser:()=>Ii,defaultActionHandlers:()=>ma,defaultJsonActionParser:()=>js,defaultParseRules:()=>Up,detectColorScheme:()=>Ws,directivePostprocessor:()=>hg,ensureAskUserQuestionSheet:()=>Fa,escapeHtml:()=>qo,extractComponentDirectiveFromMessage:()=>kl,fileToImagePart:()=>Gg,formatEnrichedContext:()=>Sx,generateAssistantMessageId:()=>aa,generateMessageId:()=>Ug,generateStableSelector:()=>qp,generateUserMessageId:()=>Oa,getActiveTheme:()=>$a,getColorScheme:()=>ip,getDisplayText:()=>Vg,getHeaderLayout:()=>xp,getImageParts:()=>zg,getPreset:()=>Rx,hasComponentDirective:()=>El,hasImages:()=>$g,headerLayouts:()=>ul,highContrastPlugin:()=>kx,initAgentWidget:()=>px,isAskUserQuestionMessage:()=>rn,isComponentDirectiveType:()=>ex,isDockedMountMode:()=>pr,isSuggestRepliesMessage:()=>As,isVoiceSupported:()=>Ps,isWebMcpToolName:()=>ea,latestAgentSuggestions:()=>Ai,listRegisteredStreamAnimations:()=>pp,markdownPostprocessor:()=>Ul,mergeWithDefaults:()=>Ji,normalizeContent:()=>qg,parseAskUserQuestionPayload:()=>on,parseSuggestRepliesPayload:()=>ed,pickBestVoice:()=>_a,pluginRegistry:()=>zs,reducedMotionPlugin:()=>Ex,registerStreamAnimationPlugin:()=>ca,removeAskUserQuestionSheet:()=>Ln,renderComponentDirective:()=>Tl,renderLoadingIndicatorWithFallback:()=>wp,renderLucideIcon:()=>ve,resolveDockConfig:()=>no,resolveSanitizer:()=>Wa,resolveTokens:()=>Yi,stripWebMcpPrefix:()=>hi,themeToCssVariables:()=>Zi,unregisterStreamAnimationPlugin:()=>cp,validateImageFile:()=>Kg,validateTheme:()=>sp});var _l=null,ys=null,Ra=null,pg=e=>{_l=e};var mi=()=>ys?Promise.resolve(ys):Ra||(_l?(Ra=_l().then(e=>(ys=e,e)),Ra):(Ra=import("./markdown-parsers-entry").then(e=>(ys=e,e)),Ra)),Ia=()=>ys;var ry=e=>{if(e)return e},bs=e=>{let t=null;return r=>{var n,a;let o=Ia();if(!o)return qo(r);if(!t){let{Marked:s}=o,i=e==null?void 0:e.markedOptions;t=new s({gfm:(n=i==null?void 0:i.gfm)!=null?n:!0,breaks:(a=i==null?void 0:i.breaks)!=null?a:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let c=ry(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},Zn=e=>e?bs({markedOptions:e.options,renderer:e.renderer}):bs(),oy=bs(),Ul=e=>oy(e),qo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),fg=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),ug=e=>`%%FORM_PLACEHOLDER_${e}%%`,mg=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,n)=>{try{let a=JSON.parse(n.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=ug(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,n)=>{let a=ug(t.length);return t.push({token:a,type:n}),a}),r},gg=e=>{let t=Zn(e);return r=>{let o=[],n=mg(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${fg(i)}"></div>`;a=a.replace(c,u)}),a}},hg=e=>{let t=[],r=mg(e,t),o=Ul(r);return t.forEach(({token:n,type:a})=>{let s=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${fg(a)}"></div>`;o=o.replace(s,c)}),o};var ny={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"]},ay=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ql=()=>{let e=null;return t=>{let r=Ia();if(!r)return qo(t);if(!e){let{DOMPurify:o}=r;e=o(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(n,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!ay.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,ny)}},Wa=e=>e===!1?null:typeof e=="function"?e:ql();var tn="webmcp:",Vl=new Map,xg=e=>{var t;Vl.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&Vl.set(r.name,o)}},zl=e=>Vl.get(hi(e)),gi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$l=null,bg=e=>{$l=e};function vg(e){if(e.length===0)return"0:empty";let t=e.map(r=>{var o,n;return[r.name,(o=r.description)!=null?o:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(n=r.origin)!=null?n:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${e.length}:${sy(t.join(""))}`}function yg(e,t){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let a=e.charCodeAt(n);r=Math.imul(r^a,2654435761),o=Math.imul(o^a,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)}function sy(e){let t=yg(e,0).toString(36),r=yg(e,2654435761).toString(36);return`${t}.${r}`}var Ha=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=t.onConfirm)!=null?r: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 r;try{r=await t.getTools()}catch(n){return gi.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}xg(r);let o=typeof location!="undefined"?location.origin:"";return r.filter(n=>this.passesClientAllowlist(n.name)).map(n=>{let a={name:n.name,description:n.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=ly(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return Ao(x?"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 a=hi(t),s;try{s=await n.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return Ao(`Failed to read WebMCP registry: ${C}`)}xg(s);let i=s.find(x=>x.name===a);if(!i)return Ao(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Ao(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let c=zl(a),d={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(d))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let u=new AbortController,g=!1,p=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await n.executeTool(i,uy(r),{signal:u.signal});return dy(x)}catch(x){if(g)return Ao(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return Ao(C)}finally{clearTimeout(p),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}($l?await $l():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){gi.warn("Failed to load @mcp-b/webmcp-polyfill: 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 r=t;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,gi.warn("document.modelContext is present but does not expose getTools()/executeTool(): 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 o;let r=(o=this.confirmHandler)!=null?o:cy;try{return await r(t)}catch(n){return gi.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,n),!1}}passesClientAllowlist(t){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(o=>iy(t,o))}},hi=e=>e.startsWith(tn)?e.slice(tn.length):e,ea=e=>e.startsWith(tn),iy=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},ly=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},dy=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:fy(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),cy=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=py(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
|
|
50
3
|
|
|
51
4
|
Arguments:
|
|
52
|
-
${
|
|
5
|
+
${t}`:"")+(e.description?`
|
|
53
6
|
|
|
54
|
-
${r.description}`:"");return window.confirm(t)},N0=r=>{if(r==null)return"";try{let e=JSON.stringify(r,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(r)}},F0=r=>{if(r===void 0)return"{}";try{let e=JSON.stringify(r);return e===void 0?"{}":e}catch{return"{}"}},U0=r=>{if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}};var Un=Bi(ji(),1);var C=(r,e)=>{let t=document.createElement(r);return e&&(t.className=e),t},un=(r,e,t)=>{let o=r.createElement(e);return t&&(o.className=t),o};var $s="ask_user_question",zs=8,Ka="data-persona-ask-sheet-for",j0="Other",G0="Other\u2026",_h="Type your own answer here",Nh="Send",K0="Next",X0="Back",Q0="Submit all",Y0="Skip",J0=3,Bd="data-ask-current-index",Dd="data-ask-question-count",Fh="data-ask-answers",Od="data-ask-grouped",Uh="data-ask-layout",Z0=r=>r.layout==="pills"?"pills":"rows",ev=r=>r.getAttribute(Uh)==="pills"?"pills":"rows",Oh=!1,qh=r=>r.replace(/["\\]/g,"\\$&"),wn=r=>r.variant==="tool"&&!!r.toolCall&&r.toolCall.name===$s,Gi=r=>{var e,t;return(t=(e=r==null?void 0:r.features)==null?void 0:e.askUserQuestion)!=null?t:{}},An=r=>{let e=r.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:t};try{let n=o.join(""),a=(0,Un.parse)(n,Un.STR|Un.OBJ|Un.ARR);if(a&&typeof a=="object")return{payload:a,complete:t}}catch{}return{payload:null,complete:t}},Vs=r=>{let e=Array.isArray(r==null?void 0:r.questions)?r.questions:[];return e.length>zs&&!Oh&&(Oh=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${zs}.`)),e.slice(0,zs)},tv=r=>{var e;return(e=Vs(r)[0])!=null?e:null},rv=(r,e)=>{var t;return(t=Vs(r)[e])!=null?t:null},zh=(r,e)=>{let t=e.styles;t&&(t.sheetBackground&&r.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&r.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&r.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&r.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&r.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&r.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&r.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&r.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&r.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},$h=(r,e,t)=>{if(r!=="rows")return null;let o=C("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let n=C("span","persona-ask-row-check");o.appendChild(n)}else{let n=C("span","persona-ask-row-badge");n.textContent=String(t+1),o.appendChild(n)}return o},ov=(r,e,t,o)=>{let a=C("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(e)),a.setAttribute("data-option-label",r.label),t==="rows"){let s=C("span","persona-ask-row-content"),i=C("span","persona-ask-row-label");if(i.textContent=r.label,s.appendChild(i),r.description){let l=C("span","persona-ask-row-description");l.textContent=r.description,s.appendChild(l)}a.appendChild(s);let d=$h(t,o,e);d&&a.appendChild(d)}else a.textContent=r.label,r.description&&(a.title=r.description);return a},nv=r=>{let t=C("span",r==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},av=(r,e,t,o)=>{var u,f,p;let a=C("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(r!=null&&r.multiSelect),d=(Array.isArray(r==null?void 0:r.options)?r.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<J0;m++)a.appendChild(nv(o));return a}if(d.forEach((m,y)=>{a.appendChild(ov(m,y,o,s))}),(r==null?void 0:r.allowFreeText)!==!1){let m=o==="rows"?j0:G0;if(o==="rows"){let y=C("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let h=C("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=e.freeTextPlaceholder)!=null?u:_h,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),h.appendChild(T),y.appendChild(h);let M=$h(o,s,d.length);M&&y.appendChild(M),a.appendChild(y)}else{let y=C("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(p=e.freeTextLabel)!=null?p:m,a.appendChild(y)}}return a},Vh=(r,e)=>{var a,s;let o=C("div",e==="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");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=r.freeTextPlaceholder)!=null?a:_h,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),e!=="rows"){let i=C("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=r.submitLabel)!=null?s:Nh,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},sv=r=>{var o;let e=C("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=C("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(o=r.submitLabel)!=null?o:Nh,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},iv=(r,e,t)=>{var l,u,f,p;let o=C("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=C("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(l=t.backLabel)!=null?l:X0,n.setAttribute("data-ask-user-action","back"),n.disabled=r===0,o.appendChild(n);let a=C("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=C("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=t.skipLabel)!=null?u:Y0,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=C("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=r===e-1;return i.textContent=d?(f=t.submitAllLabel)!=null?f:Q0:(p=t.nextLabel)!=null?p:K0,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},ha=r=>{let e=r.getAttribute(Fh);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},jh=(r,e)=>{r.setAttribute(Fh,JSON.stringify(e))},jo=r=>{var t;let e=Number((t=r.getAttribute(Bd))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},lv=(r,e)=>{r.setAttribute(Bd,String(Math.max(0,Math.floor(e))))},Xa=r=>{var t;let e=Number((t=r.getAttribute(Dd))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},qn=r=>r.getAttribute(Od)==="true",dv=(r,e)=>{var n;let t=(n=r.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let o={};return e.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(o[s]=d)}}),o},cv=(r,e)=>{var o;let t=(o=r.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},Ki=(r,e)=>{let{payload:t}=An(e),o=Vs(t),n=ha(r),a={},s=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(n,d)&&(a[l]=n[d]))}),a},Gh=r=>{let e=ha(r),t=jo(r),o=e[t],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(d=>n.add(d));let a=r.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(d=>{var f;let l=(f=d.getAttribute("data-option-label"))!=null?f:"",u=n.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=r.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Kh=r=>{if(!qn(r))return;let e=ha(r),t=jo(r),o=e[t],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=r.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=r.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},_d=(r,e,t)=>{let o=Gi(t),n=ev(r),{payload:a,complete:s}=An(e),i=qn(r),d=jo(r),l=Xa(r),u=i?rv(a,d):tv(a),f=!!(u!=null&&u.multiSelect),p=r.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${d+1}/${l}`:"");let m=r.querySelector('[data-ask-stepper="true"]');m&&m.remove();let y=r.querySelector('[data-ask-question="true"]');if(y){let k=typeof(u==null?void 0:u.question)=="string"?u.question:"";y.textContent=k,y.classList.toggle("persona-ask-question-skeleton",!k&&!s)}let h=r.querySelector('[data-ask-pill-list="true"]');if(h){let k=av(u,o,s,n);h.replaceWith(k)}if(n!=="rows"){let k=r.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Vh(o,n))}let T=r.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!T?r.appendChild(sv(o)):(!f||i)&&T&&T.remove(),r.setAttribute("data-multi-select",f?"true":"false");let M=r.querySelector('[data-ask-nav-row="true"]');if(i){let k=iv(d,l,o);M?M.replaceWith(k):r.appendChild(k)}else M&&M.remove();Gh(r),Kh(r)},pv=(r,e,t)=>{let o=Gi(e),n=Z0(o),a=r.toolCall.id,s=Vs(t),i=Math.max(1,s.length),d=i>1,l=dv(r,s),u=d?cv(r,i):0,f=C("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Ka,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",r.id),f.setAttribute(Dd,String(i)),f.setAttribute(Bd,String(u)),f.setAttribute(Od,d?"true":"false"),f.setAttribute(Uh,n),jh(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),zh(f,o);let p=C("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=C("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",p.appendChild(m);let y=C("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",p.appendChild(y),f.appendChild(p);let T=C("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),n!=="rows"&&f.appendChild(Vh(o,n)),_d(f,r,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},uv=(r,e,t)=>{let{payload:o}=An(e),n=Math.max(1,Vs(o).length);n>Xa(r)&&(r.setAttribute(Dd,String(n)),n>1&&!qn(r)&&r.setAttribute(Od,"true")),_d(r,e,t)},Xh=(r,e)=>{let t=C("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${r.id}`,t.setAttribute("data-message-id",r.id),t.setAttribute("data-bubble-type","ask-user-question");let o=Gi(e);zh(t,o);let n=C("span","persona-ask-stub-label"),{complete:a}=An(r);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(n),t},Qa=(r,e,t)=>{if(!t||!wn(r)||Gi(e).enabled===!1)return;let n=r.toolCall.id;t.querySelectorAll(`[${Ka}]`).forEach(l=>{l.getAttribute(Ka)!==n&&l.remove()});let s=t.querySelector(`[${Ka}="${qh(n)}"]`);if(s){uv(s,r,e);return}let{payload:i}=An(r),d=pv(r,e,i);t.appendChild(d)},zn=(r,e)=>{if(!r)return;let t=e?`[${Ka}="${qh(e)}"]`:`[${Ka}]`;r.querySelectorAll(t).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Nd=r=>Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),$n=(r,e)=>{let t=ha(r),o=jo(r);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[o]:t[o]=e,jh(r,t),Gh(r),Kh(r)},Xi=(r,e,t,o)=>{let n=Xa(r),a=Math.max(0,Math.min(n-1,o));lv(r,a),_d(r,e,t)};var en="suggest_replies";var Fd={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Qi={name:en,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown \u2014 do not add further commentary after calling this tool; end your turn.`,parametersSchema:Fd,origin:"sdk",annotations:{readOnlyHint:!0}},Ud=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),js=r=>{var e;return r.variant==="tool"&&((e=r.toolCall)==null?void 0:e.name)===en},qd=r=>{let e=r;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let o=t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Yi=r=>{var e;for(let t=r.length-1;t>=0;t--){let o=r[t];if(o.role==="user")return null;if(!js(o))continue;let n=qd((e=o.toolCall)==null?void 0:e.args);return n.length>0?n:null}return null},Qh=r=>{var t;let e=(t=r==null?void 0:r.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var zd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option \u2014 free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},$d={name:$s,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make \u2014 a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:zd,origin:"sdk",annotations:{readOnlyHint:!0}},Gs=r=>{var o;let e=[],t=(o=r==null?void 0:r.features)==null?void 0:o.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push($d),Qh(r)&&e.push(Qi),e};var Sn=Bi(ji(),1),Ji=r=>r.replace(/\\n/g,`
|
|
55
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
7
|
+
${e.description}`:"");return window.confirm(r)},py=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)}},uy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},fy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var En=Pa(bi(),1);var S=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Vo=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var kt=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},vs=(...e)=>e.filter(Boolean).join(" ");var ws="ask_user_question",Cs=8,Ba="data-persona-ask-sheet-for",yy="Other",by="Other\u2026",Sg="Type your own answer here",Ag="Send",vy="Next",Cy="Back",wy="Submit all",Sy="Skip",Ay=3,Gl="data-ask-current-index",Kl="data-ask-question-count",Mg="data-ask-answers",Xl="data-ask-grouped",Tg="data-ask-layout",My=e=>e.layout==="pills"?"pills":"rows",Ty=e=>e.getAttribute(Tg)==="pills"?"pills":"rows",wg=!1,Eg=e=>e.replace(/["\\]/g,"\\$&"),rn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ws,vi=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},on=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,En.parse)(n,En.STR|En.OBJ|En.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},Ss=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Cs&&!wg&&(wg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},Ey=e=>{var t;return(t=Ss(e)[0])!=null?t:null},ky=(e,t)=>{var r;return(r=Ss(e)[t])!=null?r:null},kg=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Lg=(e,t,r)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=S("span","persona-ask-row-check");o.appendChild(n)}else{let n=S("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Ly=(e,t,r,o)=>{let a=S("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=S("span","persona-ask-row-content"),i=S("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=S("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let c=Lg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Py=e=>{let r=S("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 r.setAttribute("aria-hidden","true"),r},Ry=(e,t,r,o)=>{var u,g,p;let a=S("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(c.length===0&&!r){for(let m=0;m<Ay;m++)a.appendChild(Py(o));return a}if(c.forEach((m,x)=>{a.appendChild(Ly(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?yy:by;if(o==="rows"){let x=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let C=S("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=t.freeTextPlaceholder)!=null?u:Sg,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),C.appendChild(T),x.appendChild(C);let E=Lg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(p=t.freeTextLabel)!=null?p:m,a.appendChild(x)}}return a},Pg=(e,t)=>{var a,s;let o=S("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");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:Sg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=S("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Ag,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Iy=e=>{var o;let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=S("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Ag,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Wy=(e,t,r)=>{var d,u,g,p;let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=S("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:Cy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=S("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=r.skipLabel)!=null?u:Sy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=S("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(g=r.submitAllLabel)!=null?g:wy:(p=r.nextLabel)!=null?p:vy,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},ta=e=>{let t=e.getAttribute(Mg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Rg=(e,t)=>{e.setAttribute(Mg,JSON.stringify(t))},ho=e=>{var r;let t=Number((r=e.getAttribute(Gl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Hy=(e,t)=>{e.setAttribute(Gl,String(Math.max(0,Math.floor(t))))},Da=e=>{var r;let t=Number((r=e.getAttribute(Kl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},kn=e=>e.getAttribute(Xl)==="true",By=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},Dy=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},Ci=(e,t)=>{let{payload:r}=on(t),o=Ss(r),n=ta(e),a={},s=new Set;return o.forEach((i,c)=>{let d=typeof(i==null?void 0:i.question)=="string"?i.question:"";d&&(s.has(d)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,c)&&(a[d]=n[c]))}),a},Ig=e=>{let t=ta(e),r=ho(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var g;let d=(g=c.getAttribute("data-option-label"))!=null?g:"",u=n.has(d);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.getAttribute("data-option-label"))!=null?d:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Wg=e=>{if(!kn(e))return;let t=ta(e),r=ho(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Ql=(e,t,r)=>{let o=vi(r),n=Ty(e),{payload:a,complete:s}=on(t),i=kn(e),c=ho(e),d=Da(e),u=i?ky(a,c):Ey(a),g=!!(u!=null&&u.multiSelect),p=e.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${c+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let M=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=M,x.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let M=Ry(u,o,s,n);C.replaceWith(M)}if(n!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Pg(o,n))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!T?e.appendChild(Iy(o)):(!g||i)&&T&&T.remove(),e.setAttribute("data-multi-select",g?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let M=Wy(c,d,o);E?E.replaceWith(M):e.appendChild(M)}else E&&E.remove();Ig(e),Wg(e)},Fy=(e,t,r)=>{let o=vi(t),n=My(o),a=e.toolCall.id,s=Ss(r),i=Math.max(1,s.length),c=i>1,d=By(e,s),u=c?Dy(e,i):0,g=S("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Ba,a),g.setAttribute("data-tool-call-id",a),g.setAttribute("data-message-id",e.id),g.setAttribute(Kl,String(i)),g.setAttribute(Gl,String(u)),g.setAttribute(Xl,c?"true":"false"),g.setAttribute(Tg,n),Rg(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),kg(g,o);let p=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=S("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",p.appendChild(m);let x=S("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",p.appendChild(x),g.appendChild(p);let T=S("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),n!=="rows"&&g.appendChild(Pg(o,n)),Ql(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Ny=(e,t,r)=>{let{payload:o}=on(t),n=Math.max(1,Ss(o).length);n>Da(e)&&(e.setAttribute(Kl,String(n)),n>1&&!kn(e)&&e.setAttribute(Xl,"true")),Ql(e,t,r)},Hg=(e,t)=>{let r=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=vi(t);kg(r,o);let n=S("span","persona-ask-stub-label"),{complete:a}=on(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Fa=(e,t,r)=>{if(!r||!rn(e)||vi(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ba}]`).forEach(d=>{d.getAttribute(Ba)!==n&&d.remove()});let s=r.querySelector(`[${Ba}="${Eg(n)}"]`);if(s){Ny(s,e,t);return}let{payload:i}=on(e),c=Fy(e,t,i);r.appendChild(c)},Ln=(e,t)=>{if(!e)return;let r=t?`[${Ba}="${Eg(t)}"]`:`[${Ba}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Jl=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),Pn=(e,t)=>{let r=ta(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Rg(e,r),Ig(e),Wg(e)},wi=(e,t,r,o)=>{let n=Da(e),a=Math.max(0,Math.min(n-1,o));Hy(e,a),Ql(e,t,r)};var Mo="suggest_replies";var Yl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Si={name:Mo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Yl,origin:"sdk",annotations:{readOnlyHint:!0}},Zl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),As=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Mo},ed=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Ai=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!As(o))continue;let n=ed((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Bg=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var td={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},rd={name:ws,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:td,origin:"sdk",annotations:{readOnlyHint:!0}},Ms=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(rd),Bg(e)&&t.push(Si),t};var nn=Pa(bi(),1),Mi=e=>e.replace(/\\n/g,`
|
|
8
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Na=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)}},Oy=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Dg=e=>e.status==="complete"?Oy(e):e.status==="pending"?"Waiting":"",_y=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Fg=e=>e.status==="complete"?_y(e):"Using tool...",Ti=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Es=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return Ti(t)},Ei=e=>{var r,o,n;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return Ti(t)},od=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=Es(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ki=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&Ts(o,r.slice(a,s.index),[]),s[1]!==void 0?Ts(o,s[1],["bold"]):s[2]!==void 0?Ts(o,s[2],["italic"]):s[3]!==void 0&&Ts(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&Ts(o,r.slice(a),[]),o},Ts=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Uy=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
56
9
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
57
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>r,processChunk:async o=>{if(o.length<=e)return r!==null?{text:r,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=t(o);return a!==null&&(r=a),e=o.length,r!==null?{text:r,raw:o}:null},close:async()=>{}}},xa=r=>{try{let e=JSON.parse(r);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},rl=()=>{let r={processChunk:e=>null,getExtractedText:()=>null};return r.__isPlainTextParser=!0,r},ol=()=>{var e;let r=gv();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:r.processChunk(t)},getExtractedText:r.getExtractedText.bind(r),close:(e=r.close)==null?void 0:e.bind(r)}},nl=()=>{let r=null,e=0;return{getExtractedText:()=>r,processChunk:t=>{let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(t.length<=e)return r!==null||r===""?{text:r||"",raw:t}:null;try{let n=(0,Sn.parse)(t,Sn.STR|Sn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?r=typeof n.text=="string"?Ji(n.text):"":n.type==="init"&&n.form?r="":typeof n.text=="string"&&(r=Ji(n.text)))}catch{}return e=t.length,r!==null?{text:r,raw:t}:null},close:()=>{}}},Zh=r=>{let e=null,t=0,n=r||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Ji(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Ji(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>e,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return e!==null?{text:e,raw:a}:null;try{let i=(0,Sn.parse)(a,Sn.STR|Sn.OBJ),d=n(i);d!==null&&(e=d)}catch{}return t=a.length,{text:e||"",raw:a}},close:()=>{}}},al=()=>{let r=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(r=o[1],{text:r,raw:e}):null},getExtractedText:()=>r}};var sl=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var a,s,i;let o=(i=(a=t==null?void 0:t.seq)!=null?a:t==null?void 0:t.sequenceIndex)!=null?i:(s=t==null?void 0:t.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(e,t);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:e,payload:t,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.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 e=[...this.buffer.entries()].sort((t,o)=>t[0]-o[0]);for(let[t,o]of e)this.buffer.delete(t),this.emitter(o.payloadType,o.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var hv="https://api.runtype.com/v1/dispatch",il="https://api.runtype.com";function xv(r){var a,s;let e=r.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let n=e.indexOf("/");if(n>0){let i=(s=(a=e.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var jd=r=>!!(r.contentParts&&r.contentParts.length>0||r.llmContent&&r.llmContent.trim().length>0||r.rawContent&&r.rawContent.trim().length>0||r.content&&r.content.trim().length>0);function yv(r){switch(r){case"json":return nl;case"regex-json":return ol;case"xml":return al;default:return rl}}var ex=r=>r.startsWith("{")||r.startsWith("[")||r.startsWith("<");function bv(r,e){if(!r)return e;let t=r.trim(),o=e.trim();if(t.length===0)return e;if(o.length===0)return r;let n=ex(t);if(!ex(o))return r;if(!n||o===t||o.startsWith(t))return e;let s=xa(r);return xa(e)!==null&&s===null?e:r}var ya=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,o,n,a;this.apiUrl=(t=e.apiUrl)!=null?t:hv,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(o=e.streamParser)!=null?o:yv(e.parserType),this.contextProviders=(n=e.contextProviders)!=null?n:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((a=e.webmcp)==null?void 0:a.enabled)===!0?new Ga(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let e=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/client/feedback`}async sendFeedback(e){var s,i;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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let n={...e,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok){let d=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var n,a,s,i;let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}let l=await this.buildPayload(e.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(jd).map(x=>{var w,v,E;return{id:x.id,role:x.role,content:(E=(v=(w=x.contentParts)!=null?w:x.llmContent)!=null?v:x.rawContent)!=null?E:x.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},p=l.clientTools,m=!!(p&&p.length>0),y=m?Bh(p):void 0,h=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&h&&this.lastSentClientToolsFingerprint===y,M=!1,k=null,L;for(let x=0;;x++){let v={...f,...m&&(M||!T)&&p?{clientTools:p}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),L.status===409&&x===0&&m){let E=await L.json().catch(()=>null);if((E==null?void 0:E.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}k=E!=null?E:{error:"Chat request failed"}}break}if(!L.ok){let x=k!=null?k:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(L.status===429){let v=new Error(x.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let w=new Error(x.error||"Failed to send message");throw t({type:"error",error:w}),w}if(!L.body){let x=new Error("No response body received");throw t({type:"error",error:x}),x}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(L.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(e,t){let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let n=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let n=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/agents/${e.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,o){var l,u;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||il}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return s&&(d.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(e){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(jd).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...Gs(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(e){var a,s;let o={messages:e.slice().filter(jd).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...Gs(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let d=i;return o.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=o.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(e,t,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return o.current=f,n(f),f},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),d(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,n(u)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,t({type:"status",status:"idle"})),i.error&&(s.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,o){var Rt,dr,Yr,zr;let n=e.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=O=>{let fe=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Ie=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Je=O.tools?O.tools.map(qe=>({...qe,chunks:qe.chunks?[...qe.chunks]:void 0})):void 0;return{...O,reasoning:fe,toolCall:Ie,tools:Je}},f=O=>{if(O.role!=="assistant"||O.variant)return!0;let fe=Array.isArray(O.contentParts)&&O.contentParts.length>0,Ie=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||fe||Ie||!!O.stopReason},p=O=>{f(O)&&t({type:"message",message:u(O)})},m=null,y=null,h={current:null},T={current:null},M=!1,k=new Map,L=new Map,x=new Map,w=new Map,v={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},H=(O,fe,Ie="")=>`${O}::${fe}::${Ie}`,I=(O,fe)=>`${O}::${fe}::`,P=(O,fe,Ie,Je)=>{let qe=H(O,fe,Ie),ze=x.get(qe);if(ze)return ze;let lt=Ie?`-${Ie}`:"",Mt={id:`nested-${O}-${fe}${lt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ie?{partId:Ie}:{},agentMetadata:{executionId:Je,parentToolId:O,parentStepId:fe}};return x.set(qe,Mt),p(Mt),Mt},z=O=>{if(O==null)return null;try{return String(O)}catch{return null}},j=O=>{var fe,Ie,Je,qe,ze;return z((ze=(qe=(Je=(Ie=(fe=O.stepId)!=null?fe:O.step_id)!=null?Ie:O.step)!=null?Je:O.parentId)!=null?qe:O.flowStepId)!=null?ze:O.flow_step_id)},ie=O=>{var fe,Ie,Je,qe,ze,lt,Mt;return z((Mt=(lt=(ze=(qe=(Je=(Ie=(fe=O.callId)!=null?fe:O.call_id)!=null?Ie:O.requestId)!=null?Je:O.request_id)!=null?qe:O.toolCallId)!=null?ze:O.tool_call_id)!=null?lt:O.stepId)!=null?Mt:O.step_id)},ve=o,Xe=!1,Ae=()=>{if(m)return m;let O;return!Xe&&ve?(O=ve,Xe=!0):ve&&T.current?O=`${ve}_${T.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(m),m},We=(O,fe)=>{v.lastId=fe,O&&v.byStep.set(O,fe)},Me=(O,fe)=>{var ze;let Ie=(ze=O.reasoningId)!=null?ze:O.id,Je=j(O);if(Ie){let lt=String(Ie);return We(Je,lt),lt}if(Je){let lt=v.byStep.get(Je);if(lt)return v.lastId=lt,lt}if(v.lastId&&!fe)return v.lastId;if(!fe)return null;let qe=`reason-${l()}`;return We(Je,qe),qe},Ue=O=>{let fe=k.get(O);if(fe)return fe;let Ie={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return k.set(O,Ie),p(Ie),Ie},Be=(O,fe)=>{E.lastId=fe,O&&E.byCall.set(O,fe)},Z=new Set,ne=new Map,me=new Set,be=new Map,ye=O=>{if(!O)return!1;let fe=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return fe==="emit_artifact_markdown"||fe==="emit_artifact_component"},Y=(O,fe)=>{var ze;let Ie=(ze=O.toolId)!=null?ze:O.id,Je=ie(O);if(Ie){let lt=String(Ie);return Be(Je,lt),lt}if(Je){let lt=E.byCall.get(Je);if(lt)return E.lastId=lt,lt}if(E.lastId&&!fe)return E.lastId;if(!fe)return null;let qe=`tool-${l()}`;return Be(Je,qe),qe},ge=O=>{let fe=L.get(O);if(fe)return fe;let Ie={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,Ie),p(Ie),Ie},Oe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let fe=Number(O);if(!Number.isNaN(fe)&&Number.isFinite(fe))return fe;let Ie=Date.parse(O);if(!Number.isNaN(Ie))return Ie}return Date.now()},ce=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},ae=new Map,Q=new Map,Tt=new Map,Ye=new Map,De=null,le=(O,fe,Ie)=>{var Mt;let Je=Tt.get(O);Je||(Je=[],Tt.set(O,Je));let qe=0,ze=Je.length;for(;qe<ze;){let Dt=qe+ze>>>1;Je[Dt].seq<fe?qe=Dt+1:ze=Dt}((Mt=Je[qe])==null?void 0:Mt.seq)===fe?Je[qe]={seq:fe,text:Ie}:Je.splice(qe,0,{seq:fe,text:Ie});let lt="";for(let Dt=0;Dt<Je.length;Dt++)lt+=Je[Dt].text;return lt},nt=(O,fe)=>{let Ie=ce(fe),Je=Q.get(O.id),qe=bv(Je,Ie);O.rawContent=qe;let ze=ae.get(O.id),lt=wt=>{var Ce;let ct=(Ce=O.content)!=null?Ce:"";wt.trim()!==""&&(ct.trim().length===0||wt.startsWith(ct)||wt.trimStart().startsWith(ct.trim()))&&(O.content=wt)},Mt=()=>{var wt;if(ze){let ct=(wt=ze.close)==null?void 0:wt.call(ze);ct instanceof Promise&&ct.catch(()=>{})}ae.delete(O.id),Q.delete(O.id),O.streaming=!1,p(O)};if(!ze){lt(Ie),Mt();return}let Dt=xa(qe);if(Dt!==null&&Dt.trim()!==""){lt(Dt),Mt();return}let or=wt=>{var de;let ct=typeof wt=="string"?wt:(de=wt==null?void 0:wt.text)!=null?de:null;if(ct!==null&&ct.trim()!=="")return ct;let Ce=ze.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:Ie},X;try{X=ze.processChunk(qe)}catch{lt(Ie),Mt();return}if(X instanceof Promise){X.then(wt=>{lt(or(wt)),Mt()}).catch(()=>{lt(Ie),Mt()});return}lt(or(X)),Mt()},Re=[],K=!1,he,it=()=>{K||(K=!0,queueMicrotask(()=>{K=!1,he()}))},Pt=new sl((O,fe)=>{Re.push({payloadType:O,payload:fe}),it()}),te=null,_e=new Map,Ar=(Rt=this.config.iterationDisplay)!=null?Rt:"separate";for(he=()=>{var O,fe,Ie,Je,qe,ze,lt,Mt,Dt,or,X,wt,ct,Ce,de,rt,Ft,zt,Pr,vr,xt,It,tt,jt,cr,Dr,hr,Sr,Oo,je,Tr,io,_o,lo,At,rn,No,mn,Jr,Ln,$r,Fo,mt,co,po,Or,Wt,Vr,Zr,_r,uo,fo,Nr,mo,$t,Fr,go,on,Uo,nn,qo,eo,to,gt,re,A,_,ue,$,at,ut,U,nr,mr,Cr,ko,sr,Ko,us,Eo,Lo,Xo,Qo,Qn,gn,ro,an,Pa,Yn,Ra,bi,Ia,vi,Ha,Lt,fs,zo,So,Ci,wi,Wa,hn,ms,Pn,gs,hs,xs,ys,To,Ba,sn,ln,bs,Ai,vs,Cs,Jn,Si,Ti,Mi,ki,dd,Zn,Rn,Ei,ws,In,Li,As,Hn,Ss,Pi,xn,Ri,Wn,Gt,Da,Oa;for(let ea=0;ea<Re.length;ea++){let Ke=Re[ea].payloadType,R=Re[ea].payload;if(Ke==="reason_start"){let V=(O=Me(R,!0))!=null?O:`reason-${l()}`,B=Ue(V);B.reasoning=(fe=B.reasoning)!=null?fe:{id:V,status:"streaming",chunks:[]},B.reasoning.startedAt=(Je=B.reasoning.startedAt)!=null?Je:Oe((Ie=R.startedAt)!=null?Ie:R.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",p(B)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let V=(ze=(qe=Me(R,!1))!=null?qe:Me(R,!0))!=null?ze:`reason-${l()}`,B=Ue(V);B.reasoning=(lt=B.reasoning)!=null?lt:{id:V,status:"streaming",chunks:[]},B.reasoning.startedAt=(Dt=B.reasoning.startedAt)!=null?Dt:Oe((Mt=R.startedAt)!=null?Mt:R.timestamp);let oe=(wt=(X=(or=R.reasoningText)!=null?or:R.text)!=null?X:R.delta)!=null?wt:"";if(oe&&R.hidden!==!0){let pe=typeof R.sequenceIndex=="number"?R.sequenceIndex:void 0;if(pe!==void 0){let J=le(V,pe,String(oe));B.reasoning.chunks=[J]}else B.reasoning.chunks.push(String(oe))}if(B.reasoning.status=R.done?"complete":"streaming",R.done){B.reasoning.completedAt=Oe((ct=R.completedAt)!=null?ct:R.timestamp);let pe=(Ce=B.reasoning.startedAt)!=null?Ce:Date.now();B.reasoning.durationMs=Math.max(0,((de=B.reasoning.completedAt)!=null?de:Date.now())-pe)}B.streaming=B.reasoning.status!=="complete",p(B)}else if(Ke==="reason_complete"){let V=(Ft=(rt=Me(R,!1))!=null?rt:Me(R,!0))!=null?Ft:`reason-${l()}`,B=k.get(V);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=Oe((zt=R.completedAt)!=null?zt:R.timestamp);let pe=(Pr=B.reasoning.startedAt)!=null?Pr:Date.now();B.reasoning.durationMs=Math.max(0,((vr=B.reasoning.completedAt)!=null?vr:Date.now())-pe),B.streaming=!1,p(B)}let oe=j(R);oe&&v.byStep.delete(oe)}else if(Ke==="tool_start"){let V=(xt=Y(R,!0))!=null?xt:`tool-${l()}`,B=(It=R.toolName)!=null?It:R.name;if(ye(B)){Z.add(V);continue}let oe=ge(V),pe=(tt=oe.toolCall)!=null?tt:{id:V,status:"pending"};pe.name=B!=null?B:pe.name,pe.status="running",R.args!==void 0?pe.args=R.args:R.parameters!==void 0&&(pe.args=R.parameters),pe.startedAt=(cr=pe.startedAt)!=null?cr:Oe((jt=R.startedAt)!=null?jt:R.timestamp),pe.completedAt=void 0,pe.durationMs=void 0,oe.toolCall=pe,oe.streaming=!0;let J=R.agentContext;(J||R.executionId)&&(oe.agentMetadata={executionId:(Dr=J==null?void 0:J.executionId)!=null?Dr:R.executionId,iteration:(hr=J==null?void 0:J.iteration)!=null?hr:R.iteration}),p(oe)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let V=(Oo=(Sr=Y(R,!1))!=null?Sr:Y(R,!0))!=null?Oo:`tool-${l()}`;if(Z.has(V))continue;let B=ge(V),oe=(je=B.toolCall)!=null?je:{id:V,status:"running"};oe.startedAt=(io=oe.startedAt)!=null?io:Oe((Tr=R.startedAt)!=null?Tr:R.timestamp);let pe=(At=(lo=(_o=R.text)!=null?_o:R.delta)!=null?lo:R.message)!=null?At:"";pe&&(oe.chunks=(rn=oe.chunks)!=null?rn:[],oe.chunks.push(String(pe))),oe.status="running",B.toolCall=oe,B.streaming=!0;let J=R.agentContext;(J||R.executionId)&&(B.agentMetadata=(Jr=B.agentMetadata)!=null?Jr:{executionId:(No=J==null?void 0:J.executionId)!=null?No:R.executionId,iteration:(mn=J==null?void 0:J.iteration)!=null?mn:R.iteration}),p(B)}else if(Ke==="tool_complete"){let V=($r=(Ln=Y(R,!1))!=null?Ln:Y(R,!0))!=null?$r:`tool-${l()}`;if(Z.has(V)){Z.delete(V);continue}let B=ge(V),oe=(Fo=B.toolCall)!=null?Fo:{id:V,status:"running"};oe.status="complete",R.result!==void 0&&(oe.result=R.result),typeof R.duration=="number"&&(oe.duration=R.duration),oe.completedAt=Oe((mt=R.completedAt)!=null?mt:R.timestamp);let pe=(co=R.duration)!=null?co:R.executionTime;if(typeof pe=="number")oe.durationMs=pe;else{let Ve=(po=oe.startedAt)!=null?po:Date.now();oe.durationMs=Math.max(0,((Or=oe.completedAt)!=null?Or:Date.now())-Ve)}B.toolCall=oe,B.streaming=!1;let J=R.agentContext;(J||R.executionId)&&(B.agentMetadata=(Zr=B.agentMetadata)!=null?Zr:{executionId:(Wt=J==null?void 0:J.executionId)!=null?Wt:R.executionId,iteration:(Vr=J==null?void 0:J.iteration)!=null?Vr:R.iteration}),p(B);let Le=ie(R);Le&&E.byCall.delete(Le)}else if(Ke==="step_await"&&R.awaitReason==="local_tool_required"&&R.toolName){let V=typeof R.toolCallId=="string"&&R.toolCallId.length>0?R.toolCallId:void 0,B=(_r=V!=null?V:R.toolId)!=null?_r:`local-${l()}`,oe=ge(B),pe=R.toolName,J=ga(pe),Le=(uo=oe.toolCall)!=null?uo:{id:B,status:"pending"};Le.name=pe,Le.args=R.parameters,Le.status=J?"running":"complete",Le.chunks=(fo=Le.chunks)!=null?fo:[],Le.startedAt=(mo=Le.startedAt)!=null?mo:Oe((Nr=R.startedAt)!=null?Nr:R.timestamp),J?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=($t=Le.completedAt)!=null?$t:Le.startedAt,oe.toolCall=Le,oe.streaming=!1,oe.agentMetadata={...oe.agentMetadata,executionId:(go=R.executionId)!=null?go:(Fr=oe.agentMetadata)==null?void 0:Fr.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},p(oe)}else if(Ke==="text_start"){if((on=R.toolContext)!=null&&on.toolId)continue;let V=R.partId;if(V!==void 0&&T.current!==null&&V!==T.current){let B=m;B&&(B.streaming=!1,p(B),De=B,m=null,M=!0)}V!==void 0&&(T.current=V)}else if(Ke==="text_end"){if((Uo=R.toolContext)!=null&&Uo.toolId)continue;let V=m;V&&(V.streaming=!1,p(V),De=V,m=null,M=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let V=R.stepType,B=R.executionType;if(V==="tool"||B==="context")continue;let oe=R.toolContext;if(oe!=null&&oe.toolId){let Ve=String((qo=(nn=R.id)!=null?nn:oe.stepId)!=null?qo:`step-${l()}`),yt=R.partId!==void 0&&R.partId!==null?String(R.partId):"",dt=`${oe.toolId}::${Ve}`,Vt=w.get(dt);if(yt!==""&&Vt!==void 0&&Vt!==""&&Vt!==yt){let ht=x.get(H(oe.toolId,Ve,Vt));ht&&ht.streaming!==!1&&(ht.streaming=!1,p(ht))}yt!==""&&w.set(dt,yt);let Jt=P(oe.toolId,Ve,yt,oe.executionId),Rr=(re=(gt=(to=(eo=R.text)!=null?eo:R.delta)!=null?to:R.content)!=null?gt:R.chunk)!=null?re:"";Rr&&(Jt.content+=String(Rr),Jt.streaming=!0,p(Jt)),R.isComplete&&(Jt.streaming=!1,p(Jt));continue}let pe=R.partId;if(pe!==void 0&&T.current!==null&&pe!==T.current){let Ve=m;Ve&&(Ve.streaming=!1,p(Ve),De=Ve,m=null,M=!0)}pe!==void 0&&(T.current=pe);let J=pe!==void 0&&(A=Ye.get(pe))!=null?A:Ae();pe!==void 0&&(J.partId||(J.partId=pe),Ye.set(pe,J));let Le=(at=($=(ue=(_=R.text)!=null?_:R.delta)!=null?ue:R.content)!=null?$:R.chunk)!=null?at:"";if(Le){let Ve=typeof R.seq=="number"?R.seq:void 0,yt=pe!=null?pe:J.id,dt=Ve!==void 0?le(yt,Ve,String(Le)):((ut=Q.get(J.id))!=null?ut:"")+Le;J.rawContent=dt,ae.has(J.id)||ae.set(J.id,this.createStreamParser());let Vt=ae.get(J.id),Jt=dt.trim().startsWith("{")||dt.trim().startsWith("[");if(Jt&&Q.set(J.id,dt),Vt.__isPlainTextParser===!0){J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J);continue}let ht=Vt.processChunk(dt);if(ht instanceof Promise)ht.then(kt=>{var et;let gr=typeof kt=="string"?kt:(et=kt==null?void 0:kt.text)!=null?et:null;if(gr!==null&&gr.trim()!=="")J.content=gr,p(J);else if(!Jt&&!dt.trim().startsWith("<")){let jr=m,pr=jr&&jr.id===J.id?jr:J;pr.id===J.id&&(pr.content=Ve!==void 0?dt:pr.content+Le,Q.delete(pr.id),ae.delete(pr.id),pr.rawContent=void 0,p(pr))}}).catch(()=>{J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J)});else{let kt=typeof ht=="string"?ht:(U=ht==null?void 0:ht.text)!=null?U:null;kt!==null&&kt.trim()!==""?(J.content=kt,p(J)):!Jt&&!dt.trim().startsWith("<")&&(J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J))}}if(R.isComplete){let Ve=(mr=(nr=R.result)==null?void 0:nr.response)!=null?mr:J.content;if(Ve){let yt=Q.get(J.id),dt=yt!=null?yt:ce(Ve);J.rawContent=dt;let Vt=ae.get(J.id),Jt=null,Rr=!1;if(Vt&&(Jt=Vt.getExtractedText(),Jt===null&&(Jt=xa(dt)),Jt===null)){let ht=Vt.processChunk(dt);ht instanceof Promise?(Rr=!0,ht.then(kt=>{var et;let gr=typeof kt=="string"?kt:(et=kt==null?void 0:kt.text)!=null?et:null;if(gr!==null){let jr=m;jr&&jr.id===J.id&&(jr.content=gr,jr.streaming=!1,ae.delete(jr.id),Q.delete(jr.id),p(jr))}})):Jt=typeof ht=="string"?ht:(Cr=ht==null?void 0:ht.text)!=null?Cr:null}if(!Rr){Jt!==null&&Jt.trim()!==""?J.content=Jt:Q.has(J.id)||(J.content=ce(Ve));let ht=ae.get(J.id);if(ht){let kt=(ko=ht.close)==null?void 0:ko.call(ht);kt instanceof Promise&&kt.catch(()=>{}),ae.delete(J.id)}Q.delete(J.id),J.streaming=!1,p(J)}}}}else if(Ke==="step_complete"){let V=R.stepType,B=R.executionType;if(V==="tool"||B==="context")continue;let oe=R.toolContext;if(oe!=null&&oe.toolId){let Ve=String((Ko=(sr=R.id)!=null?sr:oe.stepId)!=null?Ko:"");if(Ve){let yt=I(oe.toolId,Ve);for(let[dt,Vt]of x)dt.startsWith(yt)&&Vt.streaming!==!1&&(Vt.streaming=!1,p(Vt));w.delete(`${oe.toolId}::${Ve}`)}continue}let pe=R.stopReason;if(M){if(m!==null){let dt=m;pe&&(dt.stopReason=pe),ae.delete(dt.id),Q.delete(dt.id),dt.streaming!==!1&&(dt.streaming=!1,p(dt))}let Ve=(us=R.result)==null?void 0:us.response,yt=De;yt&&(pe&&(yt.stopReason=pe),Ve!=null?nt(yt,Ve):(ae.delete(yt.id),Q.delete(yt.id))),De=null;continue}let J=(Eo=R.result)==null?void 0:Eo.response,Le=Ae();if(pe&&(Le.stopReason=pe),J!=null){let Ve=ae.get(Le.id),yt=!1,dt=!1;if(Ve){let Vt=Ve.getExtractedText(),Jt=Q.get(Le.id),Rr=Jt!=null?Jt:ce(J);if(Le.rawContent=Rr,Vt!==null&&Vt.trim()!=="")Le.content=Vt,yt=!0;else{let ht=xa(Rr);if(ht!==null)Le.content=ht,yt=!0;else{let kt=Ve.processChunk(Rr);if(kt instanceof Promise)dt=!0,kt.then(gr=>{var jr;let et=typeof gr=="string"?gr:(jr=gr==null?void 0:gr.text)!=null?jr:null;if(et!==null&&et.trim()!==""){let pr=m;pr&&pr.id===Le.id&&(pr.content=et,pr.streaming=!1,ae.delete(pr.id),Q.delete(pr.id),p(pr))}else{let pr=Ve.getExtractedText(),Ur=m;Ur&&Ur.id===Le.id&&(pr!==null&&pr.trim()!==""?Ur.content=pr:Q.has(Ur.id)||(Ur.content=ce(J)),Ur.streaming=!1,ae.delete(Ur.id),Q.delete(Ur.id),p(Ur))}});else{let gr=typeof kt=="string"?kt:(Lo=kt==null?void 0:kt.text)!=null?Lo:null;if(gr!==null&&gr.trim()!=="")Le.content=gr,yt=!0;else{let et=Ve.getExtractedText();et!==null&&et.trim()!==""&&(Le.content=et,yt=!0)}}}}}if(!dt){if(!Le.rawContent){let Vt=Q.get(Le.id);Le.rawContent=Vt!=null?Vt:ce(J)}if(!yt&&!Q.has(Le.id)&&(Le.content=ce(J)),Ve){let Vt=(Xo=Ve.close)==null?void 0:Xo.call(Ve);Vt instanceof Promise&&Vt.catch(()=>{})}ae.delete(Le.id),Q.delete(Le.id),Le.streaming=!1,p(Le)}}else ae.delete(Le.id),Q.delete(Le.id),Le.streaming=!1,p(Le)}else if(Ke==="flow_complete"){let V=(Qo=R.result)==null?void 0:Qo.response;if(M){if(m!==null){let B=m;ae.delete(B.id),Q.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}}else if(V!=null){let B=Ae(),oe=Q.get(B.id),pe=oe!=null?oe:ce(V);B.rawContent=pe;let J=ce(V),Le=ae.get(B.id);if(Le){let dt=xa(pe);if(dt!==null)J=dt;else{let Vt=Le.processChunk(pe);Vt instanceof Promise&&Vt.then(Rr=>{var kt;let ht=typeof Rr=="string"?Rr:(kt=Rr==null?void 0:Rr.text)!=null?kt:null;ht!==null&&(B.content=ht,B.streaming=!1,p(B))});let Jt=Le.getExtractedText();Jt!==null&&(J=Jt)}}ae.delete(B.id),Q.delete(B.id);let Ve=J!==B.content,yt=B.streaming!==!1;Ve&&(B.content=J),B.streaming=!1,(Ve||yt)&&p(B)}else if(m!==null){let B=m;ae.delete(B.id),Q.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}t({type:"status",status:"idle"})}else if(Ke==="agent_start")te={executionId:R.executionId,agentId:(Qn=R.agentId)!=null?Qn:"virtual",agentName:(gn=R.agentName)!=null?gn:"",status:"running",currentIteration:0,maxTurns:(ro=R.maxTurns)!=null?ro:1,startedAt:Oe(R.startedAt)};else if(Ke==="agent_iteration_start"){if(te&&(te.currentIteration=R.iteration),Ar==="separate"&&R.iteration>1){let V=m;V&&(V.streaming=!1,p(V),_e.set(R.iteration-1,V),m=null)}}else if(Ke==="agent_turn_start")y=null;else if(Ke==="agent_turn_delta"){if(R.contentType==="text"){let V=Ae();V.content+=(an=R.delta)!=null?an:"",V.agentMetadata={executionId:R.executionId,iteration:R.iteration,turnId:R.turnId,agentName:te==null?void 0:te.agentName},y=V,p(V)}else if(R.contentType==="thinking"){let V=(Pa=R.turnId)!=null?Pa:`agent-think-${R.iteration}`,B=Ue(V);B.reasoning=(Yn=B.reasoning)!=null?Yn:{id:V,status:"streaming",chunks:[]},B.reasoning.chunks.push((Ra=R.delta)!=null?Ra:""),B.agentMetadata={executionId:R.executionId,iteration:R.iteration,turnId:R.turnId},p(B)}else if(R.contentType==="tool_input"){let V=(bi=R.toolCallId)!=null?bi:E.lastId;if(V){let B=L.get(V);B!=null&&B.toolCall&&(B.toolCall.chunks=(Ia=B.toolCall.chunks)!=null?Ia:[],B.toolCall.chunks.push((vi=R.delta)!=null?vi:""),p(B))}}}else if(Ke==="agent_turn_complete"){let V=R.turnId;if(V){let pe=k.get(V);if(pe!=null&&pe.reasoning){pe.reasoning.status="complete",pe.reasoning.completedAt=Oe(R.completedAt);let J=(Ha=pe.reasoning.startedAt)!=null?Ha:Date.now();pe.reasoning.durationMs=Math.max(0,((Lt=pe.reasoning.completedAt)!=null?Lt:Date.now())-J),pe.streaming=!1,p(pe)}}let B=R.stopReason,oe=m!=null?m:y;if(B&&oe!==null){let pe=R.turnId;(!pe||((fs=oe.agentMetadata)==null?void 0:fs.turnId)===pe)&&(oe.stopReason=B,p(oe))}}else if(Ke==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let V=(zo=R.toolCallId)!=null?zo:`agent-tool-${l()}`;Be(ie(R),V);let B=ge(V),oe=(So=B.toolCall)!=null?So:{id:V,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};oe.name=(wi=(Ci=R.toolName)!=null?Ci:R.name)!=null?wi:oe.name,oe.status="running",R.parameters!==void 0&&(oe.args=R.parameters),oe.startedAt=Oe((Wa=R.startedAt)!=null?Wa:R.timestamp),B.toolCall=oe,B.streaming=!0,B.agentMetadata={executionId:R.executionId,iteration:R.iteration},p(B)}else if(Ke==="agent_tool_delta"){let V=(hn=R.toolCallId)!=null?hn:E.lastId;if(V){let B=(ms=L.get(V))!=null?ms:ge(V);B.toolCall&&(B.toolCall.chunks=(Pn=B.toolCall.chunks)!=null?Pn:[],B.toolCall.chunks.push((gs=R.delta)!=null?gs:""),B.toolCall.status="running",B.streaming=!0,p(B))}}else if(Ke==="agent_tool_complete"){let V=(hs=R.toolCallId)!=null?hs:E.lastId;if(V){let B=(xs=L.get(V))!=null?xs:ge(V);if(B.toolCall){B.toolCall.status="complete",R.result!==void 0&&(B.toolCall.result=R.result),typeof R.executionTime=="number"&&(B.toolCall.durationMs=R.executionTime),B.toolCall.completedAt=Oe((ys=R.completedAt)!=null?ys:R.timestamp),B.streaming=!1,p(B);let oe=ie(R);oe&&E.byCall.delete(oe)}}}else if(Ke==="agent_media"){let V=Array.isArray(R.media)?R.media:[],B=[];for(let oe of V){if(!oe||typeof oe!="object")continue;let pe=oe,J=typeof pe.type=="string"?pe.type:void 0,Le=typeof pe.mediaType=="string"?pe.mediaType.toLowerCase():"",Ve=null,yt="";if(J==="media"){let dt=typeof pe.data=="string"?pe.data:void 0;if(!dt)continue;yt=Le.length>0?Le:"application/octet-stream",Ve=`data:${yt};base64,${dt}`}else if(J==="image-url"){let dt=typeof pe.url=="string"?pe.url:void 0;if(!dt)continue;yt=Le,Ve=dt}else if(J==="file-url"){let dt=typeof pe.url=="string"?pe.url:void 0;if(!dt)continue;yt=Le,Ve=dt}else continue;if(Ve)if(J==="image-url"||yt.startsWith("image/"))B.push({type:"image",image:Ve,...yt?{mimeType:yt}:{}});else if(yt.startsWith("audio/"))B.push({type:"audio",audio:Ve,mimeType:yt});else if(yt.startsWith("video/"))B.push({type:"video",video:Ve,mimeType:yt});else{let dt=yt||"application/octet-stream";B.push({type:"file",data:Ve,mimeType:dt,filename:xv(dt)})}}if(B.length>0){let oe=l(),pe=R.toolCallId,Le={id:`agent-media-${typeof pe=="string"&&pe.length>0?`${pe}-${oe}`:String(oe)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:oe,agentMetadata:{executionId:R.executionId,iteration:R.iteration}};p(Le);let Ve=m;Ve&&(Ve.streaming=!1,p(Ve)),m=null,h.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let V=`agent-reflection-${R.executionId}-${R.iteration}`,B={id:V,role:"assistant",content:(To=R.reflection)!=null?To:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:V,status:"complete",chunks:[(Ba=R.reflection)!=null?Ba:""]},agentMetadata:{executionId:R.executionId,iteration:R.iteration}};p(B)}else if(Ke==="agent_complete"){te&&(te.status=R.success?"complete":"error",te.completedAt=Oe(R.completedAt),te.stopReason=R.stopReason);let V=m;V&&(V.streaming=!1,p(V)),t({type:"status",status:"idle"})}else if(Ke==="agent_error"){let V=typeof R.error=="string"?R.error:(ln=(sn=R.error)==null?void 0:sn.message)!=null?ln:"Agent execution error";R.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",V):t({type:"error",error:new Error(V)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let V=(bs=R.approvalId)!=null?bs:`approval-${l()}`,B={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(Ai=te==null?void 0:te.agentId)!=null?Ai:"virtual",executionId:(Cs=(vs=R.executionId)!=null?vs:te==null?void 0:te.executionId)!=null?Cs:"",toolName:(Jn=R.toolName)!=null?Jn:"",toolType:R.toolType,description:(Ti=R.description)!=null?Ti:`Execute ${(Si=R.toolName)!=null?Si:"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters}};p(B)}else if(Ke==="step_await"&&R.awaitReason==="approval_required"){let V=(Mi=R.approvalId)!=null?Mi:`approval-${l()}`,B={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(ki=te==null?void 0:te.agentId)!=null?ki:"virtual",executionId:(Zn=(dd=R.executionId)!=null?dd:te==null?void 0:te.executionId)!=null?Zn:"",toolName:(Rn=R.toolName)!=null?Rn:"",toolType:R.toolType,description:(ws=R.description)!=null?ws:`Execute ${(Ei=R.toolName)!=null?Ei:"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters}};p(B)}else if(Ke==="agent_approval_complete"){let V=R.approvalId;if(V){let oe={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:(In=R.decision)!=null?In:"approved",agentId:(Li=te==null?void 0:te.agentId)!=null?Li:"virtual",executionId:(Hn=(As=R.executionId)!=null?As:te==null?void 0:te.executionId)!=null?Hn:"",toolName:(Ss=R.toolName)!=null?Ss:"",description:(Pi=R.description)!=null?Pi:"",resolvedAt:Date.now()}};p(oe)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let V=R.artifactType,B=String(R.id),oe=typeof R.title=="string"?R.title:void 0;if(t({type:"artifact_start",id:B,artifactType:V,title:oe,component:typeof R.component=="string"?R.component:void 0}),be.set(B,{markdown:"",title:oe}),!me.has(B)){me.add(B);let pe={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:oe,artifactType:V,status:"streaming"}})};ne.set(B,pe),p(pe)}}else if(Ke==="artifact_delta"){let V=String(R.id),B=typeof R.delta=="string"?R.delta:String((xn=R.delta)!=null?xn:"");t({type:"artifact_delta",id:V,artDelta:B});let oe=be.get(V);oe&&(oe.markdown+=B)}else if(Ke==="artifact_update"){let V=R.props&&typeof R.props=="object"&&!Array.isArray(R.props)?R.props:{};t({type:"artifact_update",id:String(R.id),props:V,component:typeof R.component=="string"?R.component:void 0})}else if(Ke==="artifact_complete"){let V=String(R.id);t({type:"artifact_complete",id:V});let B=ne.get(V);if(B){B.streaming=!1;try{let oe=JSON.parse((Ri=B.rawContent)!=null?Ri:"{}");if(oe.props){oe.props.status="complete";let pe=be.get(V);pe!=null&&pe.markdown&&(oe.props.markdown=pe.markdown)}B.rawContent=JSON.stringify(oe)}catch{}be.delete(V),p(B),ne.delete(V)}}}else if(Ke==="transcript_insert"){let V=R.message;if(!V||typeof V!="object")continue;let B=String((Wn=V.id)!=null?Wn:`msg-${l()}`),oe=V.role,J={id:B,role:oe==="user"?"user":oe==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:l()};if(p(J),J.rawContent)try{let Le=JSON.parse(J.rawContent),Ve=(Gt=Le==null?void 0:Le.props)==null?void 0:Gt.artifactId;typeof Ve=="string"&&me.add(Ve)}catch{}m=null,h.current=null,ae.delete(B),Q.delete(B)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let V=null;if(R.error instanceof Error)V=R.error;else if(Ke==="dispatch_error"){let B=(Da=R.message)!=null?Da:R.error;B!=null&&B!==""&&(V=new Error(String(B)))}else if(Ke==="step_error"||Ke==="flow_error"){let B=R.error;typeof B=="string"&&B!==""?V=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(V=new Error(String((Oa=B.message)!=null?Oa:B)))}else Ke==="error"&&R.error!=null&&R.error!==""&&(V=new Error(String(R.error)));if(V){t({type:"error",error:V});let B=m;B&&B.streaming&&(B.streaming=!1,p(B)),t({type:"status",status:"idle"})}}}}}Re.length=0};;){let{done:O,value:fe}=await n.read();if(O)break;s+=a.decode(fe,{stream:!0});let Ie=s.split(`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ra=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Pi=()=>{var t;let e=Uy();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Ri=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,nn.parse)(r,nn.STR|nn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?Mi(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=Mi(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Ng=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Mi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Mi(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,nn.parse)(a,nn.STR|nn.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},Ii=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Wi=class{constructor(t,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=r}push(t,r){var a,s,i;let o=(i=(a=r==null?void 0:r.seq)!=null?a:r==null?void 0:r.sequenceIndex)!=null?i:(s=r==null?void 0:r.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,r),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,r);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:t,payload:r,seq:o}),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((r,o)=>r[0]-o[0]);for(let[r,o]of t)this.buffer.delete(r),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Og="3.36.0";var oa=Og;var Vy="https://api.runtype.com/v1/dispatch",Hi="https://api.runtype.com";function $y(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var nd=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 zy(e){switch(e){case"json":return Ri;case"regex-json":return Pi;case"xml":return Ii;default:return Li}}var _g=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function jy(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=_g(r);if(!_g(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ra(e);return ra(t)!==null&&s===null?t:e}var na=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;this.apiUrl=(r=t.apiUrl)!=null?r:Vy,this.headers={"Content-Type":"application/json","X-Persona-Version":oa,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:zy(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ha(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Hi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let t=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(r)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Hi}/v1/client/feedback`}async sendFeedback(t){var s,i;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 n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let d=await this.buildPayload(t.messages),u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,g={sessionId:c.sessionId,messages:t.messages.filter(nd).map(y=>{var w,b,A;return{id:y.id,role:y.role,content:(A=(b=(w=y.contentParts)!=null?w:y.llmContent)!=null?b:y.rawContent)!=null?A:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},p=d.clientTools,m=!!(p&&p.length>0),x=m?vg(p):void 0,C=this.clientToolsFingerprintSessionId===c.sessionId,T=m&&C&&this.lastSentClientToolsFingerprint===x,E=!1,M=null,P;for(let y=0;;y++){let b={...g,...m&&(E||!T)&&p?{clientTools:p}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",b),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(b),signal:o.signal}),P.status===409&&y===0&&m){let A=await P.json().catch(()=>null);if((A==null?void 0:A.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}M=A!=null?A:{error:"Chat request failed"}}break}if(!P.ok){let y=M!=null?M:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(P.status===429){let b=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let w=new Error(y.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!P.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(P.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&r({type:"error",error:d}),d}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Hi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var d,u;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||Hi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(nd).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...Ms(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let d=await c({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(t){var a,s;let o={messages:t.slice().filter(nd).sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...Ms(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let d=await c({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let c=i;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return o.current=g,n(g),g},d=u=>o.current?o.current:c(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=d(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,n(u)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var Cr,Wt,ur,Eo;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,d=()=>i+c++,u=V=>{let j=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,he=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,Xe=V.tools?V.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...V,reasoning:j,toolCall:he,tools:Xe}},g=V=>{if(V.role!=="assistant"||V.variant)return!0;let j=Array.isArray(V.contentParts)&&V.contentParts.length>0,he=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||j||he||!!V.stopReason},p=V=>{g(V)&&r({type:"message",message:u(V)})},m=null,x=null,C={current:null},T={current:null},E=!1,M=new Map,P=new Map,y=new Map,w=new Map,b={lastId:null,byStep:new Map},A={lastId:null,byCall:new Map},H=(V,j,he="")=>`${V}::${j}::${he}`,W=(V,j)=>`${V}::${j}::`,k=(V,j,he,Xe)=>{let et=H(V,j,he),qe=y.get(et);if(qe)return qe;let Ne=he?`-${he}`:"",Pt={id:`nested-${V}-${j}${Ne}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...he?{partId:he}:{},agentMetadata:{executionId:Xe,parentToolId:V,parentStepId:j}};return y.set(et,Pt),p(Pt),Pt},N=V=>{if(V==null)return null;try{return String(V)}catch{return null}},q=V=>{var j,he,Xe,et,qe;return N((qe=(et=(Xe=(he=(j=V.stepId)!=null?j:V.step_id)!=null?he:V.step)!=null?Xe:V.parentId)!=null?et:V.flowStepId)!=null?qe:V.flow_step_id)},Z=V=>{var j,he,Xe,et,qe,Ne,Pt;return N((Pt=(Ne=(qe=(et=(Xe=(he=(j=V.callId)!=null?j:V.call_id)!=null?he:V.requestId)!=null?Xe:V.request_id)!=null?et:V.toolCallId)!=null?qe:V.tool_call_id)!=null?Ne:V.stepId)!=null?Pt:V.step_id)},me=o,Ke=!1,Ce=()=>{if(m)return m;let V;return!Ke&&me?(V=me,Ke=!0):me&&T.current?V=`${me}_${T.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},p(m),m},Ie=(V,j)=>{b.lastId=j,V&&b.byStep.set(V,j)},Ue=(V,j)=>{var qe;let he=(qe=V.reasoningId)!=null?qe:V.id,Xe=q(V);if(he){let Ne=String(he);return Ie(Xe,Ne),Ne}if(Xe){let Ne=b.byStep.get(Xe);if(Ne)return b.lastId=Ne,Ne}if(b.lastId&&!j)return b.lastId;if(!j)return null;let et=`reason-${d()}`;return Ie(Xe,et),et},Te=V=>{let j=M.get(V);if(j)return j;let he={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:V,status:"streaming",chunks:[]}};return M.set(V,he),p(he),he},We=(V,j)=>{A.lastId=j,V&&A.byCall.set(V,j)},de=new Set,J=new Map,le=new Set,ge=new Map,ue=V=>{if(!V)return!1;let j=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},G=(V,j)=>{var qe;let he=(qe=V.toolId)!=null?qe:V.id,Xe=Z(V);if(he){let Ne=String(he);return We(Xe,Ne),Ne}if(Xe){let Ne=A.byCall.get(Xe);if(Ne)return A.lastId=Ne,Ne}if(A.lastId&&!j)return A.lastId;if(!j)return null;let et=`tool-${d()}`;return We(Xe,et),et},ce=V=>{let j=P.get(V);if(j)return j;let he={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:V,status:"pending"}};return P.set(V,he),p(he),he},Be=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let j=Number(V);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let he=Date.parse(V);if(!Number.isNaN(he))return he}return Date.now()},ne=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},ee=new Map,ie=new Map,vt=new Map,Lt=new Map,gt=null,_e=(V,j,he)=>{var Pt;let Xe=vt.get(V);Xe||(Xe=[],vt.set(V,Xe));let et=0,qe=Xe.length;for(;et<qe;){let Gt=et+qe>>>1;Xe[Gt].seq<j?et=Gt+1:qe=Gt}((Pt=Xe[et])==null?void 0:Pt.seq)===j?Xe[et]={seq:j,text:he}:Xe.splice(et,0,{seq:j,text:he});let Ne="";for(let Gt=0;Gt<Xe.length;Gt++)Ne+=Xe[Gt].text;return Ne},be=(V,j)=>{let he=ne(j),Xe=ie.get(V.id),et=jy(Xe,he);V.rawContent=et;let qe=ee.get(V.id),Ne=z=>{var oe;let Ht=(oe=V.content)!=null?oe:"";z.trim()!==""&&(Ht.trim().length===0||z.startsWith(Ht)||z.trimStart().startsWith(Ht.trim()))&&(V.content=z)},Pt=()=>{var z;if(qe){let Ht=(z=qe.close)==null?void 0:z.call(qe);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(V.id),ie.delete(V.id),V.streaming=!1,p(V)};if(!qe){Ne(he),Pt();return}let Gt=ra(et);if(Gt!==null&&Gt.trim()!==""){Ne(Gt),Pt();return}let Jt=z=>{var we;let Ht=typeof z=="string"?z:(we=z==null?void 0:z.text)!=null?we:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let oe=qe.getExtractedText();return oe!==null&&oe.trim()!==""?oe:he},Pr;try{Pr=qe.processChunk(et)}catch{Ne(he),Pt();return}if(Pr instanceof Promise){Pr.then(z=>{Ne(Jt(z)),Pt()}).catch(()=>{Ne(he),Pt()});return}Ne(Jt(Pr)),Pt()},Ze=[],Y=!1,pe,Me=()=>{Y||(Y=!0,queueMicrotask(()=>{Y=!1,pe()}))},Je=new Wi((V,j)=>{Ze.push({payloadType:V,payload:j}),Me()}),Ge=null,ke=new Map,je=(Cr=this.config.iterationDisplay)!=null?Cr:"separate";for(pe=()=>{var V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ga,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr,xe,dt,tr,fr,Io,es,Xo,qn,Wo,_,ha,Ho,Bo,Qo,Do,bo,xa,Qs,Yr,Zr,vo,Co,Vn,Jo,Mr,Fo,ya,$n,ba,Js,va,Ys,Ca,mt,ts,po,Vr,Zs,ei,wa,Yo,rs,yn,os,ns,as,ss,$r,Sa,No,Oo,is,ti,ls,ds,zn,ri,oi,ni,ai,si,bn,vn,ii,cs,Cn,li,ps,wn,us;for(let Aa=0;Aa<Ze.length;Aa++){let Ve=Ze[Aa].payloadType,L=Ze[Aa].payload;if(Ve==="reason_start"){let U=(V=Ue(L,!0))!=null?V:`reason-${d()}`,I=Te(U);I.reasoning=(j=I.reasoning)!=null?j:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Xe=I.reasoning.startedAt)!=null?Xe:Be((he=L.startedAt)!=null?he:L.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let U=(qe=(et=Ue(L,!1))!=null?et:Ue(L,!0))!=null?qe:`reason-${d()}`,I=Te(U);I.reasoning=(Ne=I.reasoning)!=null?Ne:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Gt=I.reasoning.startedAt)!=null?Gt:Be((Pt=L.startedAt)!=null?Pt:L.timestamp);let X=(z=(Pr=(Jt=L.reasoningText)!=null?Jt:L.text)!=null?Pr:L.delta)!=null?z:"";if(X&&L.hidden!==!0){let re=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(re!==void 0){let K=_e(U,re,String(X));I.reasoning.chunks=[K]}else I.reasoning.chunks.push(String(X))}if(I.reasoning.status=L.done?"complete":"streaming",L.done){I.reasoning.completedAt=Be((Ht=L.completedAt)!=null?Ht:L.timestamp);let re=(oe=I.reasoning.startedAt)!=null?oe:Date.now();I.reasoning.durationMs=Math.max(0,((we=I.reasoning.completedAt)!=null?we:Date.now())-re)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ve==="reason_complete"){let U=(At=(De=Ue(L,!1))!=null?De:Ue(L,!0))!=null?At:`reason-${d()}`,I=M.get(U);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=Be((ar=L.completedAt)!=null?ar:L.timestamp);let re=(sr=I.reasoning.startedAt)!=null?sr:Date.now();I.reasoning.durationMs=Math.max(0,((wr=I.reasoning.completedAt)!=null?wr:Date.now())-re),I.streaming=!1,p(I)}let X=q(L);X&&b.byStep.delete(X)}else if(Ve==="tool_start"){let U=(Ft=G(L,!0))!=null?Ft:`tool-${d()}`,I=(ot=L.toolName)!=null?ot:L.name;if(ue(I)){de.add(U);continue}let X=ce(U),re=(Dt=X.toolCall)!=null?Dt:{id:U,status:"pending"};re.name=I!=null?I:re.name,re.status="running",L.args!==void 0?re.args=L.args:L.parameters!==void 0&&(re.args=L.parameters),re.startedAt=(Yt=re.startedAt)!=null?Yt:Be((lt=L.startedAt)!=null?lt:L.timestamp),re.completedAt=void 0,re.durationMs=void 0,X.toolCall=re,X.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(X.agentMetadata={executionId:(so=K==null?void 0:K.executionId)!=null?so:L.executionId,iteration:(Rr=K==null?void 0:K.iteration)!=null?Rr:L.iteration}),p(X)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let U=(Ur=(ir=G(L,!1))!=null?ir:G(L,!0))!=null?Ur:`tool-${d()}`;if(de.has(U))continue;let I=ce(U),X=(ko=I.toolCall)!=null?ko:{id:U,status:"running"};X.startedAt=(jr=X.startedAt)!=null?jr:Be((yt=L.startedAt)!=null?yt:L.timestamp);let re=(yo=(zo=(Lo=L.text)!=null?Lo:L.delta)!=null?zo:L.message)!=null?yo:"";re&&(X.chunks=(ht=X.chunks)!=null?ht:[],X.chunks.push(String(re))),X.status="running",I.toolCall=X,I.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(On=I.agentMetadata)!=null?On:{executionId:(Nn=K==null?void 0:K.executionId)!=null?Nn:L.executionId,iteration:(Po=K==null?void 0:K.iteration)!=null?Po:L.iteration}),p(I)}else if(Ve==="tool_complete"){let U=(ga=(qr=G(L,!1))!=null?qr:G(L,!0))!=null?ga:`tool-${d()}`;if(de.has(U)){de.delete(U);continue}let I=ce(U),X=(cn=I.toolCall)!=null?cn:{id:U,status:"running"};X.status="complete",L.result!==void 0&&(X.result=L.result),typeof L.duration=="number"&&(X.duration=L.duration),X.completedAt=Be((jo=L.completedAt)!=null?jo:L.timestamp);let re=(pn=L.duration)!=null?pn:L.executionTime;if(typeof re=="number")X.durationMs=re;else{let Oe=(un=X.startedAt)!=null?un:Date.now();X.durationMs=Math.max(0,((_n=X.completedAt)!=null?_n:Date.now())-Oe)}I.toolCall=X,I.streaming=!1;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(Ct=I.agentMetadata)!=null?Ct:{executionId:(Un=K==null?void 0:K.executionId)!=null?Un:L.executionId,iteration:(fn=K==null?void 0:K.iteration)!=null?fn:L.iteration}),p(I);let Ae=Z(L);Ae&&A.byCall.delete(Ae)}else if(Ve==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let U=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,I=(Gr=U!=null?U:L.toolId)!=null?Gr:`local-${d()}`,X=ce(I),re=L.toolName,K=ea(re),Ae=(Kr=X.toolCall)!=null?Kr:{id:I,status:"pending"};Ae.name=re,Ae.args=L.parameters,Ae.status=K?"running":"complete",Ae.chunks=(Ir=Ae.chunks)!=null?Ir:[],Ae.startedAt=(io=Ae.startedAt)!=null?io:Be((Mt=L.startedAt)!=null?Mt:L.timestamp),K?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=(lo=Ae.completedAt)!=null?lo:Ae.startedAt,X.toolCall=Ae,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(mn=L.executionId)!=null?mn:(Xr=X.agentMetadata)==null?void 0:Xr.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(X)}else if(Ve==="text_start"){if((Go=L.toolContext)!=null&&Go.toolId)continue;let U=L.partId;if(U!==void 0&&T.current!==null&&U!==T.current){let I=m;I&&(I.streaming=!1,p(I),gt=I,m=null,E=!0)}U!==void 0&&(T.current=U)}else if(Ve==="text_end"){if((gn=L.toolContext)!=null&&gn.toolId)continue;let U=m;U&&(U.streaming=!1,p(U),gt=U,m=null,E=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((Nt=(Qr=L.id)!=null?Qr:X.stepId)!=null?Nt:`step-${d()}`),at=L.partId!==void 0&&L.partId!==null?String(L.partId):"",tt=`${X.toolId}::${Oe}`,Bt=w.get(tt);if(at!==""&&Bt!==void 0&&Bt!==""&&Bt!==at){let wt=y.get(H(X.toolId,Oe,Bt));wt&&wt.streaming!==!1&&(wt.streaming=!1,p(wt))}at!==""&&w.set(tt,at);let $t=k(X.toolId,Oe,at,X.executionId),lr=(Ko=(hn=(co=(Wr=L.text)!=null?Wr:L.delta)!=null?co:L.content)!=null?hn:L.chunk)!=null?Ko:"";lr&&($t.content+=String(lr),$t.streaming=!0,p($t)),L.isComplete&&($t.streaming=!1,p($t));continue}let re=L.partId;if(re!==void 0&&T.current!==null&&re!==T.current){let Oe=m;Oe&&(Oe.streaming=!1,p(Oe),gt=Oe,m=null,E=!0)}re!==void 0&&(T.current=re);let K=re!==void 0&&(xn=Lt.get(re))!=null?xn:Ce();re!==void 0&&(K.partId||(K.partId=re),Lt.set(re,K));let Ae=(dt=(xe=(Jr=(Ro=L.text)!=null?Ro:L.delta)!=null?Jr:L.content)!=null?xe:L.chunk)!=null?dt:"";if(Ae){let Oe=typeof L.seq=="number"?L.seq:void 0,at=re!=null?re:K.id,tt=Oe!==void 0?_e(at,Oe,String(Ae)):((tr=ie.get(K.id))!=null?tr:"")+Ae;K.rawContent=tt,ee.has(K.id)||ee.set(K.id,this.createStreamParser());let Bt=ee.get(K.id),$t=tt.trim().startsWith("{")||tt.trim().startsWith("[");if($t&&ie.set(K.id,tt),Bt.__isPlainTextParser===!0){K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K);continue}let wt=Bt.processChunk(tt);if(wt instanceof Promise)wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null&&br.trim()!=="")K.content=br,p(K);else if(!$t&&!tt.trim().startsWith("<")){let Sr=m,Zt=Sr&&Sr.id===K.id?Sr:K;Zt.id===K.id&&(Zt.content=Oe!==void 0?tt:Zt.content+Ae,ie.delete(Zt.id),ee.delete(Zt.id),Zt.rawContent=void 0,p(Zt))}}).catch(()=>{K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K)});else{let Tt=typeof wt=="string"?wt:(fr=wt==null?void 0:wt.text)!=null?fr:null;Tt!==null&&Tt.trim()!==""?(K.content=Tt,p(K)):!$t&&!tt.trim().startsWith("<")&&(K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K))}}if(L.isComplete){let Oe=(es=(Io=L.result)==null?void 0:Io.response)!=null?es:K.content;if(Oe){let at=ie.get(K.id),tt=at!=null?at:ne(Oe);K.rawContent=tt;let Bt=ee.get(K.id),$t=null,lr=!1;if(Bt&&($t=Bt.getExtractedText(),$t===null&&($t=ra(tt)),$t===null)){let wt=Bt.processChunk(tt);wt instanceof Promise?(lr=!0,wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null){let Sr=m;Sr&&Sr.id===K.id&&(Sr.content=br,Sr.streaming=!1,ee.delete(Sr.id),ie.delete(Sr.id),p(Sr))}})):$t=typeof wt=="string"?wt:(Xo=wt==null?void 0:wt.text)!=null?Xo:null}if(!lr){$t!==null&&$t.trim()!==""?K.content=$t:ie.has(K.id)||(K.content=ne(Oe));let wt=ee.get(K.id);if(wt){let Tt=(qn=wt.close)==null?void 0:qn.call(wt);Tt instanceof Promise&&Tt.catch(()=>{}),ee.delete(K.id)}ie.delete(K.id),K.streaming=!1,p(K)}}}}else if(Ve==="step_complete"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((_=(Wo=L.id)!=null?Wo:X.stepId)!=null?_:"");if(Oe){let at=W(X.toolId,Oe);for(let[tt,Bt]of y)tt.startsWith(at)&&Bt.streaming!==!1&&(Bt.streaming=!1,p(Bt));w.delete(`${X.toolId}::${Oe}`)}continue}let re=L.stopReason;if(E){if(m!==null){let tt=m;re&&(tt.stopReason=re),ee.delete(tt.id),ie.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,p(tt))}let Oe=(ha=L.result)==null?void 0:ha.response,at=gt;at&&(re&&(at.stopReason=re),Oe!=null?be(at,Oe):(ee.delete(at.id),ie.delete(at.id))),gt=null;continue}let K=(Ho=L.result)==null?void 0:Ho.response,Ae=Ce();if(re&&(Ae.stopReason=re),K!=null){let Oe=ee.get(Ae.id),at=!1,tt=!1;if(Oe){let Bt=Oe.getExtractedText(),$t=ie.get(Ae.id),lr=$t!=null?$t:ne(K);if(Ae.rawContent=lr,Bt!==null&&Bt.trim()!=="")Ae.content=Bt,at=!0;else{let wt=ra(lr);if(wt!==null)Ae.content=wt,at=!0;else{let Tt=Oe.processChunk(lr);if(Tt instanceof Promise)tt=!0,Tt.then(br=>{var Sr;let Hr=typeof br=="string"?br:(Sr=br==null?void 0:br.text)!=null?Sr:null;if(Hr!==null&&Hr.trim()!==""){let Zt=m;Zt&&Zt.id===Ae.id&&(Zt.content=Hr,Zt.streaming=!1,ee.delete(Zt.id),ie.delete(Zt.id),p(Zt))}else{let Zt=Oe.getExtractedText(),uo=m;uo&&uo.id===Ae.id&&(Zt!==null&&Zt.trim()!==""?uo.content=Zt:ie.has(uo.id)||(uo.content=ne(K)),uo.streaming=!1,ee.delete(uo.id),ie.delete(uo.id),p(uo))}});else{let br=typeof Tt=="string"?Tt:(Bo=Tt==null?void 0:Tt.text)!=null?Bo:null;if(br!==null&&br.trim()!=="")Ae.content=br,at=!0;else{let Hr=Oe.getExtractedText();Hr!==null&&Hr.trim()!==""&&(Ae.content=Hr,at=!0)}}}}}if(!tt){if(!Ae.rawContent){let Bt=ie.get(Ae.id);Ae.rawContent=Bt!=null?Bt:ne(K)}if(!at&&!ie.has(Ae.id)&&(Ae.content=ne(K)),Oe){let Bt=(Qo=Oe.close)==null?void 0:Qo.call(Oe);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}}else ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}else if(Ve==="flow_complete"){let U=(Do=L.result)==null?void 0:Do.response;if(E){if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(U!=null){let I=Ce(),X=ie.get(I.id),re=X!=null?X:ne(U);I.rawContent=re;let K=ne(U),Ae=ee.get(I.id);if(Ae){let tt=ra(re);if(tt!==null)K=tt;else{let Bt=Ae.processChunk(re);Bt instanceof Promise&&Bt.then(lr=>{var Tt;let wt=typeof lr=="string"?lr:(Tt=lr==null?void 0:lr.text)!=null?Tt:null;wt!==null&&(I.content=wt,I.streaming=!1,p(I))});let $t=Ae.getExtractedText();$t!==null&&(K=$t)}}ee.delete(I.id),ie.delete(I.id);let Oe=K!==I.content,at=I.streaming!==!1;Oe&&(I.content=K),I.streaming=!1,(Oe||at)&&p(I)}else if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}r({type:"status",status:"idle"})}else if(Ve==="agent_start")Ge={executionId:L.executionId,agentId:(bo=L.agentId)!=null?bo:"virtual",agentName:(xa=L.agentName)!=null?xa:"",status:"running",currentIteration:0,maxTurns:(Qs=L.maxTurns)!=null?Qs:1,startedAt:Be(L.startedAt)};else if(Ve==="agent_iteration_start"){if(Ge&&(Ge.currentIteration=L.iteration),je==="separate"&&L.iteration>1){let U=m;U&&(U.streaming=!1,p(U),ke.set(L.iteration-1,U),m=null)}}else if(Ve==="agent_turn_start")x=null;else if(Ve==="agent_turn_delta"){if(L.contentType==="text"){let U=Ce();U.content+=(Yr=L.delta)!=null?Yr:"",U.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:Ge==null?void 0:Ge.agentName},x=U,p(U)}else if(L.contentType==="thinking"){let U=(Zr=L.turnId)!=null?Zr:`agent-think-${L.iteration}`,I=Te(U);I.reasoning=(vo=I.reasoning)!=null?vo:{id:U,status:"streaming",chunks:[]},I.reasoning.chunks.push((Co=L.delta)!=null?Co:""),I.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},p(I)}else if(L.contentType==="tool_input"){let U=(Vn=L.toolCallId)!=null?Vn:A.lastId;if(U){let I=P.get(U);I!=null&&I.toolCall&&(I.toolCall.chunks=(Jo=I.toolCall.chunks)!=null?Jo:[],I.toolCall.chunks.push((Mr=L.delta)!=null?Mr:""),p(I))}}}else if(Ve==="agent_turn_complete"){let U=L.turnId;if(U){let re=M.get(U);if(re!=null&&re.reasoning){re.reasoning.status="complete",re.reasoning.completedAt=Be(L.completedAt);let K=(Fo=re.reasoning.startedAt)!=null?Fo:Date.now();re.reasoning.durationMs=Math.max(0,((ya=re.reasoning.completedAt)!=null?ya:Date.now())-K),re.streaming=!1,p(re)}}let I=L.stopReason,X=m!=null?m:x;if(I&&X!==null){let re=L.turnId;(!re||(($n=X.agentMetadata)==null?void 0:$n.turnId)===re)&&(X.stopReason=I,p(X))}}else if(Ve==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let U=(ba=L.toolCallId)!=null?ba:`agent-tool-${d()}`;We(Z(L),U);let I=ce(U),X=(Js=I.toolCall)!=null?Js:{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};X.name=(Ys=(va=L.toolName)!=null?va:L.name)!=null?Ys:X.name,X.status="running",L.parameters!==void 0&&(X.args=L.parameters),X.startedAt=Be((Ca=L.startedAt)!=null?Ca:L.timestamp),I.toolCall=X,I.streaming=!0,I.agentMetadata={executionId:L.executionId,iteration:L.iteration},p(I)}else if(Ve==="agent_tool_delta"){let U=(mt=L.toolCallId)!=null?mt:A.lastId;if(U){let I=(ts=P.get(U))!=null?ts:ce(U);I.toolCall&&(I.toolCall.chunks=(po=I.toolCall.chunks)!=null?po:[],I.toolCall.chunks.push((Vr=L.delta)!=null?Vr:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ve==="agent_tool_complete"){let U=(Zs=L.toolCallId)!=null?Zs:A.lastId;if(U){let I=(ei=P.get(U))!=null?ei:ce(U);if(I.toolCall){I.toolCall.status="complete",L.result!==void 0&&(I.toolCall.result=L.result),typeof L.executionTime=="number"&&(I.toolCall.durationMs=L.executionTime),I.toolCall.completedAt=Be((wa=L.completedAt)!=null?wa:L.timestamp),I.streaming=!1,p(I);let X=Z(L);X&&A.byCall.delete(X)}}}else if(Ve==="agent_media"){let U=Array.isArray(L.media)?L.media:[],I=[];for(let X of U){if(!X||typeof X!="object")continue;let re=X,K=typeof re.type=="string"?re.type:void 0,Ae=typeof re.mediaType=="string"?re.mediaType.toLowerCase():"",Oe=null,at="";if(K==="media"){let tt=typeof re.data=="string"?re.data:void 0;if(!tt)continue;at=Ae.length>0?Ae:"application/octet-stream",Oe=`data:${at};base64,${tt}`}else if(K==="image-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else if(K==="file-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else continue;if(Oe)if(K==="image-url"||at.startsWith("image/"))I.push({type:"image",image:Oe,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))I.push({type:"audio",audio:Oe,mimeType:at});else if(at.startsWith("video/"))I.push({type:"video",video:Oe,mimeType:at});else{let tt=at||"application/octet-stream";I.push({type:"file",data:Oe,mimeType:tt,filename:$y(tt)})}}if(I.length>0){let X=d(),re=L.toolCallId,Ae={id:`agent-media-${typeof re=="string"&&re.length>0?`${re}-${X}`:String(X)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:X,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(Ae);let Oe=m;Oe&&(Oe.streaming=!1,p(Oe)),m=null,C.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let U=`agent-reflection-${L.executionId}-${L.iteration}`,I={id:U,role:"assistant",content:(Yo=L.reflection)!=null?Yo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:d(),reasoning:{id:U,status:"complete",chunks:[(rs=L.reflection)!=null?rs:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(I)}else if(Ve==="agent_complete"){Ge&&(Ge.status=L.success?"complete":"error",Ge.completedAt=Be(L.completedAt),Ge.stopReason=L.stopReason);let U=m;U&&(U.streaming=!1,p(U)),r({type:"status",status:"idle"})}else if(Ve==="agent_error"){let U=typeof L.error=="string"?L.error:(os=(yn=L.error)==null?void 0:yn.message)!=null?os:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):r({type:"error",error:new Error(U)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let U=(ns=L.approvalId)!=null?ns:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(as=Ge==null?void 0:Ge.agentId)!=null?as:"virtual",executionId:($r=(ss=L.executionId)!=null?ss:Ge==null?void 0:Ge.executionId)!=null?$r:"",toolName:(Sa=L.toolName)!=null?Sa:"",toolType:L.toolType,description:(Oo=L.description)!=null?Oo:`Execute ${(No=L.toolName)!=null?No:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="step_await"&&L.awaitReason==="approval_required"){let U=(is=L.approvalId)!=null?is:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(ti=Ge==null?void 0:Ge.agentId)!=null?ti:"virtual",executionId:(ds=(ls=L.executionId)!=null?ls:Ge==null?void 0:Ge.executionId)!=null?ds:"",toolName:(zn=L.toolName)!=null?zn:"",toolType:L.toolType,description:(oi=L.description)!=null?oi:`Execute ${(ri=L.toolName)!=null?ri:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="agent_approval_complete"){let U=L.approvalId;if(U){let X={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:(ni=L.decision)!=null?ni:"approved",agentId:(ai=Ge==null?void 0:Ge.agentId)!=null?ai:"virtual",executionId:(bn=(si=L.executionId)!=null?si:Ge==null?void 0:Ge.executionId)!=null?bn:"",toolName:(vn=L.toolName)!=null?vn:"",description:(ii=L.description)!=null?ii:"",resolvedAt:Date.now()}};p(X)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let U=L.artifactType,I=String(L.id),X=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:I,artifactType:U,title:X,component:typeof L.component=="string"?L.component:void 0}),ge.set(I,{markdown:"",title:X}),!le.has(I)){le.add(I);let re={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:X,artifactType:U,status:"streaming"}})};J.set(I,re),p(re)}}else if(Ve==="artifact_delta"){let U=String(L.id),I=typeof L.delta=="string"?L.delta:String((cs=L.delta)!=null?cs:"");r({type:"artifact_delta",id:U,artDelta:I});let X=ge.get(U);X&&(X.markdown+=I)}else if(Ve==="artifact_update"){let U=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:U,component:typeof L.component=="string"?L.component:void 0})}else if(Ve==="artifact_complete"){let U=String(L.id);r({type:"artifact_complete",id:U});let I=J.get(U);if(I){I.streaming=!1;try{let X=JSON.parse((Cn=I.rawContent)!=null?Cn:"{}");if(X.props){X.props.status="complete";let re=ge.get(U);re!=null&&re.markdown&&(X.props.markdown=re.markdown)}I.rawContent=JSON.stringify(X)}catch{}ge.delete(U),p(I),J.delete(U)}}}else if(Ve==="transcript_insert"){let U=L.message;if(!U||typeof U!="object")continue;let I=String((li=U.id)!=null?li:`msg-${d()}`),X=U.role,K={id:I,role:X==="user"?"user":X==="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:d()};if(p(K),K.rawContent)try{let Ae=JSON.parse(K.rawContent),Oe=(ps=Ae==null?void 0:Ae.props)==null?void 0:ps.artifactId;typeof Oe=="string"&&le.add(Oe)}catch{}m=null,C.current=null,ee.delete(I),ie.delete(I)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let U=null;if(L.error instanceof Error)U=L.error;else if(Ve==="dispatch_error"){let I=(wn=L.message)!=null?wn:L.error;I!=null&&I!==""&&(U=new Error(String(I)))}else if(Ve==="step_error"||Ve==="flow_error"){let I=L.error;typeof I=="string"&&I!==""?U=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(U=new Error(String((us=I.message)!=null?us:I)))}else Ve==="error"&&L.error!=null&&L.error!==""&&(U=new Error(String(L.error)));if(U){r({type:"error",error:U});let I=m;I&&I.streaming&&(I.streaming=!1,p(I)),r({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:V,value:j}=await n.read();if(V)break;s+=a.decode(j,{stream:!0});let he=s.split(`
|
|
58
11
|
|
|
59
|
-
`);s=(
|
|
60
|
-
`),ze="message",lt="";for(let or of qe)or.startsWith("event:")?ze=or.replace("event:","").trim():or.startsWith("data:")&&(lt+=or.replace("data:","").trim());if(!lt)continue;let Mt;try{Mt=JSON.parse(lt)}catch(or){t({type:"error",error:or instanceof Error?or:new Error("Failed to parse chat stream payload")});continue}let Dt=ze!=="message"?ze:(Yr=Mt.type)!=null?Yr:"message";if((zr=this.onSSEEvent)==null||zr.call(this,Dt,Mt),this.parseSSEEvent){h.current=m;let or=await this.handleCustomSSEEvent(Mt,t,h,p,l,T);if(h.current&&h.current!==m&&(m=h.current),or)continue}Pt.push(Dt,Mt),he()}}Pt.flushPending(),he(),Pt.destroy()}};function tx(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${r}_${e}`}function Ja(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${r}_${e}`}function ba(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${r}_${e}`}var ll="[Image]";function rx(r){return typeof r=="string"?[{type:"text",text:r}]:r}function ox(r){return typeof r=="string"?r:r.filter(e=>e.type==="text").map(e=>e.text).join("")}function nx(r){return typeof r=="string"?!1:r.some(e=>e.type==="image")}function ax(r){return typeof r=="string"?[]:r.filter(e=>e.type==="image")}function Qs(r){return{type:"text",text:r}}function sx(r,e){return{type:"image",image:r,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function ix(r){return new Promise((e,t)=>{let o=new FileReader;o.onload=()=>{let n=o.result;e({type:"image",image:n,mimeType:r.type,alt:r.name})},o.onerror=()=>t(new Error("Failed to read file")),o.readAsDataURL(r)})}function lx(r,e=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var dx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vv=["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"],Tn=[...dx,...vv];function Cv(r){return dx.includes(r)||r.startsWith("image/")}function dl(r){return Cv(r.type)}async function cx(r){return new Promise((e,t)=>{let o=new FileReader;o.onload=()=>{let n=o.result;dl(r)?e({type:"image",image:n,mimeType:r.type,alt:r.name}):e({type:"file",data:n,mimeType:r.type,filename:r.name})},o.onerror=()=>t(new Error("Failed to read file")),o.readAsDataURL(r)})}function px(r,e=Tn,t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${r.type}". Accepted types: ${e.join(", ")}`}}function wv(r){let e=r.split(".");return e.length>1?e.pop().toLowerCase():""}function ux(r,e){let t=wv(e).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"}[r]||t||"FILE"}var cl=class{constructor(e=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=e}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let o=t.AudioContext||t.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let o=this.ensureContext(),n=this.pcmToFloat32(t),a=o.createBuffer(1,n.length,this.sampleRate);a.getChannelData(0).set(n);let s=o.createBufferSource();s.buffer=a,s.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=a.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,s.onended=()=>{let d=this.activeSources.indexOf(s);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.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(e){this.finishedCallbacks.push(e)}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 e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),o=new Float32Array(t),n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=0;a<t;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var pl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,t,o,n,a){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(t),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let s=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(s);let i=0;for(let u=0;u<s.length;u++)i+=s[u]*s[u];let d=Math.sqrt(i/s.length);(o==="silence"?d<n.threshold:d>=n.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=n.duration&&(this.fired=!0,a()):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 Ys=class{constructor(e){this.config=e;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 pl;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(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var e,t,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let n=this.w;if(!n||!n.location)throw new Error("Window object or location not available");let a=n.location.protocol==="https:"?"wss:":"ws:",s=(e=this.config)==null?void 0:e.host,i=(t=this.config)==null?void 0:t.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!s)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${a}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${a}//${s}/ws/agents/${i}/voice?token=...`,f=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((p,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let y=!1,h=M=>{y||(y=!0,clearTimeout(T),m(new Error(M)))},T=setTimeout(()=>h("WebSocket connection timed out."+f),1e4);this.ws.addEventListener("open",()=>{y||(y=!0,clearTimeout(T),p())},{once:!0}),this.ws.addEventListener("error",()=>{h("WebSocket connection failed to "+u+"."+f)},{once:!0}),this.ws.addEventListener("close",M=>{if(!M.wasClean&&!y){let k=M.code!==1006?` (code ${M.code})`:"";h("WebSocket connection failed"+k+"."+f)}},{once:!0})}),this.sendHeartbeat()}catch(n){throw this.ws=null,this.errorCallbacks.forEach(a=>a(n)),this.statusCallbacks.forEach(a=>a("error")),n}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let t=JSON.parse(e.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var t,o;switch(e.type){case"session_config":e.interruptionMode&&(this.interruptionMode=e.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(n=>n({text:e.response.agentResponseText||e.response.transcript,transcript:e.response.transcript,audio:e.response.audio,confidence:.95,provider:"runtype"})),(t=e.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.playAudio(e.response.audio).catch(n=>this.errorCallbacks.forEach(a=>a(n instanceof Error?n:new Error(String(n)))))):(o=e.response.audio)!=null&&o.base64;break;case"audio_end":if(e.requestId&&e.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(n=>n("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(n=>n(new Error(e.error))),this.statusCallbacks.forEach(n=>n("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(e){e.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new cl(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(e))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(e=>e("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 e,t,o,n;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 a=this.w;this.audioContext||(this.audioContext=new(a.AudioContext||a.webkitAudioContext));let s=this.audioContext,i=(t=(e=this.config)==null?void 0:e.pauseDuration)!=null?t:2e3,d=(n=(o=this.config)==null?void 0:o.silenceThreshold)!=null?n:.01;this.vad.start(s,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(p=>p("processing")),this.processingStartCallbacks.forEach(p=>p());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",f=new Blob(this.audioChunks,{type:u});await this.sendAudio(f),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(a){throw this.errorCallbacks.forEach(s=>s(a)),this.statusCallbacks.forEach(s=>s("error")),a}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(e=>e("idle"))}async startBargeInMonitoring(){var a,s;if(this.interruptionMode!=="barge-in")return;let e=this.w;if(!this.mediaStream&&e&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&e&&(this.audioContext=new(e.AudioContext||e.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,o=(s=(a=this.config)==null?void 0:a.silenceThreshold)!=null?s:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(t=>t(e instanceof Error?e:new Error(String(e))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(e){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(e),n=this.getFormatFromMimeType(e.type),a=this.generateRequestId();this.currentRequestId=a,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:n,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:a}))}catch(o){this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error"))}}getFormatFromMimeType(e){return e.includes("wav")?"wav":e.includes("mpeg")||e.includes("mp3")?"mp3":"webm"}blobToBase64(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let s=n.result.split(",")[1];t(s)},n.onerror=o,n.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let t=atob(e.base64),o=new Uint8Array(t.length);for(let l=0;l<t.length;l++)o[l]=t.charCodeAt(l);let n=e.format||"mp3",a=n==="mp3"?"audio/mpeg":`audio/${n}`,s=new Blob([o],{type:a}),i=URL.createObjectURL(s),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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onProcessingStart(e){this.processingStartCallbacks.push(e)}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(e=>e.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(e=>e("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var va=class{constructor(e={}){this.config=e;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(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ca(r){switch(r.type){case"runtype":if(!r.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(r.runtype);case"browser":if(!va.isSupported())throw new Error("Browser speech recognition not supported");return new va(r.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${r.type}`)}}function ul(r){if((r==null?void 0:r.type)==="runtype"&&r.runtype)return Ca({type:"runtype",runtype:r.runtype});if(va.isSupported())return Ca({type:"browser",browser:(r==null?void 0:r.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Js(r){try{return ul(r),!0}catch{return!1}}var Av=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Sv(r,e){return Av.some(t=>r[t]!==e[t])}function fx(r,e){let t=r instanceof Error?r:new Error(String(r));if(typeof e=="string")return e;if(typeof e=="function")return e(t);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${o}
|
|
12
|
+
`);s=(Wt=he.pop())!=null?Wt:"";for(let Xe of he){let et=Xe.split(`
|
|
13
|
+
`),qe="message",Ne="";for(let Jt of et)Jt.startsWith("event:")?qe=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(Ne+=Jt.replace("data:","").trim());if(!Ne)continue;let Pt;try{Pt=JSON.parse(Ne)}catch(Jt){r({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Gt=qe!=="message"?qe:(ur=Pt.type)!=null?ur:"message";if((Eo=this.onSSEEvent)==null||Eo.call(this,Gt,Pt),this.parseSSEEvent){C.current=m;let Jt=await this.handleCustomSSEEvent(Pt,r,C,p,d,T);if(C.current&&C.current!==m&&(m=C.current),Jt)continue}Je.push(Gt,Pt),pe()}}Je.flushPending(),pe(),Je.destroy()}};function Ug(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Oa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Bi="[Image]";function qg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Vg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function $g(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function zg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ks(e){return{type:"text",text:e}}function jg(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 Gg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Kg(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Xg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Gy=["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"],an=[...Xg,...Gy];function Ky(e){return Xg.includes(e)||e.startsWith("image/")}function Di(e){return Ky(e.type)}async function Qg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;Di(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Jg(e,t=an,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Xy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Yg(e,t){let r=Xy(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]||r||"FILE"}var Fi=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),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.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Zg=16e3,Qy=24e3,Jy=4096,Yy=1380533830;function Zy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Yy?new Uint8Array(e,44):new Uint8Array(e)}function eb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ls=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Zg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){d.getTracks().forEach(C=>C.stop());return}this.mediaStream=d;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:Zg});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let p=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new Fi(Qy);if(n!==this.callGeneration){p.destroy(),d.getTracks().forEach(C=>C.stop()),g.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${eb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,d,x,n))},x.onmessage=C=>this.handleMessage(C,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=C=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(C.code!==1e3){let T=C.code?` (code ${C.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(d){throw this.cleanup(),this.emitError(d),this.emitStatus("error"),d}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(Jy,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let u=0;u<c.length;u++){let g=Math.max(-1,Math.min(1,c[u]));d[u]=g<0?g*32768:g*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=Zy(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var sa=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,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}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 Rn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ls(e.runtype);case"browser":if(!sa.isSupported())throw new Error("Browser speech recognition not supported");return new sa(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ni(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Rn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Rn({type:"runtype",runtype:e.runtype});if(sa.isSupported())return Rn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ps(e){try{return Ni(e),!0}catch{return!1}}function _a(e){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var In=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):_a(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var d,u;let c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(u=r.onError)==null||u.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ia=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function ad(e){if(!e)return"";let t=tb(e);return eh(t!==null?t:e)}function tb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function eh(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
14
|
+
`),t=t.replace(/\n{2,}/g,`
|
|
15
|
+
`),t.trim()}var sd=null,th=e=>{sd=e},id=()=>sd?sd():import("./runtype-tts-entry");var rb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ob(e,t){return rb.some(r=>e[r]!==t[r])}function rh(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="Sorry: 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 r.message?`${o}
|
|
61
16
|
|
|
62
|
-
_Details: ${t.message}_`:o}var Zs=r=>({isError:!0,content:[{type:"text",text:r}]}),mx=(r,e="WebMCP tool execution failed.")=>r instanceof Error&&r.message?r.message:typeof r=="string"&&r?r:e,gx=r=>ga(r)||r===en,Za=class r{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=e=>{var t,o,n,a,s,i,d,l,u,f;if(e.type==="message"){this.upsertMessage(e.message);let p=e.message.toolCall,m=!!(p!=null&&p.name)&&(ga(p.name)||p.name===en&&((o=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:o.enabled)!==!1);((n=e.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(a=e.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(s=e.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(f=(u=this.callbacks).onError)==null||f.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var o,n;this.messages=[...(o=e.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ya(e),this.wireDefaultWebMcpConfirm();for(let a of(n=e.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Js((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,o;return(o=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?o:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(e){var t,o,n;try{let a=e||this.getVoiceConfigFromConfig();if(!a)throw new Error("Voice configuration not provided");this.voiceProvider=Ca(a);let s=(t=this.config.voiceRecognition)!=null?t:{},i=(o=s.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(n=s.processingErrorText)!=null?n:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,f,p,m,y,h;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=l.transcript)!=null&&f.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((p=l.text)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let T=(h=this.pendingVoiceAssistantMessageId)!=null?h:(y=[...this.messages].reverse().find(M=>M.role==="assistant"))==null?void 0:y.id;T&&this.ttsSpokenMessageIds.add(T)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,f;this.voiceStatus=l,this.voiceActive=l==="listening",(f=(u=this.callbacks).onVoiceStatusChanged)==null||f.call(u,l)}),this.voiceProvider.connect()}catch(a){console.error("Failed to setup voice:",a)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,o,n,a,s,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=e.runtype)==null?void 0:o.agentId)||"",clientToken:((n=e.runtype)==null?void 0:n.clientToken)||"",host:(a=e.runtype)==null?void 0:a.host,voiceId:(s=e.runtype)==null?void 0:s.voiceId,pauseDuration:(i=e.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=e.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=e.browser)==null?void 0:l.language)||"en-US",continuous:(u=e.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(t=(e=this.callbacks).onError)==null||t.call(e,o instanceof Error?o:new Error(String(o))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Sv(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=t,this.client=new ya(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:f}=e,m={id:s!=null?s:t==="user"?Ja():t==="assistant"?ba():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let o of e){let{role:n,content:a,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:u,streaming:f=!1,voiceProcessing:p,rawContent:m}=o,h={id:d!=null?d:n==="user"?Ja():n==="assistant"?ba():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};t.push(h)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:d}=e,l={text:n,component:t,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var l,u,f,p,m;let o=e.trim();if(!o&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let n=Ja(),a=ba(),s={id:n,role:"user",content:o||ll,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(s),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:a},this.handleEvent)}catch(y){let h=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!h){let T=fx(y,this.config.errorMessage);if(T){let M={id:a,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(y instanceof Error?(f=(u=this.callbacks).onError)==null||f.call(u,y):(m=(p=this.callbacks).onError)==null||m.call(p,new Error(String(y))))}}async continueConversation(){var n,a,s,i,d;if(this.streaming)return;(n=this.abortController)==null||n.abort();let e=ba();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let f=fx(l,this.config.errorMessage);if(f){let p={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(p)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(e,t){var n,a,s;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(s=e.description)!=null?s:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${t.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(e,t){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let n=this.messages.find(a=>a.id===e);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:t,resolvedAt:Date.now()}}),o(t==="approved")}async resolveApproval(e,t,o){var u,f,p,m,y;let n=`approval-${e.id}`,a={...e,status:t,resolvedAt:Date.now()},s=this.messages.find(h=>h.id===n),i={id:n,role:"assistant",content:"",createdAt:(u=s==null?void 0:s.createdAt)!=null?u:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let h;if(l?h=await l({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,o):h=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),h){let T=null;if(h instanceof Response){if(!h.ok){let M=await h.json().catch(()=>null);throw new Error((p=M==null?void 0:M.error)!=null?p:`Approval request failed: ${h.status}`)}T=h.body}else h instanceof ReadableStream&&(T=h);T?await this.connectStream(T,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.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(h){let T=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(y=(m=this.callbacks).onError)==null||y.call(m,h instanceof Error?h:new Error(String(h)))}}persistAskUserQuestionProgress(e,t){let o=this.messages.find(n=>n.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let o=this.messages.find(n=>n.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var u,f,p,m,y,h,T,M,k,L,x,w;let o=this.messages.find(v=>v.id===e.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let n=(f=e.agentMetadata)==null?void 0:f.executionId,a=(p=e.toolCall)==null?void 0:p.name;if(!n||!a){(y=(m=this.callbacks).onError)==null||y.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof t=="string"?void 0:t;if(s===void 0&&typeof t=="string"){let v=(h=e.toolCall)==null?void 0:h.args,E=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(E.length===1){let H=typeof((T=E[0])==null?void 0:T.question)=="string"?E[0].question:"";H&&(s={[H]:t})}}this.markAskUserQuestionResolved(e,s),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(k=e.toolCall)==null?void 0:k.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof t=="string"?t:Object.entries(t).map(([E,H])=>`${E}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};l.forEach((E,H)=>{let I=typeof(E==null?void 0:E.question)=="string"?E.question:"";if(!I)return;let P=v[I],z=Array.isArray(P)?P.join(", "):typeof P=="string"?P:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:z||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:t});if(!v.ok){let E=await v.json().catch(()=>null);throw new Error((L=E==null?void 0:E.error)!=null?L:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(w=(x=this.callbacks).onError)==null||w.call(x,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(e){var a,s;let t=(a=e.agentMetadata)==null?void 0:a.executionId,o=(s=e.toolCall)==null?void 0:s.id;if(!t||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let n=this.webMcpAwaitBatches.get(t);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=t;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){var n,a;let t=this.messages.find(s=>s.id===e.id),o=[(n=t==null?void 0:t.toolCall)==null?void 0:n.startedAt,(a=e.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(e){var o,n;if(((o=e.toolCall)==null?void 0:o.name)!==en)return!1;let t=this.messages.find(a=>a.id===e.id);return((n=(t!=null?t:e).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,o,n=Date.now(),a){this.messages.some(s=>s.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...a},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,l,u,f;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(t.map(async p=>{var w,v,E,H,I,P,z;let m=(w=p.toolCall)==null?void 0:w.name,y=(v=p.toolCall)==null?void 0:v.id;if(!m||!y)return null;let h=`${e}:${y}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(h),o.push(h);let T=this.markWebMcpToolRunning(p),M=(H=(E=p.agentMetadata)==null?void 0:E.webMcpToolCallId)!=null?H:m;if(m===en)return{dedupeKey:h,resumeKey:M,output:Ud(),toolMessage:p,startedAt:T,completedAt:Date.now()};let k=new AbortController;this.webMcpResolveControllers.add(k),n.push(k);let L=this.client.executeWebMcpToolCall(m,(I=p.toolCall)==null?void 0:I.args,k.signal),x;if(!L)x={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{x=await L}catch(j){let ie=j instanceof Error&&(j.name==="AbortError"||j.message.includes("aborted")||j.message.includes("abort"));return ie||(z=(P=this.callbacks).onError)==null||z.call(P,j instanceof Error?j:new Error(String(j))),this.markWebMcpToolComplete(p,Zs(ie?"Aborted by cancel()":mx(j)),T),this.webMcpInflightKeys.delete(h),null}return k.signal.aborted?(this.markWebMcpToolComplete(p,Zs("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(h),null):{dedupeKey:h,resumeKey:M,output:x,toolMessage:p,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=s.filter(y=>y!==null),i.length===0)return;let p={};for(let y of i)p[y.resumeKey]=y.output;let m=await this.client.resumeFlow(e,p,{signal:a.signal});if(!m.ok){let y=await m.json().catch(()=>null);throw new Error((d=y==null?void 0:y.error)!=null?d:`Resume failed: ${m.status}`)}for(let y of i)this.webMcpResolvedKeys.add(y.dedupeKey),this.markWebMcpToolComplete(y.toolMessage,y.output,y.startedAt,y.completedAt,((l=y.toolMessage.toolCall)==null?void 0:l.name)===en?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(f=(u=this.callbacks).onError)==null||f.call(u,p instanceof Error?p:new Error(String(p)));else for(let y of i)this.markWebMcpToolComplete(y.toolMessage,Zs("Aborted by cancel()"),y.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of n)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var y,h,T,M,k,L,x,w,v,E,H,I;let t=(y=e.agentMetadata)==null?void 0:y.executionId,o=(h=e.toolCall)==null?void 0:h.name,n=(T=e.toolCall)==null?void 0:T.id;if(!t){(k=(M=this.callbacks).onError)==null||k.call(M,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!n){let P=`${t}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(P)||this.webMcpResolvedKeys.has(P))return;this.webMcpInflightKeys.add(P);try{await this.resumeWithToolOutput(t,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(P)}catch(z){(x=(L=this.callbacks).onError)==null||x.call(L,z instanceof Error?z:new Error(String(z)))}finally{this.webMcpInflightKeys.delete(P)}return}let a=`${t}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=o===en,u=(w=e.toolCall)==null?void 0:w.args,f=l?null:this.client.executeWebMcpToolCall(o,u,d),p="execute",m=s;try{let P;if(l?P=Ud():f?P=await f:P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Zs("Aborted by cancel()"),s);return}let z=(E=(v=e.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?E:o;p="resume",await this.resumeWithToolOutput(t,z,P,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(e,P,s,m,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(P){let z=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));(p==="execute"||z||d.aborted)&&this.markWebMcpToolComplete(e,Zs(z||d.aborted?"Aborted by cancel()":mx(P)),s),z||(I=(H=this.callbacks).onError)==null||I.call(H,P instanceof Error?P:new Error(String(P)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,o,n){var s,i;let a=await this.client.resumeFlow(e,{[t]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let d=await a.json().catch(()=>null);throw new Error((s=d==null?void 0:d.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var n;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let a={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,a),this.selectedArtifactId=t,this.emitArtifactsState(),a}let o={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(n=e.props)!=null?n:{}};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,o;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=o.content;n.trim()&&this.speak(n,e)}speak(e,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(e),a=o.getVoices();if(t.voice){let s=a.find(i=>i.name===t.voice);s&&(n.voice=s)}else a.length>0&&(n.voice=t.pickVoice?t.pickVoice(a):r.pickBestVoice(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),setTimeout(()=>o.speak(n),50)}static pickBestVoice(e){var o;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let a=e.find(s=>s.name===n);if(a)return a}return(o=e.find(n=>n.lang.startsWith("en")))!=null?o:e[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),o=this.messages.findIndex(n=>n.id===t.id);if(o===-1){this.appendMessage(t);return}this.messages=this.messages.map((n,a)=>{var u,f,p,m,y,h,T,M,k,L,x,w,v,E,H;if(a!==o)return n;let s={...n,...t};if(((u=n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=n.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&t.agentMetadata&&(s.agentMetadata={...(p=s.agentMetadata)!=null?p:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&t.approval&&n.approval.id===t.approval.id){let I=n.approval,P=t.approval;s.approval={...I,...P,executionId:P.executionId||I.executionId,toolName:P.toolName||I.toolName,description:P.description||I.description,toolType:(m=P.toolType)!=null?m:I.toolType,reason:(y=P.reason)!=null?y:I.reason,parameters:(h=P.parameters)!=null?h:I.parameters}}let i=(T=t.toolCall)==null?void 0:T.name,d=(M=t.agentMetadata)==null?void 0:M.executionId,l=(k=t.toolCall)==null?void 0:k.id;if(i&&gx(i)&&d&&l&&((L=t.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let I=`${d}:${l}`,P=this.webMcpInflightKeys.has(I),z=this.webMcpResolvedKeys.has(I),j=(x=n.toolCall)==null?void 0:x.name,ie=((w=n.agentMetadata)==null?void 0:w.executionId)===d&&((v=n.toolCall)==null?void 0:v.id)===l&&j!==void 0&&gx(j)&&((E=n.toolCall)==null?void 0:E.status)==="complete";(P||z||ie)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,o)=>{var d,l;let n=new Date(t.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(d=t.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return s!==i?s-i:t.id.localeCompare(o.id)})}};var Gd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var Kd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Xd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Qd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Yd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Jd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Zd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var ec=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var tc=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var rc=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var oc=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var nc=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var ac=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var sc=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var ic=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var lc=[["path",{d:"M20 6 9 17l-5-5"}]];var dc=[["path",{d:"m6 9 6 6 6-6"}]];var cc=[["path",{d:"m15 18-6-6 6-6"}]];var pc=[["path",{d:"m9 18 6-6-6-6"}]];var uc=[["path",{d:"m18 15-6-6-6 6"}]];var fl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var ml=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var fc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var mc=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var gc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var hc=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var xc=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var yc=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var bc=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var gl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var hl=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var vc=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Cc=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var wc=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Ac=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var Sc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Tc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Mc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var kc=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Ec=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Lc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Pc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Rc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var xl=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Ic=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Hc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Wc=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Bc=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Dc=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Oc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var yl=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var _c=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Nc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var Fc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Uc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var qc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var bl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var zc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var $c=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Vc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var jc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Gc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Kc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Xc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Qc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Yc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Jc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Zc=[["path",{d:"M5 12h14"}]];var ep=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var tp=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var rp=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var op=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var np=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var ap=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var sp=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var ip=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var lp=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var dp=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var cp=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var pp=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var up=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var fp=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var mp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var gp=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var hp=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var xp=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var yp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var bp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var vl=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var vp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Cp=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var wp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Ap=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Cl=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Sp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Tp=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Mp=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var kp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Ep=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Lp=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Pp=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Rp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Ip=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Hp=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var wl=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Wp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Bp=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Dp=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Op=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var _p=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Np=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var Fp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Up=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var Tv={activity:Gd,"arrow-down":Kd,"arrow-up":Jd,"arrow-up-right":Yd,bot:oc,"chevron-down":dc,"chevron-up":uc,"chevron-right":pc,"chevron-left":cc,check:lc,clipboard:mc,"clipboard-copy":fc,copy:hc,file:Mc,"file-code":Ac,"file-spreadsheet":Sc,"file-text":Tc,"image-plus":_c,loader:zc,"loader-circle":bl,mic:Yc,paperclip:op,"refresh-cw":pp,search:mp,send:gp,"shield-alert":yp,"shield-check":bp,"shield-x":vl,square:Sp,"thumbs-down":Lp,"thumbs-up":Pp,upload:Bp,"volume-2":Op,x:Fp,user:Dp,mail:Vc,phone:ip,calendar:sc,clock:gc,building:nc,"map-pin":jc,lock:$c,key:Uc,"credit-card":xc,"at-sign":Zd,hash:Wc,globe:Hc,link:qc,"circle-check":fl,"circle-x":ml,"triangle-alert":wl,info:Fc,ban:ec,shield:vp,"arrow-left":Xd,"arrow-right":Qd,"external-link":Cc,ellipsis:hl,"ellipsis-vertical":gl,menu:Kc,house:yl,plus:dp,minus:Zc,pencil:ap,trash:Hp,"trash-2":Ip,save:fp,download:bc,share:xp,funnel:xl,settings:hp,"rotate-cw":up,maximize:Gc,minimize:Jc,"shopping-cart":wp,"shopping-bag":Cp,package:rp,truck:Wp,tag:Ep,gift:Ic,receipt:cp,wallet:Np,store:Mp,"dollar-sign":yc,percent:sp,play:lp,pause:np,"volume-x":_p,camera:ic,image:Nc,film:Ec,headphones:Bc,"message-circle":Xc,"message-square":Qc,bell:tc,heart:Dc,star:Tp,eye:wc,"eye-off":vc,bookmark:rc,"calendar-days":ac,history:Oc,timer:Rp,folder:Rc,"folder-open":Pc,files:kc,sparkles:Cl,zap:Up,sun:kp,moon:tp,flag:Lc,monitor:ep,smartphone:Ap},Ee=(r,e=24,t="currentColor",o=2)=>{let n=Tv[r];return n?Mv(n,e,t,o):(console.warn(`Lucide icon "${r}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Mv(r,e,t,o){if(!Array.isArray(r))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),r.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),n.appendChild(d)}),n}var Al={allowedTypes:Tn,maxFileSize:10*1024*1024,maxFiles:4};function kv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ev(r){return r==="application/pdf"||r.startsWith("text/")||r.includes("word")?"file-text":r.includes("excel")||r.includes("spreadsheet")?"file-spreadsheet":r==="application/json"?"file-code":"file"}var wa=class r{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,o,n;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Al.allowedTypes,maxFileSize:(o=e.maxFileSize)!=null?o:Al.maxFileSize,maxFiles:(n=e.maxFiles)!=null?n:Al.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Al.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,o,n,a,s,i,d;if(e.length){for(let l of e){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,l,"count");continue}let u=px(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let f=(n=u.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,f);continue}try{let f=await cx(l),p=dl(l)?URL.createObjectURL(l):null,m={id:kv(),file:l,previewUrl:p,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var a,s,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let o=this.attachments[t];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(t,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${e}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var e,t;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=dl(e.file),o=C("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",t&&e.previewUrl){let s=C("img");s.src=e.previewUrl,s.alt=e.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=C("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=Ev(e.file.type),d=Ee(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=C("span");l.textContent=ux(e.file.type,e.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",s.appendChild(l),o.appendChild(s)}let n=C("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=Ee("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new r({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var hx=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function ei(r,e){if(!r)return e;if(!e)return r;let t={...r};for(let[o,n]of Object.entries(e)){let a=t[o];hx(a)&&hx(n)?t[o]=ei(a,n):t[o]=n}return t}var Wo="min(440px, calc(100vw - 24px))",Sl="440px",Xt={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:Wo,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 xx(r,e){if(!(!r&&!e))return r?e?ei(r,e):r:e}function Tl(r){var e,t,o,n,a,s,i,d,l,u,f,p,m,y,h,T,M,k,L,x,w;return r?{...Xt,...r,theme:xx(Xt.theme,r.theme),darkTheme:xx(Xt.darkTheme,r.darkTheme),launcher:{...Xt.launcher,...r.launcher,dock:{...(e=Xt.launcher)==null?void 0:e.dock,...(t=r.launcher)==null?void 0:t.dock},clearChat:{...(o=Xt.launcher)==null?void 0:o.clearChat,...(n=r.launcher)==null?void 0:n.clearChat}},copy:{...Xt.copy,...r.copy},sendButton:{...Xt.sendButton,...r.sendButton},statusIndicator:{...Xt.statusIndicator,...r.statusIndicator},voiceRecognition:{...Xt.voiceRecognition,...r.voiceRecognition},features:(()=>{var Z,ne,me,be,ye,Y,ge,Oe,ce,ae;let v=(Z=Xt.features)==null?void 0:Z.artifacts,E=(ne=r.features)==null?void 0:ne.artifacts,H=(me=Xt.features)==null?void 0:me.scrollToBottom,I=(be=r.features)==null?void 0:be.scrollToBottom,P=(ye=Xt.features)==null?void 0:ye.scrollBehavior,z=(Y=r.features)==null?void 0:Y.scrollBehavior,j=(ge=Xt.features)==null?void 0:ge.streamAnimation,ie=(Oe=r.features)==null?void 0:Oe.streamAnimation,ve=(ce=Xt.features)==null?void 0:ce.askUserQuestion,Xe=(ae=r.features)==null?void 0:ae.askUserQuestion,Ae=v===void 0&&E===void 0?void 0:{...v,...E,layout:{...v==null?void 0:v.layout,...E==null?void 0:E.layout}},We=H===void 0&&I===void 0?void 0:{...H,...I},Me=P===void 0&&z===void 0?void 0:{...P,...z},Ue=j===void 0&&ie===void 0?void 0:{...j,...ie},Be=ve===void 0&&Xe===void 0?void 0:{...ve,...Xe,styles:{...ve==null?void 0:ve.styles,...Xe==null?void 0:Xe.styles}};return{...Xt.features,...r.features,...We!==void 0?{scrollToBottom:We}:{},...Me!==void 0?{scrollBehavior:Me}:{},...Ae!==void 0?{artifacts:Ae}:{},...Ue!==void 0?{streamAnimation:Ue}:{},...Be!==void 0?{askUserQuestion:Be}:{}}})(),suggestionChips:(a=r.suggestionChips)!=null?a:Xt.suggestionChips,suggestionChipsConfig:{...Xt.suggestionChipsConfig,...r.suggestionChipsConfig},layout:{...Xt.layout,...r.layout,header:{...(s=Xt.layout)==null?void 0:s.header,...(i=r.layout)==null?void 0:i.header},messages:{...(d=Xt.layout)==null?void 0:d.messages,...(l=r.layout)==null?void 0:l.messages,avatar:{...(f=(u=Xt.layout)==null?void 0:u.messages)==null?void 0:f.avatar,...(m=(p=r.layout)==null?void 0:p.messages)==null?void 0:m.avatar},timestamp:{...(h=(y=Xt.layout)==null?void 0:y.messages)==null?void 0:h.timestamp,...(M=(T=r.layout)==null?void 0:T.messages)==null?void 0:M.timestamp}},slots:{...(k=Xt.layout)==null?void 0:k.slots,...(L=r.layout)==null?void 0:L.slots}},markdown:{...Xt.markdown,...r.markdown,options:{...(x=Xt.markdown)==null?void 0:x.options,...(w=r.markdown)==null?void 0:w.options}},messageActions:{...Xt.messageActions,...r.messageActions}}:Xt}var qp={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"}},zp={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"}},$p={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:Wo,maxWidth:Sl,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 es(r,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),o=r;for(let n of t){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?es(r,o):o}function Ml(r){let e={};function t(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let d=es(r,s);d!==void 0&&(e[i]={path:i,value:d,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&t(s,i)}}return t(r.palette,"palette"),t(r.semantic,"semantic"),t(r.components,"components"),e}function Vp(r){let e=[],t=[];return r.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),r.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),r.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function yx(r,e){let t={...r};for(let[o,n]of Object.entries(e)){let a=t[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?t[o]=yx(a,n):t[o]=n}return t}function Lv(r,e){return e?yx(r,e):r}function ts(r,e={}){var n,a,s,i,d,l,u,f,p,m,y,h,T;let t={palette:qp,semantic:zp,components:$p},o={palette:{...t.palette,...r==null?void 0:r.palette,colors:{...t.palette.colors,...(n=r==null?void 0:r.palette)==null?void 0:n.colors},spacing:{...t.palette.spacing,...(a=r==null?void 0:r.palette)==null?void 0:a.spacing},typography:{...t.palette.typography,...(s=r==null?void 0:r.palette)==null?void 0:s.typography},shadows:{...t.palette.shadows,...(i=r==null?void 0:r.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=r==null?void 0:r.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=r==null?void 0:r.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...r==null?void 0:r.semantic,colors:{...t.semantic.colors,...(u=r==null?void 0:r.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(p=(f=r==null?void 0:r.semantic)==null?void 0:f.colors)==null?void 0:p.interactive},feedback:{...t.semantic.colors.feedback,...(y=(m=r==null?void 0:r.semantic)==null?void 0:m.colors)==null?void 0:y.feedback}},spacing:{...t.semantic.spacing,...(h=r==null?void 0:r.semantic)==null?void 0:h.spacing},typography:{...t.semantic.typography,...(T=r==null?void 0:r.semantic)==null?void 0:T.typography}},components:Lv(t.components,r==null?void 0:r.components)};if(e.validate!==!1){let M=Vp(o);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(k=>k.message).join(", ")}`)}if(e.plugins)for(let M of e.plugins)o=M.transform(o);return o}function kl(r){var h,T,M,k,L,x,w,v,E,H,I,P,z,j,ie,ve,Xe,Ae,We,Me,Ue,Be,Z,ne,me,be,ye,Y,ge,Oe,ce,ae,Q,Tt,Ye,De,le,nt,Re,K,he,it,Pt,te,_e,Ar,Rt,dr,Yr,zr,O,fe,Ie,Je,qe,ze,lt,Mt,Dt,or,X,wt,ct,Ce,de,rt,Ft,zt,Pr,vr,xt,It,tt,jt,cr,Dr,hr,Sr,Oo,je,Tr,io,_o,lo,At,rn,No,mn,Jr,Ln,$r,Fo,mt,co,po,Or,Wt,Vr,Zr,_r,uo,fo,Nr,mo,$t,Fr,go,on,Uo,nn,qo,eo,to,gt,re,A,_,ue;let e=Ml(r),t={};for(let[$,at]of Object.entries(e)){let ut=$.replace(/\./g,"-");t[`--persona-${ut}`]=at.value}t["--persona-primary"]=(h=t["--persona-semantic-colors-primary"])!=null?h:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(M=t["--persona-semantic-colors-accent"])!=null?M:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(k=t["--persona-semantic-colors-surface"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(L=t["--persona-semantic-colors-background"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(x=t["--persona-semantic-colors-container"])!=null?x:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(v=t["--persona-semantic-colors-text-muted"])!=null?v:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(E=t["--persona-semantic-colors-text-inverse"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(H=t["--persona-semantic-colors-border"])!=null?H:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(I=t["--persona-semantic-colors-divider"])!=null?I:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(P=t["--persona-components-voice-recording-indicator"])!=null?P:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(z=t["--persona-components-voice-recording-background"])!=null?z:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(j=t["--persona-components-voice-processing-icon"])!=null?j:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ie=t["--persona-components-voice-speaking-icon"])!=null?ie:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ve=t["--persona-components-approval-requested-background"])!=null?ve:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Xe=t["--persona-components-approval-requested-border"])!=null?Xe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ae=t["--persona-components-approval-requested-text"])!=null?Ae:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(We=t["--persona-components-approval-requested-shadow"])!=null?We:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(Me=t["--persona-components-approval-approve-background"])!=null?Me:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Ue=t["--persona-components-approval-deny-background"])!=null?Ue:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Be=t["--persona-components-attachment-image-background"])!=null?Be:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Z=t["--persona-components-attachment-image-border"])!=null?Z:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ne=t["--persona-semantic-typography-fontFamily"])!=null?ne:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(me=t["--persona-semantic-typography-fontSize"])!=null?me:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(be=t["--persona-semantic-typography-fontWeight"])!=null?be:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ye=t["--persona-semantic-typography-lineHeight"])!=null?ye:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(Y=t["--persona-palette-radius-sm"])!=null?Y:"0.125rem",t["--persona-radius-md"]=(ge=t["--persona-palette-radius-md"])!=null?ge:"0.375rem",t["--persona-radius-lg"]=(Oe=t["--persona-palette-radius-lg"])!=null?Oe:"0.5rem",t["--persona-radius-xl"]=(ce=t["--persona-palette-radius-xl"])!=null?ce:"0.75rem",t["--persona-radius-full"]=(ae=t["--persona-palette-radius-full"])!=null?ae:"9999px",t["--persona-launcher-radius"]=(Tt=(Q=t["--persona-components-launcher-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?Tt:"9999px",t["--persona-launcher-bg"]=(Ye=t["--persona-components-launcher-background"])!=null?Ye:t["--persona-primary"],t["--persona-launcher-fg"]=(De=t["--persona-components-launcher-foreground"])!=null?De:t["--persona-text-inverse"],t["--persona-launcher-border"]=(le=t["--persona-components-launcher-border"])!=null?le:t["--persona-border"],t["--persona-button-primary-bg"]=(nt=t["--persona-components-button-primary-background"])!=null?nt:t["--persona-primary"],t["--persona-button-primary-fg"]=(Re=t["--persona-components-button-primary-foreground"])!=null?Re:t["--persona-text-inverse"],t["--persona-button-radius"]=(he=(K=t["--persona-components-button-primary-borderRadius"])!=null?K:t["--persona-palette-radius-full"])!=null?he:"9999px",t["--persona-panel-radius"]=(Pt=(it=t["--persona-components-panel-borderRadius"])!=null?it:t["--persona-radius-xl"])!=null?Pt:"0.75rem",t["--persona-panel-border"]=(te=t["--persona-components-panel-border"])!=null?te:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ar=(_e=t["--persona-components-panel-shadow"])!=null?_e:t["--persona-palette-shadows-xl"])!=null?Ar:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(Rt=t["--persona-components-launcher-shadow"])!=null?Rt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(Yr=(dr=t["--persona-components-input-borderRadius"])!=null?dr:t["--persona-radius-lg"])!=null?Yr:"0.5rem",t["--persona-message-user-radius"]=(O=(zr=t["--persona-components-message-user-borderRadius"])!=null?zr:t["--persona-radius-lg"])!=null?O:"0.5rem",t["--persona-message-assistant-radius"]=(Ie=(fe=t["--persona-components-message-assistant-borderRadius"])!=null?fe:t["--persona-radius-lg"])!=null?Ie:"0.5rem",t["--persona-header-bg"]=(Je=t["--persona-components-header-background"])!=null?Je:t["--persona-surface"],t["--persona-header-border"]=(qe=t["--persona-components-header-border"])!=null?qe:t["--persona-divider"],t["--persona-header-icon-bg"]=(ze=t["--persona-components-header-iconBackground"])!=null?ze:t["--persona-primary"],t["--persona-header-icon-fg"]=(lt=t["--persona-components-header-iconForeground"])!=null?lt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Mt=t["--persona-components-header-titleForeground"])!=null?Mt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Dt=t["--persona-components-header-subtitleForeground"])!=null?Dt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(or=t["--persona-components-header-actionIconForeground"])!=null?or:t["--persona-muted"];let o=(X=r.components)==null?void 0:X.header;o!=null&&o.shadow&&(t["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(t["--persona-header-border-bottom"]=o.borderBottom);let n=(wt=r.components)==null?void 0:wt.introCard;t["--persona-intro-card-bg"]=(ct=t["--persona-components-introCard-background"])!=null?ct:t["--persona-surface"],t["--persona-intro-card-radius"]=(Ce=t["--persona-components-introCard-borderRadius"])!=null?Ce:"1rem",t["--persona-intro-card-padding"]=(de=t["--persona-components-introCard-padding"])!=null?de:"1.5rem",t["--persona-intro-card-shadow"]=(Ft=(rt=n==null?void 0:n.shadow)!=null?rt:t["--persona-components-introCard-shadow"])!=null?Ft:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(zt=t["--persona-components-input-background"])!=null?zt:t["--persona-surface"],t["--persona-input-placeholder"]=(Pr=t["--persona-components-input-placeholder"])!=null?Pr:t["--persona-text-muted"],t["--persona-message-user-bg"]=(vr=t["--persona-components-message-user-background"])!=null?vr:t["--persona-accent"],t["--persona-message-user-text"]=(xt=t["--persona-components-message-user-text"])!=null?xt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(It=t["--persona-components-message-user-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(tt=t["--persona-components-message-assistant-background"])!=null?tt:t["--persona-surface"],t["--persona-message-assistant-text"]=(jt=t["--persona-components-message-assistant-text"])!=null?jt:t["--persona-text"],t["--persona-message-assistant-border"]=(cr=t["--persona-components-message-assistant-border"])!=null?cr:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Dr=t["--persona-components-message-assistant-shadow"])!=null?Dr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Sr=(hr=t["--persona-components-scrollToBottom-background"])!=null?hr:t["--persona-button-primary-bg"])!=null?Sr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(je=(Oo=t["--persona-components-scrollToBottom-foreground"])!=null?Oo:t["--persona-button-primary-fg"])!=null?je:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Tr=t["--persona-components-scrollToBottom-border"])!=null?Tr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(io=t["--persona-components-scrollToBottom-size"])!=null?io:"40px",t["--persona-scroll-to-bottom-radius"]=(At=(lo=(_o=t["--persona-components-scrollToBottom-borderRadius"])!=null?_o:t["--persona-button-radius"])!=null?lo:t["--persona-radius-full"])!=null?At:"9999px",t["--persona-scroll-to-bottom-shadow"]=(No=(rn=t["--persona-components-scrollToBottom-shadow"])!=null?rn:t["--persona-palette-shadows-sm"])!=null?No:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(mn=t["--persona-components-scrollToBottom-padding"])!=null?mn:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Jr=t["--persona-components-scrollToBottom-gap"])!=null?Jr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=($r=(Ln=t["--persona-components-scrollToBottom-fontSize"])!=null?Ln:t["--persona-palette-typography-fontSize-sm"])!=null?$r:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Fo=t["--persona-components-scrollToBottom-iconSize"])!=null?Fo:"14px",t["--persona-tool-bubble-shadow"]=(mt=t["--persona-components-toolBubble-shadow"])!=null?mt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(co=t["--persona-components-reasoningBubble-shadow"])!=null?co:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(po=t["--persona-components-composer-shadow"])!=null?po:"none",t["--persona-md-inline-code-bg"]=(Or=t["--persona-components-markdown-inlineCode-background"])!=null?Or:t["--persona-container"],t["--persona-md-inline-code-color"]=(Wt=t["--persona-components-markdown-inlineCode-foreground"])!=null?Wt:t["--persona-text"],t["--persona-md-link-color"]=(Zr=(Vr=t["--persona-components-markdown-link-foreground"])!=null?Vr:t["--persona-accent"])!=null?Zr:"#0f0f0f";let a=t["--persona-components-markdown-heading-h1-fontSize"];a&&(t["--persona-md-h1-size"]=a);let s=t["--persona-components-markdown-heading-h1-fontWeight"];s&&(t["--persona-md-h1-weight"]=s);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(_r=t["--persona-components-markdown-codeBlock-background"])!=null?_r:t["--persona-container"],t["--persona-md-code-block-border-color"]=(uo=t["--persona-components-markdown-codeBlock-borderColor"])!=null?uo:t["--persona-border"],t["--persona-md-code-block-text-color"]=(fo=t["--persona-components-markdown-codeBlock-textColor"])!=null?fo:"inherit",t["--persona-md-table-header-bg"]=(Nr=t["--persona-components-markdown-table-headerBackground"])!=null?Nr:t["--persona-container"],t["--persona-md-table-border-color"]=(mo=t["--persona-components-markdown-table-borderColor"])!=null?mo:t["--persona-border"],t["--persona-md-hr-color"]=($t=t["--persona-components-markdown-hr-color"])!=null?$t:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Fr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Fr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(go=t["--persona-components-markdown-blockquote-background"])!=null?go:"transparent",t["--persona-md-blockquote-text-color"]=(on=t["--persona-components-markdown-blockquote-textColor"])!=null?on:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Uo=t["--persona-components-collapsibleWidget-container"])!=null?Uo:t["--persona-surface"],t["--cw-surface"]=(nn=t["--persona-components-collapsibleWidget-surface"])!=null?nn:t["--persona-surface"],t["--cw-border"]=(qo=t["--persona-components-collapsibleWidget-border"])!=null?qo:t["--persona-border"],t["--persona-message-border"]=(eo=t["--persona-components-message-border"])!=null?eo:t["--persona-border"];let u=r.components,f=u==null?void 0:u.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let p=u==null?void 0:u.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let y=u==null?void 0:u.artifact;if(y!=null&&y.toolbar){let $=y.toolbar;$.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=$.iconHoverColor),$.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=$.iconHoverBackground),$.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=$.iconPadding),$.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=$.iconBorderRadius),$.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=$.iconBorder),$.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=$.toggleGroupGap),$.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=$.copyBackground),$.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=$.copyBorder),$.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=$.copyColor),$.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=$.copyBorderRadius),$.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=$.copyPadding),$.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=$.copyMenuBackground,t["--persona-dropdown-bg"]=(to=t["--persona-dropdown-bg"])!=null?to:$.copyMenuBackground),$.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=$.copyMenuBorder,t["--persona-dropdown-border"]=(gt=t["--persona-dropdown-border"])!=null?gt:$.copyMenuBorder),$.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=$.copyMenuShadow,t["--persona-dropdown-shadow"]=(re=t["--persona-dropdown-shadow"])!=null?re:$.copyMenuShadow),$.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=$.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(A=t["--persona-dropdown-radius"])!=null?A:$.copyMenuBorderRadius),$.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=$.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(_=t["--persona-dropdown-item-hover-bg"])!=null?_:$.copyMenuItemHoverBackground),$.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=$.iconBackground),$.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=$.toolbarBorder)}if(y!=null&&y.tab){let $=y.tab;$.background&&(t["--persona-artifact-tab-bg"]=$.background),$.activeBackground&&(t["--persona-artifact-tab-active-bg"]=$.activeBackground),$.activeBorder&&(t["--persona-artifact-tab-active-border"]=$.activeBorder),$.borderRadius&&(t["--persona-artifact-tab-radius"]=$.borderRadius),$.textColor&&(t["--persona-artifact-tab-color"]=$.textColor),$.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=$.hoverBackground),$.listBackground&&(t["--persona-artifact-tab-list-bg"]=$.listBackground),$.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=$.listBorderColor),$.listPadding&&(t["--persona-artifact-tab-list-padding"]=$.listPadding)}if(y!=null&&y.pane){let $=y.pane;if($.toolbarBackground){let at=(ue=es(r,$.toolbarBackground))!=null?ue:$.toolbarBackground;t["--persona-artifact-toolbar-bg"]=at}}return t}var bx={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 Pv={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"}}},vx=r=>{if(!(!r||typeof r!="object"||Array.isArray(r)))return r},ti=()=>{var r;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Rv=r=>{var t;let e=(t=r==null?void 0:r.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":ti()},jp=r=>Rv(r),Iv=r=>ts(r),Hv=r=>{var t;let e=ts(void 0,{validate:!1});return ts({...r,palette:{...e.palette,colors:{...Pv.colors,...(t=r==null?void 0:r.palette)==null?void 0:t.colors}}},{validate:!1})},rs=r=>{let e=jp(r),t=vx(r==null?void 0:r.theme),o=vx(r==null?void 0:r.darkTheme);return e==="dark"?Hv(ei(t!=null?t:{},o!=null?o:{})):Iv(t)},Wv=r=>kl(r),Vn=(r,e)=>{let t=rs(e),o=Wv(t);for(let[n,a]of Object.entries(o))r.style.setProperty(n,a)},El=r=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{r(ti())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>r(ti());t.addEventListener?(t.addEventListener("change",o),e.push(()=>t.removeEventListener("change",o))):t.addListener&&(t.addListener(o),e.push(()=>t.removeListener(o)))}return()=>{e.forEach(t=>t())}};var Cx=(function(){"use strict";let r=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:r,afterNodeAdded:r,beforeNodeMorphed:r,afterNodeMorphed:r,beforeNodeRemoved:r,afterNodeRemoved:r,beforeAttributeUpdated:r},head:{style:"merge",shouldPreserve:p=>p.getAttribute("im-preserve")==="true",shouldReAppend:p=>p.getAttribute("im-re-append")==="true",shouldRemove:r,afterHeadMorphed:r},restoreFocus:!0};function t(p,m,y={}){p=u(p);let h=f(m),T=l(p,h,y),M=n(T,()=>i(T,p,h,k=>k.morphStyle==="innerHTML"?(a(k,p,h),Array.from(p.childNodes)):o(k,p,h)));return T.pantry.remove(),M}function o(p,m,y){let h=f(m);return a(p,h,y,m,m.nextSibling),Array.from(h.childNodes)}function n(p,m){var L;if(!p.config.restoreFocus)return m();let y=document.activeElement;if(!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement))return m();let{id:h,selectionStart:T,selectionEnd:M}=y,k=m();return h&&h!==((L=document.activeElement)==null?void 0:L.getAttribute("id"))&&(y=p.target.querySelector(`[id="${h}"]`),y==null||y.focus()),y&&!y.selectionEnd&&M&&y.setSelectionRange(T,M),k}let a=(function(){function p(x,w,v,E=null,H=null){w instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(w=w.content,v=v.content),E||(E=w.firstChild);for(let I of v.childNodes){if(E&&E!=H){let z=y(x,I,E,H);if(z){z!==E&&T(x,E,z),s(z,I,x),E=z.nextSibling;continue}}if(I instanceof Element){let z=I.getAttribute("id");if(x.persistentIds.has(z)){let j=M(w,z,E,x);s(j,I,x),E=j.nextSibling;continue}}let P=m(w,I,E,x);P&&(E=P.nextSibling)}for(;E&&E!=H;){let I=E;E=E.nextSibling,h(x,I)}}function m(x,w,v,E){if(E.callbacks.beforeNodeAdded(w)===!1)return null;if(E.idMap.has(w)){let H=document.createElement(w.tagName);return x.insertBefore(H,v),s(H,w,E),E.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return x.insertBefore(H,v),E.callbacks.afterNodeAdded(H),H}}let y=(function(){function x(E,H,I,P){let z=null,j=H.nextSibling,ie=0,ve=I;for(;ve&&ve!=P;){if(v(ve,H)){if(w(E,ve,H))return ve;z===null&&(E.idMap.has(ve)||(z=ve))}if(z===null&&j&&v(ve,j)&&(ie++,j=j.nextSibling,ie>=2&&(z=void 0)),E.activeElementAndParents.includes(ve))break;ve=ve.nextSibling}return z||null}function w(E,H,I){let P=E.idMap.get(H),z=E.idMap.get(I);if(!z||!P)return!1;for(let j of P)if(z.has(j))return!0;return!1}function v(E,H){var z,j,ie;let I=E,P=H;return I.nodeType===P.nodeType&&I.tagName===P.tagName&&(!((z=I.getAttribute)!=null&&z.call(I,"id"))||((j=I.getAttribute)==null?void 0:j.call(I,"id"))===((ie=P.getAttribute)==null?void 0:ie.call(P,"id")))}return x})();function h(x,w){var v;if(x.idMap.has(w))L(x.pantry,w,null);else{if(x.callbacks.beforeNodeRemoved(w)===!1)return;(v=w.parentNode)==null||v.removeChild(w),x.callbacks.afterNodeRemoved(w)}}function T(x,w,v){let E=w;for(;E&&E!==v;){let H=E;E=E.nextSibling,h(x,H)}return E}function M(x,w,v,E){var I,P;let H=((P=(I=E.target).getAttribute)==null?void 0:P.call(I,"id"))===w&&E.target||E.target.querySelector(`[id="${w}"]`)||E.pantry.querySelector(`[id="${w}"]`);return k(H,E),L(x,H,v),H}function k(x,w){let v=x.getAttribute("id");for(;x=x.parentNode;){let E=w.idMap.get(x);E&&(E.delete(v),E.size||w.idMap.delete(x))}}function L(x,w,v){if(x.moveBefore)try{x.moveBefore(w,v)}catch{x.insertBefore(w,v)}else x.insertBefore(w,v)}return p})(),s=(function(){function p(k,L,x){return x.ignoreActive&&k===document.activeElement?null:(x.callbacks.beforeNodeMorphed(k,L)===!1||(k instanceof HTMLHeadElement&&x.head.ignore||(k instanceof HTMLHeadElement&&x.head.style!=="morph"?d(k,L,x):(m(k,L,x),M(k,x)||a(x,k,L))),x.callbacks.afterNodeMorphed(k,L)),k)}function m(k,L,x){let w=L.nodeType;if(w===1){let v=k,E=L,H=v.attributes,I=E.attributes;for(let P of I)T(P.name,v,"update",x)||v.getAttribute(P.name)!==P.value&&v.setAttribute(P.name,P.value);for(let P=H.length-1;0<=P;P--){let z=H[P];if(z&&!E.hasAttribute(z.name)){if(T(z.name,v,"remove",x))continue;v.removeAttribute(z.name)}}M(v,x)||y(v,E,x)}(w===8||w===3)&&k.nodeValue!==L.nodeValue&&(k.nodeValue=L.nodeValue)}function y(k,L,x){if(k instanceof HTMLInputElement&&L instanceof HTMLInputElement&&L.type!=="file"){let w=L.value,v=k.value;h(k,L,"checked",x),h(k,L,"disabled",x),L.hasAttribute("value")?v!==w&&(T("value",k,"update",x)||(k.setAttribute("value",w),k.value=w)):T("value",k,"remove",x)||(k.value="",k.removeAttribute("value"))}else if(k instanceof HTMLOptionElement&&L instanceof HTMLOptionElement)h(k,L,"selected",x);else if(k instanceof HTMLTextAreaElement&&L instanceof HTMLTextAreaElement){let w=L.value,v=k.value;if(T("value",k,"update",x))return;w!==v&&(k.value=w),k.firstChild&&k.firstChild.nodeValue!==w&&(k.firstChild.nodeValue=w)}}function h(k,L,x,w){let v=L[x],E=k[x];if(v!==E){let H=T(x,k,"update",w);H||(k[x]=L[x]),v?H||k.setAttribute(x,""):T(x,k,"remove",w)||k.removeAttribute(x)}}function T(k,L,x,w){return k==="value"&&w.ignoreActiveValue&&L===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(k,L,x)===!1}function M(k,L){return!!L.ignoreActiveValue&&k===document.activeElement&&k!==document.body}return p})();function i(p,m,y,h){if(p.head.block){let T=m.querySelector("head"),M=y.querySelector("head");if(T&&M){let k=d(T,M,p);return Promise.all(k).then(()=>{let L=Object.assign(p,{head:{block:!1,ignore:!0}});return h(L)})}}return h(p)}function d(p,m,y){let h=[],T=[],M=[],k=[],L=new Map;for(let w of m.children)L.set(w.outerHTML,w);for(let w of p.children){let v=L.has(w.outerHTML),E=y.head.shouldReAppend(w),H=y.head.shouldPreserve(w);v||H?E?T.push(w):(L.delete(w.outerHTML),M.push(w)):y.head.style==="append"?E&&(T.push(w),k.push(w)):y.head.shouldRemove(w)!==!1&&T.push(w)}k.push(...L.values());let x=[];for(let w of k){let v=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let E,H=new Promise(function(I){E=I});v.addEventListener("load",function(){E()}),x.push(H)}p.appendChild(v),y.callbacks.afterNodeAdded(v),h.push(v)}}for(let w of T)y.callbacks.beforeNodeRemoved(w)!==!1&&(p.removeChild(w),y.callbacks.afterNodeRemoved(w));return y.head.afterHeadMorphed(p,{added:h,kept:M,removed:T}),x}let l=(function(){function p(x,w,v){let{persistentIds:E,idMap:H}=k(x,w),I=m(v),P=I.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(P))throw`Do not understand how to morph style ${P}`;return{target:x,newContent:w,config:I,morphStyle:P,ignoreActive:I.ignoreActive,ignoreActiveValue:I.ignoreActiveValue,restoreFocus:I.restoreFocus,idMap:H,persistentIds:E,pantry:y(),activeElementAndParents:h(x),callbacks:I.callbacks,head:I.head}}function m(x){let w=Object.assign({},e);return Object.assign(w,x),w.callbacks=Object.assign({},e.callbacks,x.callbacks),w.head=Object.assign({},e.head,x.head),w}function y(){let x=document.createElement("div");return x.hidden=!0,document.body.insertAdjacentElement("afterend",x),x}function h(x){let w=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&x.contains(v))for(;v&&(w.push(v),v!==x);)v=v.parentElement;return w}function T(x){var v;let w=Array.from(x.querySelectorAll("[id]"));return(v=x.getAttribute)!=null&&v.call(x,"id")&&w.push(x),w}function M(x,w,v,E){for(let H of E){let I=H.getAttribute("id");if(w.has(I)){let P=H;for(;P;){let z=x.get(P);if(z==null&&(z=new Set,x.set(P,z)),z.add(I),P===v)break;P=P.parentElement}}}}function k(x,w){let v=T(x),E=T(w),H=L(v,E),I=new Map;M(I,H,x,v);let P=w.__idiomorphRoot||w;return M(I,H,P,E),{persistentIds:H,idMap:I}}function L(x,w){let v=new Set,E=new Map;for(let{id:I,tagName:P}of x)E.has(I)?v.add(I):E.set(I,P);let H=new Set;for(let{id:I,tagName:P}of w)H.has(I)?v.add(I):E.get(I)===P&&H.add(I);for(let I of v)H.delete(I);return H}return p})(),{normalizeElement:u,normalizeParent:f}=(function(){let p=new WeakSet;function m(M){return M instanceof Document?M.documentElement:M}function y(M){if(M==null)return document.createElement("div");if(typeof M=="string")return y(T(M));if(p.has(M))return M;if(M instanceof Node){if(M.parentNode)return new h(M);{let k=document.createElement("div");return k.append(M),k}}else{let k=document.createElement("div");for(let L of[...M])k.append(L);return k}}class h{constructor(k){this.originalNode=k,this.realParentNode=k.parentNode,this.previousSibling=k.previousSibling,this.nextSibling=k.nextSibling}get childNodes(){let k=[],L=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;L&&L!=this.nextSibling;)k.push(L),L=L.nextSibling;return k}querySelectorAll(k){return this.childNodes.reduce((L,x)=>{if(x instanceof Element){x.matches(k)&&L.push(x);let w=x.querySelectorAll(k);for(let v=0;v<w.length;v++)L.push(w[v])}return L},[])}insertBefore(k,L){return this.realParentNode.insertBefore(k,L)}moveBefore(k,L){return this.realParentNode.moveBefore(k,L)}get __idiomorphRoot(){return this.originalNode}}function T(M){let k=new DOMParser,L=M.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(L.match(/<\/html>/)||L.match(/<\/head>/)||L.match(/<\/body>/)){let x=k.parseFromString(M,"text/html");if(L.match(/<\/html>/))return p.add(x),x;{let w=x.firstChild;return w&&p.add(w),w}}else{let w=k.parseFromString("<body><template>"+M+"</template></body>","text/html").body.querySelector("template").content;return p.add(w),w}}return{normalizeElement:m,normalizeParent:y}})();return{morph:t,defaults:e}})();var Ll=(r,e,t={})=>{let{preserveTypingAnimation:o=!0}=t;Cx.morph(r,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let d=(s=n.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Pl={index:-1,draft:""};function wx(r){let{direction:e,history:t,currentValue:o,atStart:n,state:a}=r,s=a.index!==-1;if(t.length===0)return{handled:!1,state:a};if(e==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:t[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<t.length-1){let i=a.index+1;return{handled:!0,value:t[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Pl}}}function Ax(r,e){var t,o,n,a,s,i,d,l,u,f,p,m,y,h,T,M,k,L,x,w,v,E,H,I,P,z,j,ie,ve,Xe,Ae,We,Me,Ue,Be,Z,ne,me;return[r.id,r.role,(o=(t=r.content)==null?void 0:t.length)!=null?o:0,(a=(n=r.content)==null?void 0:n.slice(-32))!=null?a:"",r.streaming?"1":"0",(s=r.variant)!=null?s:"",(d=(i=r.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=r.llmContent)==null?void 0:l.length)!=null?u:0,(p=(f=r.approval)==null?void 0:f.status)!=null?p:"",(y=(m=r.toolCall)==null?void 0:m.status)!=null?y:"",(T=(h=r.toolCall)==null?void 0:h.name)!=null?T:"",(L=(k=(M=r.toolCall)==null?void 0:M.chunks)==null?void 0:k.length)!=null?L:0,(E=(v=(w=(x=r.toolCall)==null?void 0:x.chunks)==null?void 0:w[r.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?E:"",typeof((H=r.toolCall)==null?void 0:H.args)=="string"?r.toolCall.args.length:(I=r.toolCall)!=null&&I.args?JSON.stringify(r.toolCall.args).length:0,(j=(z=(P=r.reasoning)==null?void 0:P.chunks)==null?void 0:z.length)!=null?j:0,(Ae=(Xe=(ve=(ie=r.reasoning)==null?void 0:ie.chunks)==null?void 0:ve[r.reasoning.chunks.length-1])==null?void 0:Xe.length)!=null?Ae:0,(Be=(Ue=(Me=(We=r.reasoning)==null?void 0:We.chunks)==null?void 0:Me[r.reasoning.chunks.length-1])==null?void 0:Ue.slice(-32))!=null?Be:"",(ne=(Z=r.contentParts)==null?void 0:Z.length)!=null?ne:0,(me=r.stopReason)!=null?me:"",e].join("\0")}function Sx(){return new Map}function Tx(r,e,t){let o=r.get(e);return o&&o.fingerprint===t?o.wrapper:null}function Mx(r,e,t,o){r.set(e,{fingerprint:t,wrapper:o})}function kx(r,e){for(let t of r.keys())e.has(t)||r.delete(t)}function Rl(r=!0){let e=r;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Mn(r){return Math.max(0,r.scrollHeight-r.clientHeight)}function Aa(r,e){return Mn(r)-r.scrollTop<=e}function Il(r){let{following:e,currentScrollTop:t,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=r,u=t-o;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:t}:!e&&n&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:e&&d&&!n?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Hl(r){let{following:e,deltaY:t,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=r;return e&&t<0?"pause":!e&&n&&t>0&&o?"resume":"none"}function Ex(r,e){return!r||r.isCollapsed?!1:e.contains(r.anchorNode)||e.contains(r.focusNode)}function Lx(r){let e=Math.max(0,r.anchorOffsetTop-r.topOffset),t=Math.max(0,e+r.viewportHeight-r.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Px(r){let e=Math.max(0,r.currentContentHeight-r.contentHeightAtAnchor);return Math.max(0,r.initialSpacerHeight-e)}var ao={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},so=1e5,jn=so+1;var ri={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Bv=["pre","code","a","script","style"],Wl=r=>{var e,t,o,n,a;return{type:(e=r==null?void 0:r.type)!=null?e:ri.type,placeholder:(t=r==null?void 0:r.placeholder)!=null?t:ri.placeholder,speed:(o=r==null?void 0:r.speed)!=null?o:ri.speed,duration:(n=r==null?void 0:r.duration)!=null?n:ri.duration,buffer:(a=r==null?void 0:r.buffer)!=null?a:ri.buffer}},Ix=[{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"}],oi=new Map;for(let r of Ix)oi.set(r.name,r);var Sa=r=>{oi.set(r.name,r)},Xp=r=>{Ix.some(e=>e.name===r)||oi.delete(r)},Qp=()=>Array.from(oi.keys()),ni=(r,e)=>{var t,o;return r==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,r)?(t=e[r])!=null?t:null:(o=oi.get(r))!=null?o:null},Bl=(r,e,t,o,n)=>{if(!n)return r;if(t!=null&&t.bufferContent)return t.bufferContent(r,o);if(!r)return r;if(e==="word"){let a=r.search(/\s(?=\S*$)/);return a<0?"":r.slice(0,a)}if(e==="line"){let a=r.lastIndexOf(`
|
|
63
|
-
`);return a<0?"":r.slice(0,a)}return r},Dv=(r,e,t,o)=>{let n=r.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${t}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=e,n},Ov=(r,e,t,o)=>{let n=r.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${t}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=e,n},Gp=/\s/,_v=(r,e)=>{let t=r.parentNode;for(;t;){if(t.nodeType===1){let o=t;if(e.has(o.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Nv=(r,e,t)=>{var d;let o=r.ownerDocument,n=r.parentNode;if(!o||!n)return;let a=(d=r.nodeValue)!=null?d:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(Gp.test(a[i])){let l=i;for(;l<a.length&&Gp.test(a[l]);)l+=1;s.appendChild(o.createTextNode(a.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<a.length&&!Gp.test(a[u]);)l.appendChild(Dv(o,a[u],e,t.value)),t.value+=1,u+=1;s.appendChild(l),i=u}n.replaceChild(s,r)},Fv=(r,e,t)=>{var d;let o=r.ownerDocument,n=r.parentNode;if(!o||!n)return;let a=(d=r.nodeValue)!=null?d:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(o.createTextNode(l)):(s.appendChild(Ov(o,l,e,t.value)),t.value+=1));n.replaceChild(s,r)},ai=(r,e,t,o)=>{var f,p;if(!r||typeof document=="undefined")return r;let n=document.createElement("div");n.innerHTML=r;let a=new Set(((f=o==null?void 0:o.skipTags)!=null?f:Bv).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],d=s.nextNode();for(;d;)_v(d,a)||i.push(d),d=s.nextNode();let l={value:(p=o==null?void 0:o.startIndex)!=null?p:0},u=e==="char"?Nv:Fv;for(let m of i)u(m,t,l);return n.innerHTML},Dl=(r=document)=>{let e=r.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},si=(r=document)=>{let e=r.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=r.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Rx=new WeakMap,Uv=(r,e)=>{var a;if(!r.styles)return;let t=Rx.get(e);if(t||(t=new Set,Rx.set(e,t)),t.has(r.name)){let s=r.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;t.delete(r.name)}t.add(r.name);let n=(e instanceof ShadowRoot?e.ownerDocument:(a=e.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",r.name),n.textContent=r.styles,e.appendChild(n)},Kp=new WeakMap,qv=(r,e)=>{if(!r.onAttach)return;let t=Kp.get(e);if(t||(t=new Map,Kp.set(e,t)),t.has(r.name))return;let o=r.onAttach(e);t.set(r.name,o)},Hx=r=>{let e=Kp.get(r);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Yp=(r,e)=>{Uv(r,e),qv(r,e)};function Jp(r,e=so){let t=r.style.position,o=r.style.zIndex,n=r.style.isolation,a=getComputedStyle(r),s=a.position==="static"||a.position==="";return s&&(r.style.position="relative"),r.style.zIndex=String(e),r.style.isolation="isolate",()=>{s&&(r.style.position=t),r.style.zIndex=o,r.style.isolation=n}}var ii=0,Gn=null;function Zp(r=document){var t;if(ii++,ii===1){let o=r.body,a=((t=r.defaultView)!=null?t:window).scrollY||r.documentElement.scrollTop;Gn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let e=!1;return()=>{var o;if(!e&&(e=!0,ii=Math.max(0,ii-1),ii===0&&Gn)){let n=r.body,a=(o=r.defaultView)!=null?o:window;n.style.overflow=Gn.originalOverflow,n.style.position=Gn.originalPosition,n.style.top=Gn.originalTop,n.style.width=Gn.originalWidth,a.scrollTo(0,Gn.scrollY),Gn=null}}}var li={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lr=r=>{var e,t;return((t=(e=r==null?void 0:r.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},Kn=r=>{var e,t;return((t=(e=r==null?void 0:r.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},Bo=r=>{var t,o,n,a,s,i;let e=(t=r==null?void 0:r.launcher)==null?void 0:t.dock;return{side:(o=e==null?void 0:e.side)!=null?o:li.side,width:(n=e==null?void 0:e.width)!=null?n:li.width,animate:(a=e==null?void 0:e.animate)!=null?a:li.animate,reveal:(s=e==null?void 0:e.reveal)!=null?s:li.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:li.maxHeight}};var tn={"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 di=(r,e)=>{let t=C("button");t.type="button",t.innerHTML=`
|
|
17
|
+
_Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]}),oh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,nh=e=>ea(e)||e===Mo,Ua=class{constructor(t={},r){this.config=t;this.callbacks=r;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.readAloud=new ia(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,u,g;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall,m=!!(p!=null&&p.name)&&(ea(p.name)||p.name===Mo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.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:(i=t.message.agentMetadata.iteration)!=null?i: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;((c=this.agentExecution)==null?void 0:c.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),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new na(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,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),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId;!r||!o||!this.config.clientToken||id().catch(()=>{})}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 Ps((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,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=In.isSupported()?new In({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(o=t.host)!=null?o:this.config.apiUrl,d=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(c&&d&&u)return id().then(({RuntypeSpeechEngine:p,FallbackSpeechEngine:m})=>{let x=new p({host:c,agentId:d,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new m(x,r,{onFallback:C=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${C.message}`)}):x});if(g&&r)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Rn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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 r,o,n,a,s,i,c,d,u,g;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:(a=(n=t.runtype)==null?void 0:n.clientToken)!=null?a:this.config.clientToken,host:(i=(s=t.runtype)==null?void 0:s.host)!=null?i:this.config.apiUrl,voiceId:(c=t.runtype)==null?void 0:c.voiceId,createPlaybackEngine:(d=t.runtype)==null?void 0:d.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=t.browser)==null?void 0:u.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}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,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!ob(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new na(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:d=!1,voiceProcessing:u,rawContent:g}=t,m={id:s!=null?s:r==="user"?Oa():r==="assistant"?aa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};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 r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:d,sequence:u,streaming:g=!1,voiceProcessing:p,rawContent:m}=o,C={id:c!=null?c:n==="user"?Oa():n==="assistant"?aa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};r.push(C)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,u,g,p,m;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves();let n=Oa(),a=aa(),s={id:n,role:"user",content:o||Bi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let T=rh(x,this.config.errorMessage);if(T){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(p=this.callbacks).onError)==null||m.call(p,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=aa();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let g=rh(d,this.config.errorMessage);if(g){let p={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(p)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(d))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,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(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var u,g,p,m,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(C=>C.id===n),i={id:n,role:"assistant",content:"",createdAt:(u=s==null?void 0:s.createdAt)!=null?u:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,d=c&&typeof c=="object"?c.onDecision:void 0;try{let C;if(d?C=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):C=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),C){let T=null;if(C instanceof Response){if(!C.ok){let E=await C.json().catch(()=>null);throw new Error((p=E==null?void 0:E.error)!=null?p:`Approval request failed: ${C.status}`)}T=C.body}else C instanceof ReadableStream&&(T=C);T?await this.connectStream(T,{allowReentry:!0}):(r==="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(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(x=(m=this.callbacks).onError)==null||x.call(m,C instanceof Error?C:new Error(String(C)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var u,g,p,m,x,C,T,E,M,P,y,w;let o=this.messages.find(b=>b.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let n=(g=t.agentMetadata)==null?void 0:g.executionId,a=(p=t.toolCall)==null?void 0:p.name;if(!n||!a){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let b=(C=t.toolCall)==null?void 0:C.args,A=Array.isArray(b==null?void 0:b.questions)?b.questions:[];if(A.length===1){let H=typeof((T=A[0])==null?void 0:T.question)=="string"?A[0].question:"";H&&(s={[H]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(M=t.toolCall)==null?void 0:M.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let b=typeof r=="string"?r:Object.entries(r).map(([A,H])=>`${A}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let b=s!=null?s:{};d.forEach((A,H)=>{let W=typeof(A==null?void 0:A.question)=="string"?A.question:"";if(!W)return;let k=b[W],N=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let b=await this.client.resumeFlow(n,{[a]:r});if(!b.ok){let A=await b.json().catch(()=>null);throw new Error((P=A==null?void 0:A.error)!=null?P:`Resume failed: ${b.status}`)}b.body?await this.connectStream(b.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(b){let A=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,A||(w=(y=this.callbacks).onError)==null||w.call(y,b instanceof Error?b:new Error(String(b)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==Mo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,d,u,g;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async p=>{var w,b,A,H,W,k,N;let m=(w=p.toolCall)==null?void 0:w.name,x=(b=p.toolCall)==null?void 0:b.id;if(!m||!x)return null;let C=`${t}:${x}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(C),o.push(C);let T=this.markWebMcpToolRunning(p),E=(H=(A=p.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?H:m;if(m===Mo)return{dedupeKey:C,resumeKey:E,output:Zl(),toolMessage:p,startedAt:T,completedAt:Date.now()};let M=new AbortController;this.webMcpResolveControllers.add(M),n.push(M);let P=this.client.executeWebMcpToolCall(m,(W=p.toolCall)==null?void 0:W.args,M.signal),y;if(!P)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await P}catch(q){let Z=q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")||q.message.includes("abort"));return Z||(N=(k=this.callbacks).onError)==null||N.call(k,q instanceof Error?q:new Error(String(q))),this.markWebMcpToolComplete(p,Rs(Z?"Aborted by cancel()":oh(q)),T),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(p,Rs("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:E,output:y,toolMessage:p,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let p={};for(let x of i)p[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,p,{signal:a.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((c=x==null?void 0:x.error)!=null?c:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((d=x.toolMessage.toolCall)==null?void 0:d.name)===Mo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,p instanceof Error?p:new Error(String(p)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Rs("Aborted by cancel()"),x.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of n)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,C,T,E,M,P,y,w,b,A,H,W;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(C=t.toolCall)==null?void 0:C.name,n=(T=t.toolCall)==null?void 0:T.id;if(!r){(M=(E=this.callbacks).onError)==null||M.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let k=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(N){(y=(P=this.callbacks).onError)==null||y.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(k)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let d=o===Mo,u=(w=t.toolCall)==null?void 0:w.args,g=d?null:this.client.executeWebMcpToolCall(o,u,c),p="execute",m=s;try{let k;if(d?k=Zl():g?k=await g:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Rs("Aborted by cancel()"),s);return}let N=(A=(b=t.agentMetadata)==null?void 0:b.webMcpToolCallId)!=null?A:o;p="resume",await this.resumeWithToolOutput(r,N,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,k,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(k){let N=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(p==="execute"||N||c.aborted)&&this.markWebMcpToolComplete(t,Rs(N||c.aborted?"Aborted by cancel()":oh(k)),s),N||(W=(H=this.callbacks).onError)==null||W.call(H,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.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 n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;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:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!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 o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=ad(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return _a(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=ad(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var u,g,p,m,x,C,T,E,M,P,y,w,b,A,H;if(a!==o)return n;let s={...n,...r};if(((u=n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=n.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(p=s.agentMetadata)!=null?p:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let W=n.approval,k=r.approval;s.approval={...W,...k,executionId:k.executionId||W.executionId,toolName:k.toolName||W.toolName,description:k.description||W.description,toolType:(m=k.toolType)!=null?m:W.toolType,reason:(x=k.reason)!=null?x:W.reason,parameters:(C=k.parameters)!=null?C:W.parameters}}let i=(T=r.toolCall)==null?void 0:T.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(M=r.toolCall)==null?void 0:M.id;if(i&&nh(i)&&c&&d&&((P=r.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let W=`${c}:${d}`,k=this.webMcpInflightKeys.has(W),N=this.webMcpResolvedKeys.has(W),q=(y=n.toolCall)==null?void 0:y.name,Z=((w=n.agentMetadata)==null?void 0:w.executionId)===c&&((b=n.toolCall)==null?void 0:b.id)===d&&q!==void 0&&nh(q)&&((A=n.toolCall)==null?void 0:A.status)==="complete";(k||N||Z)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),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((r,o)=>{var c,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var ld=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var dd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var cd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var pd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var ud=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var fd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var md=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var gd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var hd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var xd=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var yd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var bd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var vd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Cd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var wd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Sd=[["path",{d:"M20 6 9 17l-5-5"}]];var Ad=[["path",{d:"m6 9 6 6 6-6"}]];var Md=[["path",{d:"m15 18-6-6 6-6"}]];var Td=[["path",{d:"m9 18 6-6-6-6"}]];var Ed=[["path",{d:"m18 15-6-6-6 6"}]];var Oi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var _i=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var kd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var Ld=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Pd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Rd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Id=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Wd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Hd=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Ui=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var qi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Bd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Dd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var Fd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Nd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var Od=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var _d=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Ud=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var qd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Vd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var $d=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var zd=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var jd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Vi=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Gd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Kd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Xd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Qd=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Jd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Yd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var $i=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Zd=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var ec=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var tc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var rc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var oc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var zi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var nc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var ac=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var sc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var ic=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var lc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var dc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var cc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var pc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var uc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var fc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var mc=[["path",{d:"M5 12h14"}]];var gc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var hc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var xc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var yc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var bc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var vc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Cc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var wc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Sc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Ac=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Mc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var Tc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Ec=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var kc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var Lc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Pc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Rc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Ic=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Wc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Hc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var ji=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Bc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Dc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var Fc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Nc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Gi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Oc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var _c=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Uc=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var qc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Vc=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var $c=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var zc=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var jc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Gc=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Kc=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Ki=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Xc=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Qc=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Jc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Yc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Zc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var ep=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var tp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var rp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var nb={activity:ld,"arrow-down":dd,"arrow-up":fd,"arrow-up-right":ud,bot:yd,"chevron-down":Ad,"chevron-up":Ed,"chevron-right":Td,"chevron-left":Md,check:Sd,clipboard:Ld,"clipboard-copy":kd,copy:Rd,file:Ud,"file-code":Nd,"file-spreadsheet":Od,"file-text":_d,"image-plus":Zd,loader:nc,"loader-circle":zi,mic:uc,paperclip:yc,"refresh-cw":Tc,search:Lc,send:Pc,"shield-alert":Wc,"shield-check":Hc,"shield-x":ji,square:Oc,"thumbs-down":$c,"thumbs-up":zc,upload:Qc,"volume-2":Yc,x:tp,user:Jc,mail:sc,phone:wc,calendar:Cd,clock:Pd,building:bd,"map-pin":ic,lock:ac,key:rc,"credit-card":Id,"at-sign":md,hash:Xd,globe:Kd,link:oc,"circle-check":Oi,"circle-x":_i,"triangle-alert":Ki,info:tc,ban:gd,shield:Bc,"arrow-left":cd,"arrow-right":pd,"external-link":Dd,ellipsis:qi,"ellipsis-vertical":Ui,menu:dc,house:$i,plus:Ac,minus:mc,pencil:vc,trash:Kc,"trash-2":Gc,save:kc,download:Hd,share:Ic,funnel:Vi,settings:Rc,"rotate-cw":Ec,maximize:lc,minimize:fc,"shopping-cart":Fc,"shopping-bag":Dc,package:xc,truck:Xc,tag:Vc,gift:Gd,receipt:Mc,wallet:ep,store:Uc,"dollar-sign":Wd,percent:Cc,play:Sc,pause:bc,"volume-x":Zc,camera:wd,image:ec,film:Vd,headphones:Qd,"message-circle":cc,"message-square":pc,bell:hd,heart:Jd,star:_c,eye:Fd,"eye-off":Bd,bookmark:xd,"calendar-days":vd,history:Yd,timer:jc,folder:jd,"folder-open":zd,files:qd,sparkles:Gi,zap:rp,sun:qc,moon:hc,flag:$d,monitor:gc,smartphone:Nc},ve=(e,t=24,r="currentColor",o=2)=>{let n=nb[e];return n?ab(n,t,r,o):(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 ab(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,u])=>{d!=="stroke"&&c.setAttribute(d,String(u))}),n.appendChild(c)}),n}var Xi={allowedTypes:an,maxFileSize:10*1024*1024,maxFiles:4};function sb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ib(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 la=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Xi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Xi.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Xi.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:Xi.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 r,o,n,a,s,i,c;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let u=Jg(d,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(n=u.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,g);continue}try{let g=await Qg(d),p=Di(d)?URL.createObjectURL(d):null,m={id:sb(),file:d,previewUrl:p,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=Di(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=S("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=S("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=ib(t.file.type),c=ve(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=S("span");d.textContent=Yg(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let n=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=ve("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){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:r})}};var ah=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Is(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];ah(a)&&ah(n)?r[o]=Is(a,n):r[o]=n}return r}var oo="min(440px, calc(100vw - 24px))",Qi="440px",lb={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:oo,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)"},_t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:lb,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 sh(e,t){if(!(!e&&!t))return e?t?Is(e,t):e:t}function Ji(e){var t,r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w;return e?{..._t,...e,theme:sh(_t.theme,e.theme),darkTheme:sh(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=_t.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,J,le,ge,ue,G,ce,Be,ne,ee;let b=(de=_t.features)==null?void 0:de.artifacts,A=(J=e.features)==null?void 0:J.artifacts,H=(le=_t.features)==null?void 0:le.scrollToBottom,W=(ge=e.features)==null?void 0:ge.scrollToBottom,k=(ue=_t.features)==null?void 0:ue.scrollBehavior,N=(G=e.features)==null?void 0:G.scrollBehavior,q=(ce=_t.features)==null?void 0:ce.streamAnimation,Z=(Be=e.features)==null?void 0:Be.streamAnimation,me=(ne=_t.features)==null?void 0:ne.askUserQuestion,Ke=(ee=e.features)==null?void 0:ee.askUserQuestion,Ce=b===void 0&&A===void 0?void 0:{...b,...A,layout:{...b==null?void 0:b.layout,...A==null?void 0:A.layout}},Ie=H===void 0&&W===void 0?void 0:{...H,...W},Ue=k===void 0&&N===void 0?void 0:{...k,...N},Te=q===void 0&&Z===void 0?void 0:{...q,...Z},We=me===void 0&&Ke===void 0?void 0:{...me,...Ke,styles:{...me==null?void 0:me.styles,...Ke==null?void 0:Ke.styles}};return{..._t.features,...e.features,...Ie!==void 0?{scrollToBottom:Ie}:{},...Ue!==void 0?{scrollBehavior:Ue}:{},...Ce!==void 0?{artifacts:Ce}:{},...Te!==void 0?{streamAnimation:Te}:{},...We!==void 0?{askUserQuestion:We}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(s=_t.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=_t.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(g=(u=_t.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(p=e.layout)==null?void 0:p.messages)==null?void 0:m.avatar},timestamp:{...(C=(x=_t.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(M=_t.layout)==null?void 0:M.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(y=_t.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var op={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"}},np={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"}},ap={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:oo,maxWidth:Qi,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 qa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?qa(e,o):o}function Yi(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=qa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function sp(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function ih(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=ih(a,n):r[o]=n}return r}function db(e,t){return t?ih(e,t):e}function Va(e,t={}){var n,a,s,i,c,d,u,g,p,m,x,C,T;let r={palette:op,semantic:np,components:ap},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...r.semantic.colors.interactive,...(p=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:p.interactive},feedback:{...r.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:db(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=sp(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(M=>M.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Zi(e){var C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze,Y,pe,Me,Je,Ge,ke,je,Cr,Wt,ur,Eo,V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ga,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr;let t=Yi(e),r={};for(let[xe,dt]of Object.entries(t)){let tr=xe.replace(/\./g,"-");r[`--persona-${tr}`]=dt.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(T=r["--persona-semantic-colors-secondary"])!=null?T:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(M=r["--persona-semantic-colors-surface"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(P=r["--persona-semantic-colors-background"])!=null?P:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(b=r["--persona-semantic-colors-text-muted"])!=null?b:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(A=r["--persona-semantic-colors-text-inverse"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(H=r["--persona-semantic-colors-border"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(W=r["--persona-semantic-colors-divider"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(k=r["--persona-components-voice-recording-indicator"])!=null?k:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(N=r["--persona-components-voice-recording-background"])!=null?N:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(q=r["--persona-components-voice-processing-icon"])!=null?q:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Z=r["--persona-components-voice-speaking-icon"])!=null?Z:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ke=r["--persona-components-approval-requested-border"])!=null?Ke:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Ce=r["--persona-components-approval-requested-text"])!=null?Ce:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Ie=r["--persona-components-approval-requested-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-approval-approve-bg"]=(Ue=r["--persona-components-approval-approve-background"])!=null?Ue:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Te=r["--persona-components-approval-deny-background"])!=null?Te:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(We=r["--persona-components-attachment-image-background"])!=null?We:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(de=r["--persona-components-attachment-image-border"])!=null?de:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(J=r["--persona-semantic-typography-fontFamily"])!=null?J:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(le=r["--persona-semantic-typography-fontSize"])!=null?le:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ge=r["--persona-semantic-typography-fontWeight"])!=null?ge:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(ue=r["--persona-semantic-typography-lineHeight"])!=null?ue:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(G=r["--persona-palette-radius-sm"])!=null?G:"0.125rem",r["--persona-radius-md"]=(ce=r["--persona-palette-radius-md"])!=null?ce:"0.375rem",r["--persona-radius-lg"]=(Be=r["--persona-palette-radius-lg"])!=null?Be:"0.5rem",r["--persona-radius-xl"]=(ne=r["--persona-palette-radius-xl"])!=null?ne:"0.75rem",r["--persona-radius-full"]=(ee=r["--persona-palette-radius-full"])!=null?ee:"9999px",r["--persona-launcher-radius"]=(vt=(ie=r["--persona-components-launcher-borderRadius"])!=null?ie:r["--persona-palette-radius-full"])!=null?vt:"9999px",r["--persona-launcher-bg"]=(Lt=r["--persona-components-launcher-background"])!=null?Lt:r["--persona-primary"],r["--persona-launcher-fg"]=(gt=r["--persona-components-launcher-foreground"])!=null?gt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(_e=r["--persona-components-launcher-border"])!=null?_e:r["--persona-border"],r["--persona-button-primary-bg"]=(be=r["--persona-components-button-primary-background"])!=null?be:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ze=r["--persona-components-button-primary-foreground"])!=null?Ze:r["--persona-text-inverse"],r["--persona-button-radius"]=(pe=(Y=r["--persona-components-button-primary-borderRadius"])!=null?Y:r["--persona-palette-radius-full"])!=null?pe:"9999px",r["--persona-panel-radius"]=(Je=(Me=r["--persona-components-panel-borderRadius"])!=null?Me:r["--persona-radius-xl"])!=null?Je:"0.75rem",r["--persona-panel-border"]=(Ge=r["--persona-components-panel-border"])!=null?Ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(je=(ke=r["--persona-components-panel-shadow"])!=null?ke:r["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(Cr=r["--persona-components-launcher-shadow"])!=null?Cr:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(ur=(Wt=r["--persona-components-input-borderRadius"])!=null?Wt:r["--persona-radius-lg"])!=null?ur:"0.5rem",r["--persona-message-user-radius"]=(V=(Eo=r["--persona-components-message-user-borderRadius"])!=null?Eo:r["--persona-radius-lg"])!=null?V:"0.5rem",r["--persona-message-assistant-radius"]=(he=(j=r["--persona-components-message-assistant-borderRadius"])!=null?j:r["--persona-radius-lg"])!=null?he:"0.5rem",r["--persona-header-bg"]=(Xe=r["--persona-components-header-background"])!=null?Xe:r["--persona-surface"],r["--persona-header-border"]=(et=r["--persona-components-header-border"])!=null?et:r["--persona-divider"],r["--persona-header-icon-bg"]=(qe=r["--persona-components-header-iconBackground"])!=null?qe:r["--persona-primary"],r["--persona-header-icon-fg"]=(Ne=r["--persona-components-header-iconForeground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Pt=r["--persona-components-header-titleForeground"])!=null?Pt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Gt=r["--persona-components-header-subtitleForeground"])!=null?Gt:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Jt=r["--persona-components-header-actionIconForeground"])!=null?Jt:r["--persona-muted"];let o=(Pr=e.components)==null?void 0:Pr.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(z=e.components)==null?void 0:z.introCard;r["--persona-intro-card-bg"]=(Ht=r["--persona-components-introCard-background"])!=null?Ht:r["--persona-surface"],r["--persona-intro-card-radius"]=(oe=r["--persona-components-introCard-borderRadius"])!=null?oe:"1rem",r["--persona-intro-card-padding"]=(we=r["--persona-components-introCard-padding"])!=null?we:"1.5rem",r["--persona-intro-card-shadow"]=(At=(De=n==null?void 0:n.shadow)!=null?De:r["--persona-components-introCard-shadow"])!=null?At:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(ar=r["--persona-components-input-background"])!=null?ar:r["--persona-surface"],r["--persona-input-placeholder"]=(sr=r["--persona-components-input-placeholder"])!=null?sr:r["--persona-text-muted"],r["--persona-message-user-bg"]=(wr=r["--persona-components-message-user-background"])!=null?wr:r["--persona-accent"],r["--persona-message-user-text"]=(Ft=r["--persona-components-message-user-text"])!=null?Ft:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(ot=r["--persona-components-message-user-shadow"])!=null?ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Dt=r["--persona-components-message-assistant-background"])!=null?Dt:r["--persona-surface"],r["--persona-message-assistant-text"]=(lt=r["--persona-components-message-assistant-text"])!=null?lt:r["--persona-text"],r["--persona-message-assistant-border"]=(Yt=r["--persona-components-message-assistant-border"])!=null?Yt:r["--persona-border"],r["--persona-message-assistant-shadow"]=(so=r["--persona-components-message-assistant-shadow"])!=null?so:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(ir=(Rr=r["--persona-components-scrollToBottom-background"])!=null?Rr:r["--persona-button-primary-bg"])!=null?ir:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(ko=(Ur=r["--persona-components-scrollToBottom-foreground"])!=null?Ur:r["--persona-button-primary-fg"])!=null?ko:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(yt=r["--persona-components-scrollToBottom-border"])!=null?yt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(jr=r["--persona-components-scrollToBottom-size"])!=null?jr:"40px",r["--persona-scroll-to-bottom-radius"]=(yo=(zo=(Lo=r["--persona-components-scrollToBottom-borderRadius"])!=null?Lo:r["--persona-button-radius"])!=null?zo:r["--persona-radius-full"])!=null?yo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Nn=(ht=r["--persona-components-scrollToBottom-shadow"])!=null?ht:r["--persona-palette-shadows-sm"])!=null?Nn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Po=r["--persona-components-scrollToBottom-padding"])!=null?Po:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(On=r["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(ga=(qr=r["--persona-components-scrollToBottom-fontSize"])!=null?qr:r["--persona-palette-typography-fontSize-sm"])!=null?ga:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(cn=r["--persona-components-scrollToBottom-iconSize"])!=null?cn:"14px",r["--persona-tool-bubble-shadow"]=(jo=r["--persona-components-toolBubble-shadow"])!=null?jo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(pn=r["--persona-components-reasoningBubble-shadow"])!=null?pn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(un=r["--persona-components-composer-shadow"])!=null?un:"none",r["--persona-md-inline-code-bg"]=(_n=r["--persona-components-markdown-inlineCode-background"])!=null?_n:r["--persona-container"],r["--persona-md-inline-code-color"]=(Un=r["--persona-components-markdown-inlineCode-foreground"])!=null?Un:r["--persona-text"],r["--persona-md-link-color"]=(Ct=(fn=r["--persona-components-markdown-link-foreground"])!=null?fn:r["--persona-accent"])!=null?Ct:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(Gr=r["--persona-components-markdown-codeBlock-background"])!=null?Gr:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Kr=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Kr:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Ir=r["--persona-components-markdown-codeBlock-textColor"])!=null?Ir:"inherit",r["--persona-md-table-header-bg"]=(Mt=r["--persona-components-markdown-table-headerBackground"])!=null?Mt:r["--persona-container"],r["--persona-md-table-border-color"]=(io=r["--persona-components-markdown-table-borderColor"])!=null?io:r["--persona-border"],r["--persona-md-hr-color"]=(lo=r["--persona-components-markdown-hr-color"])!=null?lo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(Xr=r["--persona-components-markdown-blockquote-borderColor"])!=null?Xr:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(mn=r["--persona-components-markdown-blockquote-background"])!=null?mn:"transparent",r["--persona-md-blockquote-text-color"]=(Go=r["--persona-components-markdown-blockquote-textColor"])!=null?Go:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(gn=r["--persona-components-collapsibleWidget-container"])!=null?gn:r["--persona-surface"],r["--cw-surface"]=(Qr=r["--persona-components-collapsibleWidget-surface"])!=null?Qr:r["--persona-surface"],r["--cw-border"]=(Nt=r["--persona-components-collapsibleWidget-border"])!=null?Nt:r["--persona-border"],r["--persona-message-border"]=(Wr=r["--persona-components-message-border"])!=null?Wr:r["--persona-border"];let u=e.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(r["--persona-icon-btn-bg"]=g.background),g.border&&(r["--persona-icon-btn-border"]=g.border),g.color&&(r["--persona-icon-btn-color"]=g.color),g.padding&&(r["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(r["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(r["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(r["--persona-icon-btn-active-border"]=g.activeBorder));let p=u==null?void 0:u.labelButton;p&&(p.background&&(r["--persona-label-btn-bg"]=p.background),p.border&&(r["--persona-label-btn-border"]=p.border),p.color&&(r["--persona-label-btn-color"]=p.color),p.padding&&(r["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(r["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(r["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(r["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(r["--persona-label-btn-gap"]=p.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let xe=x.toolbar;xe.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,r["--persona-dropdown-bg"]=(co=r["--persona-dropdown-bg"])!=null?co:xe.copyMenuBackground),xe.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,r["--persona-dropdown-border"]=(hn=r["--persona-dropdown-border"])!=null?hn:xe.copyMenuBorder),xe.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,r["--persona-dropdown-shadow"]=(Ko=r["--persona-dropdown-shadow"])!=null?Ko:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(xn=r["--persona-dropdown-radius"])!=null?xn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ro=r["--persona-dropdown-item-hover-bg"])!=null?Ro:xe.copyMenuItemHoverBackground),xe.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(r["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(r["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(r["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(r["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(r["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(r["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(r["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let dt=(Jr=qa(e,xe.toolbarBackground))!=null?Jr:xe.toolbarBackground;r["--persona-artifact-toolbar-bg"]=dt}}return r}var lh={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 cb={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"}}},dh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ws=()=>{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"},pb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Ws()},ip=e=>pb(e),ub=e=>Va(e),fb=e=>{var r;let t=Va(void 0,{validate:!1});return Va({...e,palette:{...t.palette,colors:{...cb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},$a=e=>{let t=ip(e),r=dh(e==null?void 0:e.theme),o=dh(e==null?void 0:e.darkTheme);return t==="dark"?fb(Is(r!=null?r:{},o!=null?o:{})):ub(r)},mb=e=>Zi(e),Wn=(e,t)=>{let r=$a(t),o=mb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},el=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Ws())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ws());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var ch=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:p=>p.getAttribute("im-preserve")==="true",shouldReAppend:p=>p.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(p,m,x={}){p=u(p);let C=g(m),T=d(p,C,x),E=n(T,()=>i(T,p,C,M=>M.morphStyle==="innerHTML"?(a(M,p,C),Array.from(p.childNodes)):o(M,p,C)));return T.pantry.remove(),E}function o(p,m,x){let C=g(m);return a(p,C,x,m,m.nextSibling),Array.from(C.childNodes)}function n(p,m){var P;if(!p.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:C,selectionStart:T,selectionEnd:E}=x,M=m();return C&&C!==((P=document.activeElement)==null?void 0:P.getAttribute("id"))&&(x=p.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(T,E),M}let a=(function(){function p(y,w,b,A=null,H=null){w instanceof HTMLTemplateElement&&b instanceof HTMLTemplateElement&&(w=w.content,b=b.content),A||(A=w.firstChild);for(let W of b.childNodes){if(A&&A!=H){let N=x(y,W,A,H);if(N){N!==A&&T(y,A,N),s(N,W,y),A=N.nextSibling;continue}}if(W instanceof Element){let N=W.getAttribute("id");if(y.persistentIds.has(N)){let q=E(w,N,A,y);s(q,W,y),A=q.nextSibling;continue}}let k=m(w,W,A,y);k&&(A=k.nextSibling)}for(;A&&A!=H;){let W=A;A=A.nextSibling,C(y,W)}}function m(y,w,b,A){if(A.callbacks.beforeNodeAdded(w)===!1)return null;if(A.idMap.has(w)){let H=document.createElement(w.tagName);return y.insertBefore(H,b),s(H,w,A),A.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return y.insertBefore(H,b),A.callbacks.afterNodeAdded(H),H}}let x=(function(){function y(A,H,W,k){let N=null,q=H.nextSibling,Z=0,me=W;for(;me&&me!=k;){if(b(me,H)){if(w(A,me,H))return me;N===null&&(A.idMap.has(me)||(N=me))}if(N===null&&q&&b(me,q)&&(Z++,q=q.nextSibling,Z>=2&&(N=void 0)),A.activeElementAndParents.includes(me))break;me=me.nextSibling}return N||null}function w(A,H,W){let k=A.idMap.get(H),N=A.idMap.get(W);if(!N||!k)return!1;for(let q of k)if(N.has(q))return!0;return!1}function b(A,H){var N,q,Z;let W=A,k=H;return W.nodeType===k.nodeType&&W.tagName===k.tagName&&(!((N=W.getAttribute)!=null&&N.call(W,"id"))||((q=W.getAttribute)==null?void 0:q.call(W,"id"))===((Z=k.getAttribute)==null?void 0:Z.call(k,"id")))}return y})();function C(y,w){var b;if(y.idMap.has(w))P(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(b=w.parentNode)==null||b.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function T(y,w,b){let A=w;for(;A&&A!==b;){let H=A;A=A.nextSibling,C(y,H)}return A}function E(y,w,b,A){var W,k;let H=((k=(W=A.target).getAttribute)==null?void 0:k.call(W,"id"))===w&&A.target||A.target.querySelector(`[id="${w}"]`)||A.pantry.querySelector(`[id="${w}"]`);return M(H,A),P(y,H,b),H}function M(y,w){let b=y.getAttribute("id");for(;y=y.parentNode;){let A=w.idMap.get(y);A&&(A.delete(b),A.size||w.idMap.delete(y))}}function P(y,w,b){if(y.moveBefore)try{y.moveBefore(w,b)}catch{y.insertBefore(w,b)}else y.insertBefore(w,b)}return p})(),s=(function(){function p(M,P,y){return y.ignoreActive&&M===document.activeElement?null:(y.callbacks.beforeNodeMorphed(M,P)===!1||(M instanceof HTMLHeadElement&&y.head.ignore||(M instanceof HTMLHeadElement&&y.head.style!=="morph"?c(M,P,y):(m(M,P,y),E(M,y)||a(y,M,P))),y.callbacks.afterNodeMorphed(M,P)),M)}function m(M,P,y){let w=P.nodeType;if(w===1){let b=M,A=P,H=b.attributes,W=A.attributes;for(let k of W)T(k.name,b,"update",y)||b.getAttribute(k.name)!==k.value&&b.setAttribute(k.name,k.value);for(let k=H.length-1;0<=k;k--){let N=H[k];if(N&&!A.hasAttribute(N.name)){if(T(N.name,b,"remove",y))continue;b.removeAttribute(N.name)}}E(b,y)||x(b,A,y)}(w===8||w===3)&&M.nodeValue!==P.nodeValue&&(M.nodeValue=P.nodeValue)}function x(M,P,y){if(M instanceof HTMLInputElement&&P instanceof HTMLInputElement&&P.type!=="file"){let w=P.value,b=M.value;C(M,P,"checked",y),C(M,P,"disabled",y),P.hasAttribute("value")?b!==w&&(T("value",M,"update",y)||(M.setAttribute("value",w),M.value=w)):T("value",M,"remove",y)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&P instanceof HTMLOptionElement)C(M,P,"selected",y);else if(M instanceof HTMLTextAreaElement&&P instanceof HTMLTextAreaElement){let w=P.value,b=M.value;if(T("value",M,"update",y))return;w!==b&&(M.value=w),M.firstChild&&M.firstChild.nodeValue!==w&&(M.firstChild.nodeValue=w)}}function C(M,P,y,w){let b=P[y],A=M[y];if(b!==A){let H=T(y,M,"update",w);H||(M[y]=P[y]),b?H||M.setAttribute(y,""):T(y,M,"remove",w)||M.removeAttribute(y)}}function T(M,P,y,w){return M==="value"&&w.ignoreActiveValue&&P===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(M,P,y)===!1}function E(M,P){return!!P.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return p})();function i(p,m,x,C){if(p.head.block){let T=m.querySelector("head"),E=x.querySelector("head");if(T&&E){let M=c(T,E,p);return Promise.all(M).then(()=>{let P=Object.assign(p,{head:{block:!1,ignore:!0}});return C(P)})}}return C(p)}function c(p,m,x){let C=[],T=[],E=[],M=[],P=new Map;for(let w of m.children)P.set(w.outerHTML,w);for(let w of p.children){let b=P.has(w.outerHTML),A=x.head.shouldReAppend(w),H=x.head.shouldPreserve(w);b||H?A?T.push(w):(P.delete(w.outerHTML),E.push(w)):x.head.style==="append"?A&&(T.push(w),M.push(w)):x.head.shouldRemove(w)!==!1&&T.push(w)}M.push(...P.values());let y=[];for(let w of M){let b=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(b)!==!1){if("href"in b&&b.href||"src"in b&&b.src){let A,H=new Promise(function(W){A=W});b.addEventListener("load",function(){A()}),y.push(H)}p.appendChild(b),x.callbacks.afterNodeAdded(b),C.push(b)}}for(let w of T)x.callbacks.beforeNodeRemoved(w)!==!1&&(p.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(p,{added:C,kept:E,removed:T}),y}let d=(function(){function p(y,w,b){let{persistentIds:A,idMap:H}=M(y,w),W=m(b),k=W.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(k))throw`Do not understand how to morph style ${k}`;return{target:y,newContent:w,config:W,morphStyle:k,ignoreActive:W.ignoreActive,ignoreActiveValue:W.ignoreActiveValue,restoreFocus:W.restoreFocus,idMap:H,persistentIds:A,pantry:x(),activeElementAndParents:C(y),callbacks:W.callbacks,head:W.head}}function m(y){let w=Object.assign({},t);return Object.assign(w,y),w.callbacks=Object.assign({},t.callbacks,y.callbacks),w.head=Object.assign({},t.head,y.head),w}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function C(y){let w=[],b=document.activeElement;if((b==null?void 0:b.tagName)!=="BODY"&&y.contains(b))for(;b&&(w.push(b),b!==y);)b=b.parentElement;return w}function T(y){var b;let w=Array.from(y.querySelectorAll("[id]"));return(b=y.getAttribute)!=null&&b.call(y,"id")&&w.push(y),w}function E(y,w,b,A){for(let H of A){let W=H.getAttribute("id");if(w.has(W)){let k=H;for(;k;){let N=y.get(k);if(N==null&&(N=new Set,y.set(k,N)),N.add(W),k===b)break;k=k.parentElement}}}}function M(y,w){let b=T(y),A=T(w),H=P(b,A),W=new Map;E(W,H,y,b);let k=w.__idiomorphRoot||w;return E(W,H,k,A),{persistentIds:H,idMap:W}}function P(y,w){let b=new Set,A=new Map;for(let{id:W,tagName:k}of y)A.has(W)?b.add(W):A.set(W,k);let H=new Set;for(let{id:W,tagName:k}of w)H.has(W)?b.add(W):A.get(W)===k&&H.add(W);for(let W of b)H.delete(W);return H}return p})(),{normalizeElement:u,normalizeParent:g}=(function(){let p=new WeakSet;function m(E){return E instanceof Document?E.documentElement:E}function x(E){if(E==null)return document.createElement("div");if(typeof E=="string")return x(T(E));if(p.has(E))return E;if(E instanceof Node){if(E.parentNode)return new C(E);{let M=document.createElement("div");return M.append(E),M}}else{let M=document.createElement("div");for(let P of[...E])M.append(P);return M}}class C{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],P=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;P&&P!=this.nextSibling;)M.push(P),P=P.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((P,y)=>{if(y instanceof Element){y.matches(M)&&P.push(y);let w=y.querySelectorAll(M);for(let b=0;b<w.length;b++)P.push(w[b])}return P},[])}insertBefore(M,P){return this.realParentNode.insertBefore(M,P)}moveBefore(M,P){return this.realParentNode.moveBefore(M,P)}get __idiomorphRoot(){return this.originalNode}}function T(E){let M=new DOMParser,P=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(P.match(/<\/html>/)||P.match(/<\/head>/)||P.match(/<\/body>/)){let y=M.parseFromString(E,"text/html");if(P.match(/<\/html>/))return p.add(y),y;{let w=y.firstChild;return w&&p.add(w),w}}else{let w=M.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return p.add(w),w}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var tl=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;ch.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var rl={index:-1,draft:""};function ph(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...rl}}}function uh(e,t){var r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(u=(d=e.llmContent)==null?void 0:d.length)!=null?u:0,(p=(g=e.approval)==null?void 0:g.status)!=null?p:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(T=(C=e.toolCall)==null?void 0:C.name)!=null?T:"",(P=(M=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:M.length)!=null?P:0,(A=(b=(w=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:b.slice(-32))!=null?A:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(W=e.toolCall)!=null&&W.args?JSON.stringify(e.toolCall.args).length:0,(q=(N=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:N.length)!=null?q:0,(Ce=(Ke=(me=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:Ke.length)!=null?Ce:0,(We=(Te=(Ue=(Ie=e.reasoning)==null?void 0:Ie.chunks)==null?void 0:Ue[e.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?We:"",(J=(de=e.contentParts)==null?void 0:de.length)!=null?J:0,(le=e.stopReason)!=null?le:"",t].join("\0")}function fh(){return new Map}function mh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function gh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function hh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function ol(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function sn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function da(e,t){return sn(e)-e.scrollTop<=t}function nl(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,u=r-o;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:r}:!t&&n&&(!d||u>0)?{action:"resume",delta:u,nextLastScrollTop:r}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:u,nextLastScrollTop:r}:{action:"none",delta:u,nextLastScrollTop:r}}function al(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function xh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yh(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function bh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Lr=1e5,Hn=Lr+1;var Hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gb=["pre","code","a","script","style"],sl=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Hs.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Hs.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Hs.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Hs.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Hs.buffer}},Ch=[{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"}],Bs=new Map;for(let e of Ch)Bs.set(e.name,e);var ca=e=>{Bs.set(e.name,e)},cp=e=>{Ch.some(t=>t.name===e)||Bs.delete(e)},pp=()=>Array.from(Bs.keys()),Ds=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Bs.get(e))!=null?o:null},il=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
18
|
+
`);return a<0?"":e.slice(0,a)}return e},hb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},xb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},lp=/\s/,yb=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},bb=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(lp.test(a[i])){let d=i;for(;d<a.length&&lp.test(a[d]);)d+=1;s.appendChild(o.createTextNode(a.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=i;for(;u<a.length&&!lp.test(a[u]);)d.appendChild(hb(o,a[u],t,r.value)),r.value+=1,u+=1;s.appendChild(d),i=u}n.replaceChild(s,e)},vb=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(xb(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},Fs=(e,t,r,o)=>{var g,p;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((g=o==null?void 0:o.skipTags)!=null?g:gb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)yb(c,a)||i.push(c),c=s.nextNode();let d={value:(p=o==null?void 0:o.startIndex)!=null?p:0},u=t==="char"?bb:vb;for(let m of i)u(m,r,d);return n.innerHTML},ll=(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},Ns=(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 r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},vh=new WeakMap,Cb=(e,t)=>{var a;if(!e.styles)return;let r=vh.get(t);if(r||(r=new Set,vh.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},dp=new WeakMap,wb=(e,t)=>{if(!e.onAttach)return;let r=dp.get(t);if(r||(r=new Map,dp.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},wh=e=>{let t=dp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},up=(e,t)=>{Cb(e,t),wb(e,t)};function fp(e,t=Lr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Os=0,Bn=null;function mp(e=document){var r;if(Os++,Os===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Bn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Os=Math.max(0,Os-1),Os===0&&Bn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Bn.originalOverflow,n.style.position=Bn.originalPosition,n.style.top=Bn.originalTop,n.style.width=Bn.originalWidth,a.scrollTo(0,Bn.scrollY),Bn=null}}}var _s={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},pr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Dn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},no=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:_s.side,width:(n=t==null?void 0:t.width)!=null?n:_s.width,animate:(a=t==null?void 0:t.animate)!=null?a:_s.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:_s.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:_s.maxHeight}};var To={"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 Sb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",dl=(e,t={})=>{var T,E,M,P,y,w;let{showClose:r=!0,wrapperClassName:o=Sb,buttonSize:n,iconSize:a="28px"}=t,s=(T=e==null?void 0:e.launcher)!=null?T:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=S("div",o),d=(M=s.closeButtonTooltipText)!=null?M:"Close chat",u=(P=s.closeButtonShowTooltip)!=null?P:!0,g=(y=s.closeButtonIconName)!=null?y:"x",p=(w=s.closeButtonIconText)!=null?w:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=kt("button",{className:vs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||_r.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),C=ve(g,a,"currentColor",1);if(C?(C.style.display="block",x.appendChild(C)):x.textContent=p,c.appendChild(x),u&&d){let b=null,A=()=>{if(b)return;let W=x.ownerDocument,k=W.body;if(!k)return;b=Vo(W,"div","persona-clear-chat-tooltip"),b.textContent=d;let N=Vo(W,"div");N.className="persona-clear-chat-tooltip-arrow",b.appendChild(N);let q=x.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Hn),b.style.left=`${q.left+q.width/2}px`,b.style.top=`${q.top-8}px`,b.style.transform="translate(-50%, -100%)",k.appendChild(b)},H=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};c.addEventListener("mouseenter",A),c.addEventListener("mouseleave",H),x.addEventListener("focus",A),x.addEventListener("blur",H),c._cleanupTooltip=()=>{H(),c.removeEventListener("mouseenter",A),c.removeEventListener("mouseleave",H),x.removeEventListener("focus",A),x.removeEventListener("blur",H)}}return{button:x,wrapper:c}},Ab="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",cl=(e,t={})=>{var b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue;let{wrapperClassName:r=Ab,buttonSize:o,iconSize:n="20px"}=t,s=(A=((b=e==null?void 0:e.launcher)!=null?b:{}).clearChat)!=null?A:{},i=(H=o!=null?o:s.size)!=null?H:"32px",c=(W=s.iconName)!=null?W:"refresh-cw",d=(k=s.iconColor)!=null?k:"",u=(N=s.backgroundColor)!=null?N:"",g=(q=s.borderWidth)!=null?q:"",p=(Z=s.borderColor)!=null?Z:"",m=(me=s.borderRadius)!=null?me:"",x=(Ke=s.paddingX)!=null?Ke:"",C=(Ce=s.paddingY)!=null?Ce:"",T=(Ie=s.tooltipText)!=null?Ie:"Clear chat",E=(Ue=s.showTooltip)!=null?Ue:!0,M=S("div",r),P=!!(g||p),y=kt("button",{className:vs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:d||_r.actionIconColor,backgroundColor:u||void 0,border:P?`${g||"0px"} solid ${p||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),w=ve(c,n,"currentColor",1);if(w&&(w.style.display="block",y.appendChild(w)),M.appendChild(y),E&&T){let Te=null,We=()=>{if(Te)return;let J=y.ownerDocument,le=J.body;if(!le)return;Te=Vo(J,"div","persona-clear-chat-tooltip"),Te.textContent=T;let ge=Vo(J,"div");ge.className="persona-clear-chat-tooltip-arrow",Te.appendChild(ge);let ue=y.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(Hn),Te.style.left=`${ue.left+ue.width/2}px`,Te.style.top=`${ue.top-8}px`,Te.style.transform="translate(-50%, -100%)",le.appendChild(Te)},de=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};M.addEventListener("mouseenter",We),M.addEventListener("mouseleave",de),y.addEventListener("focus",We),y.addEventListener("blur",de),M._cleanupTooltip=()=>{de(),M.removeEventListener("mouseenter",We),M.removeEventListener("mouseleave",de),y.removeEventListener("focus",We),y.removeEventListener("blur",de)}}return{button:y,wrapper:M}};var _r={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))"},ln=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We;let{config:t,showClose:r=!0}=e,o=kt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(w=t==null?void 0:t.launcher)!=null?w:{},a=(b=n.headerIconSize)!=null?b:"48px",s=(A=n.closeButtonPlacement)!=null?A:"inline",i=(H=n.headerIconHidden)!=null?H:!1,c=n.headerIconName,d=kt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let de=parseFloat(a)||24,J=ve(c,de*.6,"currentColor",1);J?d.replaceChildren(J):d.textContent=(k=(W=t==null?void 0:t.launcher)==null?void 0:W.agentIconText)!=null?k:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let de=S("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=a,de.style.width=a,d.replaceChildren(de)}else d.textContent=(Z=(q=t==null?void 0:t.launcher)==null?void 0:q.agentIconText)!=null?Z:"\u{1F4AC}";let u=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=kt("span",{className:"persona-text-base persona-font-semibold",text:(Ke=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?Ke:"Chat Assistant",style:{color:_r.titleColor}}),p=kt("span",{className:"persona-text-xs",text:(Ie=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:_r.subtitleColor}});u.append(g,p),i?o.append(u):o.append(d,u);let m=(Ue=n.clearChat)!=null?Ue:{},x=(Te=m.enabled)!=null?Te:!0,C=(We=m.placement)!=null?We:"inline",T=null,E=null;if(x){let J=cl(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=J.button,E=J.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="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:P,wrapper:y}=dl(t,{showClose:r,wrapperClassName:M});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:p,closeButton:P,closeButtonWrapper:y,clearChatButton:T,clearChatButtonWrapper:E}},pa=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.placement)!=null?d:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Fn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=S("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Hn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let T=document.createElement("hr");s.appendChild(T)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let T=ve(m.icon,16,"currentColor",1.5);T&&x.appendChild(T)}let C=document.createElement("span");C.textContent=m.label,x.appendChild(C),x.addEventListener("click",T=>{T.stopPropagation(),u(),r(m.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function d(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function g(){s.classList.contains("persona-hidden")?d():u()}function p(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:u,toggle:g,destroy:p}}function yr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=S("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=ve(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[u,g]of Object.entries(i))c.setAttribute(u,g);return c}function Us(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let u=S("button",d);if(u.type="button",u.setAttribute("aria-label",r),t){let p=ve(t,a!=null?a:14,"currentColor",2);p&&u.appendChild(p)}let g=S("span");if(g.textContent=r,u.appendChild(g),i&&u.addEventListener("click",i),c)for(let[p,m]of Object.entries(c))u.setAttribute(p,m);return u}function Sh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=S("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===s?"true":"false")}for(let u of t){let g;u.icon?g=yr({icon:u.icon,label:u.label,onClick:()=>{s=u.id,c(),o(u.id)}}):(g=S("button","persona-icon-btn"),g.type="button",g.setAttribute("aria-label",u.label),g.title=u.label,g.textContent=u.label,g.addEventListener("click",()=>{s=u.id,c(),o(u.id)})),g.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:g}),a.appendChild(g)}function d(u){s=u,c()}return{element:a,setSelected:d}}function pl(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,d=S("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let u=S("span","persona-combo-btn-label");u.textContent=t,d.appendChild(u);let g=ve(r,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),c&&(d.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",d.style.padding=(x=c.padding)!=null?x:"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{var C,T;d.style.backgroundColor=(C=c.background)!=null?C:"",d.style.borderColor=(T=c.border)!=null?T:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let p=Fn({items:o,onSelect:C=>{d.setAttribute("aria-expanded","false"),n(C)},anchor:d,position:a,portal:s});return s||d.appendChild(p.element),d.addEventListener("click",C=>{C.stopPropagation();let T=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",T?"false":"true"),p.toggle()}),d.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),d.click())}),{element:d,setLabel:C=>{u.textContent=C,d.setAttribute("aria-label",C)},open:()=>{d.setAttribute("aria-expanded","true"),p.show()},close:()=>{d.setAttribute("aria-expanded","false"),p.hide()},toggle:()=>{let C=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",C?"false":"true"),p.toggle()},destroy:()=>{p.destroy(),d.remove()}}}var gp=e=>{var o;let t=ln({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Mb(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=S("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",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=ve(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=S("div","persona-relative");c.appendChild(i);let d=Fn({items:s.menuItems,onSelect:u=>r==null?void 0:r(u),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",u=>{u.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var hp=e=>{var M,P,y,w,b,A,H,W,k;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(M=t==null?void 0:t.launcher)!=null?M:{},i=S("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 c=n==null?void 0:n.titleMenu,d,u;if(c)d=pl({label:(P=s.title)!=null?P:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=_r.titleColor,u=(y=d.querySelector(".persona-combo-btn-label"))!=null?y:d;else{if(d=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=S("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=_r.titleColor,u.textContent=(w=s.title)!=null?w:"Chat Assistant",d.appendChild(u),Mb(d,n==null?void 0:n.trailingActions,(b=n==null?void 0:n.onAction)!=null?b:a),n!=null&&n.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let q=n.onTitleClick;d.addEventListener("click",Z=>{Z.target.closest("button")||q()}),d.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),q())})}let N=n==null?void 0:n.titleRowHover;N&&(d.style.borderRadius=(A=N.borderRadius)!=null?A:"10px",d.style.padding=(H=N.padding)!=null?H:"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{var q,Z;d.style.backgroundColor=(q=N.background)!=null?q:"",d.style.borderColor=(Z=N.border)!=null?Z:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=(W=s.closeButtonSize)!=null?W:"32px",p=S("div",""),m=S("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=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||_r.actionIconColor;let x=(k=s.closeButtonIconName)!=null?k:"x",C=ve(x,"28px","currentColor",1);C?m.appendChild(C):m.textContent="\xD7",o&&m.addEventListener("click",o),p.appendChild(m),i.appendChild(p);let T=S("div");T.style.display="none";let E=S("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:E,closeButton:m,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},ul={default:gp,minimal:hp},xp=e=>{var t;return(t=ul[e])!=null?t:ul.default},za=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let d=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=S("div");u.style.display="none";let g=S("span"),p=S("span"),m=S("button");m.style.display="none";let x=S("div");return x.style.display="none",{header:d,iconHolder:u,headerTitle:g,headerSubtitle:p,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=xp(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var fl=e=>{var s,i;let t=S("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.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 r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}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:a}},ml=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(b=t.useIcon)!=null?b:!1,o=(A=t.iconText)!=null?A:"\u2191",n=t.iconName,a=(H=t.stopIconName)!=null?H:"square",s=(W=t.tooltipText)!=null?W:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",c=(q=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?q:"Send",d=(me=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?me:"Stop",u=(Ke=t.showTooltip)!=null?Ke:!1,g=(Ce=t.size)!=null?Ce:"40px",p=t.backgroundColor,m=t.textColor,x=S("div","persona-send-button-wrapper"),C=kt("button",{className:vs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!p&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?g:void 0,height:r?g:void 0,minWidth:r?g:void 0,minHeight:r?g:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,E=null;if(r){let Ie=parseFloat(g)||24,Ue=(m==null?void 0:m.trim())||"currentColor";n?(T=ve(n,Ie,Ue,2),T?C.appendChild(T):C.textContent=o):C.textContent=o,E=ve(a,Ie,Ue,2)}else C.textContent=c;let M=null;u&&s&&(M=S("div","persona-send-button-tooltip"),M.textContent=s,x.appendChild(M)),C.setAttribute("aria-label",s),x.appendChild(C);let P="send";return{button:C,wrapper:x,setMode:Ie=>{if(Ie===P)return;P=Ie;let Ue=Ie==="stop"?i:s;if(C.setAttribute("aria-label",Ue),M&&(M.textContent=Ue),r){if(T&&E){let Te=Ie==="stop"?E:T;C.replaceChildren(Te)}}else C.textContent=Ie==="stop"?d:c}}},gl=e=>{var M,P,y,w,b,A,H,W,k,N,q,Z;let t=(M=e==null?void 0:e.voiceRecognition)!=null?M:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(o||n))return null;let s=(w=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?w:"40px",i=(b=t.iconName)!=null?b:"mic",c=(A=t.iconSize)!=null?A:s,d=parseFloat(c)||24,u=(W=t.backgroundColor)!=null?W:(H=e==null?void 0:e.sendButton)==null?void 0:H.backgroundColor,g=(N=t.iconColor)!=null?N:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor,p=S("div","persona-send-button-wrapper"),m=kt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ve(i,d,g||"currentColor",1.5);C?m.appendChild(C):m.textContent="\u{1F3A4}",p.appendChild(m);let T=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&T){let me=S("div","persona-send-button-tooltip");me.textContent=T,p.appendChild(me)}return{button:m,wrapper:p}},hl=e=>{var x,C,T,E,M,P,y,w;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(T=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?T:"40px",o=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=S("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:an).join(","),n.multiple=((M=t.maxFiles)!=null?M:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(P=t.buttonIconName)!=null?P:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=S("div","persona-send-button-wrapper"),u=kt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=ve(a,c,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",b=>{b.preventDefault(),n.click()}),d.appendChild(u);let p=(w=t.buttonTooltipText)!=null?w:"Attach file",m=S("div","persona-send-button-tooltip");return m.textContent=p,d.appendChild(m),{button:u,wrapper:d,input:n,previewsContainer:o}},xl=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let d=S("a");d.href=t.idleLink,d.target="_blank",d.rel="noopener noreferrer",d.textContent=a,d.style.color="inherit",d.style.textDecoration="none",o.appendChild(d)}else o.textContent=a;return o},yl=()=>kt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ja=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=yl(),n=kt("form",{className:"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",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=fl(t);s();let i=ml(t),c=gl(t),d=hl(t),u=xl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let g=kt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),p=S("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=S("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&p.append(d.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),g.append(p,m),n.append(g),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),r.append(o,n,u),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:u,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:g,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var Ah=()=>{let e=kt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),r=ve("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=S("span","persona-pill-peek__text"),n=S("span","persona-pill-peek__caret"),a=ve("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Mh=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=yl();o.style.display="none";let n=xl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=fl(t);a.style.maxHeight="100px",s();let i=ml(t),c=gl(t),d=hl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let u=kt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=S("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&g.append(d.wrapper);let p=S("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&p.append(c.wrapper),p.append(i.wrapper),u.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),d&&u.append(d.input),u.append(g,a,p),d&&r.append(d.previewsContainer),r.append(u,o,n);let m=u;return{footer:r,suggestions:o,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:n,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:m,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Th=e=>{var u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,r=pr(e);if(Dn(e)){let N=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.composerBar)!=null?m:{},q=S("div","persona-widget-wrapper persona-fixed persona-transition");q.setAttribute("data-persona-composer-bar",""),q.dataset.state="collapsed",q.dataset.expandedSize=(x=N.expandedSize)!=null?x:"anchored",q.style.zIndex=String((T=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?T:Lr);let Z=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",q.appendChild(Z);let me=S("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=N.expandedSize)!=null?E:"anchored",me.style.zIndex=String((P=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?P:Lr),{wrapper:q,panel:Z,pillRoot:me}}if(r){let N=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),q=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(q),{wrapper:N,panel:q}}if(!t){let N=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?w:"100%";return N.style.width=Z,q.style.width="100%",N.appendChild(q),{wrapper:N,panel:q}}let n=(b=e==null?void 0:e.launcher)!=null?b:{},a=n.position&&To[n.position]?To[n.position]:To["bottom-right"],s=S("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?H:Lr);let i=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(k=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?k:e==null?void 0:e.launcherWidth,d=c!=null?c:oo;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Tb=(e,t)=>{var y,w,b,A,H,W,k,N,q;let r=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=dl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(b=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:w.enabled)!=null?b:!0,s=null,i=null;if(a){let Z=cl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=kt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=kt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let u=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),g=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),p=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,g),m=S("div","persona-flex persona-flex-col persona-gap-3"),x=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((q=e==null?void 0:e.copy)==null?void 0:q.showWelcomeCard)!==!1||(p.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(p,m);let T=kt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=Mh({config:e}),{root:M,textNode:P}=Ah();return r.append(c,n,d,T),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:m,composerOverlay:T,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:u,introSubtitle:g,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:c,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:M,peekTextNode:P}},Eh=(e,t=!0)=>{var T,E,M,P,y,w,b,A,H;if(Dn(e))return Tb(e,t);let r=kt("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=(T=e==null?void 0:e.layout)==null?void 0:T.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?za(e,o,{showClose:t}):ln({config:e,showClose:t}),s=kt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),c=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(w=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?w:"Ask anything about your account or products."}),d=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:pr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),u=S("div","persona-flex persona-flex-col persona-gap-3"),g=(b=e==null?void 0:e.layout)==null?void 0:b.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((A=e==null?void 0:e.copy)==null?void 0:A.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,u);let m=ja({config:e}),x=((H=e==null?void 0:e.layout)==null?void 0:H.showFooter)!==!1;n?pa(r,a,e):(a.header.style.display="none",pa(r,a,e)),r.append(s);let C=kt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(m.footer.style.display="none"),r.append(m.footer),r.append(C),{container:r,body:s,messagesWrapper:u,composerOverlay:C,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:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.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 yp=(e,t)=>{let r=S("button");r.type="button",r.innerHTML=`
|
|
64
19
|
<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>
|
|
65
20
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
66
21
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -68,14 +23,14 @@ _Details: ${t.message}_`:o}var Zs=r=>({isError:!0,content:[{type:"text",text:r}]
|
|
|
68
23
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
69
24
|
</span>
|
|
70
25
|
<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>
|
|
71
|
-
`,t.addEventListener("click",e);let o=a=>{var L,x,w,v,E,H,I,P,z,j,ie,ve,Xe;let s=(L=a.launcher)!=null?L:{},i=Lr(a),d=t.querySelector("[data-role='launcher-title']");if(d){let Ae=(x=s.title)!=null?x:"Chat Assistant";d.textContent=Ae,d.setAttribute("title",Ae)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let Ae=(w=s.subtitle)!=null?w:"Get answers fast";l.textContent=Ae,l.setAttribute("title",Ae)}let u=t.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let Ae=(v=s.agentIconSize)!=null?v:"40px";if(f.style.height=Ae,f.style.width=Ae,f.innerHTML="",s.agentIconName){let We=parseFloat(Ae)||24,Me=Ee(s.agentIconName,We*.6,"var(--persona-text-inverse, #ffffff)",2);Me?(f.appendChild(Me),f.style.display=""):(f.textContent=(E=s.agentIconText)!=null?E:"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}",f.style.display="")}let p=t.querySelector("[data-role='launcher-image']");if(p){let Ae=(I=s.agentIconSize)!=null?I:"40px";p.style.height=Ae,p.style.width=Ae,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(p.src=s.iconUrl,p.style.display="block"):p.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ae=(P=s.callToActionIconSize)!=null?P:"32px";m.style.height=Ae,m.style.width=Ae,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.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(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,We=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Me=parseFloat(Ae)||24,Ue=Math.max(Me-We,8),Be=Ee(s.callToActionIconName,Ue,"currentColor",2);Be?m.appendChild(Be):m.textContent=(z=s.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(j=s.callToActionIconText)!=null?j:"\u2197"}let y=s.position&&tn[s.position]?tn[s.position]:tn["bottom-right"],h="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?T:`${h} ${y}`,i||(t.style.zIndex=String((ie=s.zIndex)!=null?ie:so));let M="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(ve=s.border)!=null?ve:M,t.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Xe=s.collapsedMaxWidth)!=null?Xe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},n=()=>{t.removeEventListener("click",e),t.remove()};return r&&o(r),{element:t,update:o,destroy:n}};var zv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ol=(r,e={})=>{var h,T,M,k,L,x;let{showClose:t=!0,wrapperClassName:o=zv,buttonSize:n,iconSize:a="28px"}=e,s=(h=r==null?void 0:r.launcher)!=null?h:{},i=(T=n!=null?n:s.closeButtonSize)!=null?T:"32px",d=C("div",o),l=C("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(M=s.closeButtonTooltipText)!=null?M:"Close chat",f=(k=s.closeButtonShowTooltip)!=null?k:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let p=(L=s.closeButtonIconName)!=null?L:"x",m=(x=s.closeButtonIconText)!=null?x:"\xD7";l.style.color=s.closeButtonColor||Ao.actionIconColor;let y=Ee(p,a,"currentColor",1);if(y?(y.style.display="block",l.appendChild(y)):l.textContent=m,s.closeButtonBackgroundColor?(l.style.backgroundColor=s.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let w=s.closeButtonBorderWidth||"0px",v=s.closeButtonBorderColor||"transparent";l.style.border=`${w} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(l.style.borderRadius=s.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(l.style.paddingLeft=s.closeButtonPaddingX,l.style.paddingRight=s.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),s.closeButtonPaddingY?(l.style.paddingTop=s.closeButtonPaddingY,l.style.paddingBottom=s.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),f&&u){let w=null,v=()=>{if(w)return;let H=l.ownerDocument,I=H.body;if(!I)return;w=un(H,"div","persona-clear-chat-tooltip"),w.textContent=u;let P=un(H,"div");P.className="persona-clear-chat-tooltip-arrow",w.appendChild(P);let z=l.getBoundingClientRect();w.style.position="fixed",w.style.zIndex=String(jn),w.style.left=`${z.left+z.width/2}px`,w.style.top=`${z.top-8}px`,w.style.transform="translate(-50%, -100%)",I.appendChild(w)},E=()=>{w&&w.parentNode&&(w.parentNode.removeChild(w),w=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",E),l.addEventListener("focus",v),l.addEventListener("blur",E),d._cleanupTooltip=()=>{E(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",E),l.removeEventListener("focus",v),l.removeEventListener("blur",E)}}return{button:l,wrapper:d}},$v="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",_l=(r,e={})=>{var w,v,E,H,I,P,z,j,ie,ve,Xe,Ae,We;let{wrapperClassName:t=$v,buttonSize:o,iconSize:n="20px"}=e,s=(v=((w=r==null?void 0:r.launcher)!=null?w:{}).clearChat)!=null?v:{},i=(E=o!=null?o:s.size)!=null?E:"32px",d=(H=s.iconName)!=null?H:"refresh-cw",l=(I=s.iconColor)!=null?I:"",u=(P=s.backgroundColor)!=null?P:"",f=(z=s.borderWidth)!=null?z:"",p=(j=s.borderColor)!=null?j:"",m=(ie=s.borderRadius)!=null?ie:"",y=(ve=s.paddingX)!=null?ve:"",h=(Xe=s.paddingY)!=null?Xe:"",T=(Ae=s.tooltipText)!=null?Ae:"Clear chat",M=(We=s.showTooltip)!=null?We:!0,k=C("div",t),L=C("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",T),L.style.color=l||Ao.actionIconColor;let x=Ee(d,n,"currentColor",1);if(x&&(x.style.display="block",L.appendChild(x)),u&&(L.style.backgroundColor=u,L.classList.remove("hover:persona-bg-gray-100")),f||p){let Me=f||"0px",Ue=p||"transparent";L.style.border=`${Me} solid ${Ue}`,L.classList.remove("persona-border-none")}if(m&&(L.style.borderRadius=m,L.classList.remove("persona-rounded-full")),y&&(L.style.paddingLeft=y,L.style.paddingRight=y),h&&(L.style.paddingTop=h,L.style.paddingBottom=h),k.appendChild(L),M&&T){let Me=null,Ue=()=>{if(Me)return;let Z=L.ownerDocument,ne=Z.body;if(!ne)return;Me=un(Z,"div","persona-clear-chat-tooltip"),Me.textContent=T;let me=un(Z,"div");me.className="persona-clear-chat-tooltip-arrow",Me.appendChild(me);let be=L.getBoundingClientRect();Me.style.position="fixed",Me.style.zIndex=String(jn),Me.style.left=`${be.left+be.width/2}px`,Me.style.top=`${be.top-8}px`,Me.style.transform="translate(-50%, -100%)",ne.appendChild(Me)},Be=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};k.addEventListener("mouseenter",Ue),k.addEventListener("mouseleave",Be),L.addEventListener("focus",Ue),L.addEventListener("blur",Be),k._cleanupTooltip=()=>{Be(),k.removeEventListener("mouseenter",Ue),k.removeEventListener("mouseleave",Be),L.removeEventListener("focus",Ue),L.removeEventListener("blur",Be)}}return{button:L,wrapper:k}};var Ao={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))"},kn=r=>{var w,v,E,H,I,P,z,j,ie,ve,Xe,Ae,We,Me,Ue,Be;let{config:e,showClose:t=!0}=r,o=C("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let n=(w=e==null?void 0:e.launcher)!=null?w:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(E=n.closeButtonPlacement)!=null?E:"inline",i=(H=n.headerIconHidden)!=null?H:!1,d=n.headerIconName,l=C("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=a,l.style.width=a,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 Z=parseFloat(a)||24,ne=Ee(d,Z*.6,"currentColor",1);ne?l.replaceChildren(ne):l.textContent=(P=(I=e==null?void 0:e.launcher)==null?void 0:I.agentIconText)!=null?P:"\u{1F4AC}"}else if((z=e==null?void 0:e.launcher)!=null&&z.iconUrl){let Z=C("img");Z.src=e.launcher.iconUrl,Z.alt="",Z.className="persona-rounded-xl persona-object-cover",Z.style.height=a,Z.style.width=a,l.replaceChildren(Z)}else l.textContent=(ie=(j=e==null?void 0:e.launcher)==null?void 0:j.agentIconText)!=null?ie:"\u{1F4AC}";let u=C("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=C("span","persona-text-base persona-font-semibold");f.style.color=Ao.titleColor,f.textContent=(Xe=(ve=e==null?void 0:e.launcher)==null?void 0:ve.title)!=null?Xe:"Chat Assistant";let p=C("span","persona-text-xs");p.style.color=Ao.subtitleColor,p.textContent=(We=(Ae=e==null?void 0:e.launcher)==null?void 0:Ae.subtitle)!=null?We:"Here to help you get answers fast",u.append(f,p),i?o.append(u):o.append(l,u);let m=(Me=n.clearChat)!=null?Me:{},y=(Ue=m.enabled)!=null?Ue:!0,h=(Be=m.placement)!=null?Be:"inline",T=null,M=null;if(y){let ne=_l(e,{wrapperClassName:h==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=ne.button,M=ne.wrapper,h==="top-right"&&(M.style.right="48px"),h==="inline"&&o.appendChild(M)}let k=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&h==="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:x}=Ol(e,{showClose:t,wrapperClassName:k});return s!=="top-right"&&o.appendChild(x),{header:o,iconHolder:l,headerTitle:f,headerSubtitle:p,closeButton:L,closeButtonWrapper:x,clearChatButton:T,clearChatButtonWrapper:M}},Ta=(r,e,t)=>{var s,i,d,l;let o=(s=t==null?void 0:t.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";r.appendChild(e.header),n==="top-right"&&(r.style.position="relative",r.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&a==="top-right"&&(r.style.position="relative",r.appendChild(e.clearChatButtonWrapper))};function Xn(r){let{items:e,onSelect:t,anchor:o,position:n="bottom-left",portal:a}=r,s=C("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(jn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of e){if(m.dividerBefore){let T=document.createElement("hr");s.appendChild(T)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",m.id),m.destructive&&y.setAttribute("data-destructive",""),m.icon){let T=Ee(m.icon,16,"currentColor",1.5);T&&y.appendChild(T)}let h=document.createElement("span");h.textContent=m.label,y.appendChild(h),y.addEventListener("click",T=>{T.stopPropagation(),u(),t(m.id)}),s.appendChild(y)}let i=null;function d(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function l(){d(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=y=>{!s.contains(y.target)&&!o.contains(y.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function f(){s.classList.contains("persona-hidden")?l():u()}function p(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:u,toggle:f,destroy:p}}function Br(r){let{icon:e,label:t,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=r,d=C("button","persona-icon-btn"+(a?" "+a:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Ee(e,o!=null?o:16,"currentColor",n!=null?n:2);if(l&&d.appendChild(l),s&&d.addEventListener("click",s),i)for(let[u,f]of Object.entries(i))d.setAttribute(u,f);return d}function ci(r){let{icon:e,label:t,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:d}=r,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+n,s&&(l+=" "+s);let u=C("button",l);if(u.type="button",u.setAttribute("aria-label",t),e){let p=Ee(e,a!=null?a:14,"currentColor",2);p&&u.appendChild(p)}let f=C("span");if(f.textContent=t,u.appendChild(f),i&&u.addEventListener("click",i),d)for(let[p,m]of Object.entries(d))u.setAttribute(p,m);return u}function Wx(r){let{items:e,selectedId:t,onSelect:o,className:n}=r,a=C("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===s?"true":"false")}for(let u of e){let f;u.icon?f=Br({icon:u.icon,label:u.label,onClick:()=>{s=u.id,d(),o(u.id)}}):(f=C("button","persona-icon-btn"),f.type="button",f.setAttribute("aria-label",u.label),f.title=u.label,f.textContent=u.label,f.addEventListener("click",()=>{s=u.id,d(),o(u.id)})),f.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:f}),a.appendChild(f)}function l(u){s=u,d()}return{element:a,setSelected:l}}function Nl(r){var m,y;let{label:e,icon:t="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:d}=r,l=C("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",e);let u=C("span","persona-combo-btn-label");u.textContent=e,l.appendChild(u);let f=Ee(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",l.appendChild(f)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(y=d.padding)!=null?y:"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 h,T;l.style.backgroundColor=(h=d.background)!=null?h:"",l.style.borderColor=(T=d.border)!=null?T:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let p=Xn({items:o,onSelect:h=>{l.setAttribute("aria-expanded","false"),n(h)},anchor:l,position:a,portal:s});return s||l.appendChild(p.element),l.addEventListener("click",h=>{h.stopPropagation();let T=!p.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",T?"false":"true"),p.toggle()}),l.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),l.click())}),{element:l,setLabel:h=>{u.textContent=h,l.setAttribute("aria-label",h)},open:()=>{l.setAttribute("aria-expanded","true"),p.show()},close:()=>{l.setAttribute("aria-expanded","false"),p.hide()},toggle:()=>{let h=!p.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",h?"false":"true"),p.toggle()},destroy:()=>{p.destroy(),l.remove()}}}var eu=r=>{var o;let e=kn({config:r.config,showClose:r.showClose,onClose:r.onClose,onClearChat:r.onClearChat}),t=(o=r.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(t){let n=e.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>t()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),t())}))}return e};function Vv(r,e,t){var o,n,a;if(e!=null&&e.length)for(let s of e){let i=C("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",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let d=Ee(s.icon,14,"currentColor",2);d&&i.appendChild(d)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let d=C("div","persona-relative");d.appendChild(i);let l=Xn({items:s.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),r.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(s.id)),r.appendChild(i)}}var tu=r=>{var k,L,x,w,v,E,H,I,P;let{config:e,showClose:t=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=r,s=(k=e==null?void 0:e.launcher)!=null?k:{},i=C("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=n==null?void 0:n.titleMenu,l,u;if(d)l=Nl({label:(L=s.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Ao.titleColor,u=(x=l.querySelector(".persona-combo-btn-label"))!=null?x:l;else{if(l=C("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=C("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Ao.titleColor,u.textContent=(w=s.title)!=null?w:"Chat Assistant",l.appendChild(u),Vv(l,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let j=n.onTitleClick;l.addEventListener("click",ie=>{ie.target.closest("button")||j()}),l.addEventListener("keydown",ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),j())})}let z=n==null?void 0:n.titleRowHover;z&&(l.style.borderRadius=(E=z.borderRadius)!=null?E:"10px",l.style.padding=(H=z.padding)!=null?H:"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,ie;l.style.backgroundColor=(j=z.background)!=null?j:"",l.style.borderColor=(ie=z.border)!=null?ie:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let f=(I=s.closeButtonSize)!=null?I:"32px",p=C("div",""),m=C("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=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=s.closeButtonColor||Ao.actionIconColor;let y=(P=s.closeButtonIconName)!=null?P:"x",h=Ee(y,"28px","currentColor",1);h?m.appendChild(h):m.textContent="\xD7",o&&m.addEventListener("click",o),p.appendChild(m),i.appendChild(p);let T=C("div");T.style.display="none";let M=C("span");return M.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:M,closeButton:m,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},Fl={default:eu,minimal:tu},ru=r=>{var e;return(e=Fl[r])!=null?e:Fl.default},os=(r,e,t)=>{var s,i,d;if(e!=null&&e.render){let l=e.render({config:r,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=C("div");u.style.display="none";let f=C("span"),p=C("span"),m=C("button");m.style.display="none";let y=C("div");return y.style.display="none",{header:l,iconHolder:u,headerTitle:f,headerSubtitle:p,closeButton:m,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=e==null?void 0:e.layout)!=null?s:"default",a=ru(o)({config:r,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(a.iconHolder.style.display="none"),e.showTitle===!1&&(a.headerTitle.style.display="none"),e.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(a.closeButton.style.display="none"),e.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ul=r=>{var s,i;let e=C("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(s=r==null?void 0:r.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",e.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",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,o=20;e.style.maxHeight=`${t*o}px`,e.style.overflowY="auto";let n=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*o},a=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,n());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:a}},ql=r=>{var w,v,E,H,I,P,z,j,ie,ve,Xe,Ae;let e=(w=r==null?void 0:r.sendButton)!=null?w:{},t=(v=e.useIcon)!=null?v:!1,o=(E=e.iconText)!=null?E:"\u2191",n=e.iconName,a=(H=e.stopIconName)!=null?H:"square",s=(I=e.tooltipText)!=null?I:"Send message",i=(P=e.stopTooltipText)!=null?P:"Stop generating",d=(j=(z=r==null?void 0:r.copy)==null?void 0:z.sendButtonLabel)!=null?j:"Send",l=(ve=(ie=r==null?void 0:r.copy)==null?void 0:ie.stopButtonLabel)!=null?ve:"Stop",u=(Xe=e.showTooltip)!=null?Xe:!1,f=(Ae=e.size)!=null?Ae:"40px",p=e.backgroundColor,m=e.textColor,y=C("div","persona-send-button-wrapper"),h=C("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");h.type="submit",h.setAttribute("data-persona-composer-submit","");let T=null,M=null;if(t){h.style.width=f,h.style.height=f,h.style.minWidth=f,h.style.minHeight=f,h.style.fontSize="18px",h.style.lineHeight="1",h.innerHTML="",m?h.style.color=m:h.style.color="var(--persona-button-primary-fg, #ffffff)";let We=parseFloat(f)||24,Me=(m==null?void 0:m.trim())||"currentColor";n?(T=Ee(n,We,Me,2),T?h.appendChild(T):h.textContent=o):h.textContent=o,M=Ee(a,We,Me,2),p?h.style.backgroundColor=p:h.classList.add("persona-bg-persona-primary")}else h.textContent=d,m?h.style.color=m:h.classList.add("persona-text-white");e.borderWidth&&(h.style.borderWidth=e.borderWidth,h.style.borderStyle="solid"),e.borderColor&&(h.style.borderColor=e.borderColor),e.paddingX?(h.style.paddingLeft=e.paddingX,h.style.paddingRight=e.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),e.paddingY?(h.style.paddingTop=e.paddingY,h.style.paddingBottom=e.paddingY):(h.style.paddingTop="",h.style.paddingBottom="");let k=null;u&&s&&(k=C("div","persona-send-button-tooltip"),k.textContent=s,y.appendChild(k)),h.setAttribute("aria-label",s),y.appendChild(h);let L="send";return{button:h,wrapper:y,setMode:We=>{if(We===L)return;L=We;let Me=We==="stop"?i:s;if(h.setAttribute("aria-label",Me),k&&(k.textContent=Me),t){if(T&&M){let Ue=We==="stop"?M:T;h.replaceChildren(Ue)}}else h.textContent=We==="stop"?l:d}}},zl=r=>{var k,L,x,w,v,E,H,I,P,z,j,ie;let e=(k=r==null?void 0:r.voiceRecognition)!=null?k:{};if(!(e.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((L=e.provider)==null?void 0:L.type)==="runtype";if(!(o||n))return null;let s=(w=(x=r==null?void 0:r.sendButton)==null?void 0:x.size)!=null?w:"40px",i=C("div","persona-send-button-wrapper"),d=C("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=(v=e.iconName)!=null?v:"mic",u=(E=e.iconSize)!=null?E:s,f=parseFloat(u)||24,p=(I=e.backgroundColor)!=null?I:(H=r==null?void 0:r.sendButton)==null?void 0:H.backgroundColor,m=(z=e.iconColor)!=null?z:(P=r==null?void 0:r.sendButton)==null?void 0:P.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let h=Ee(l,f,m||"currentColor",1.5);h?d.appendChild(h):d.textContent="\u{1F3A4}",p&&(d.style.backgroundColor=p),e.borderWidth&&(d.style.borderWidth=e.borderWidth,d.style.borderStyle="solid"),e.borderColor&&(d.style.borderColor=e.borderColor),e.paddingX&&(d.style.paddingLeft=e.paddingX,d.style.paddingRight=e.paddingX),e.paddingY&&(d.style.paddingTop=e.paddingY,d.style.paddingBottom=e.paddingY),i.appendChild(d);let T=(j=e.tooltipText)!=null?j:"Start voice recognition";if(((ie=e.showTooltip)!=null?ie:!1)&&T){let ve=C("div","persona-send-button-tooltip");ve.textContent=T,i.appendChild(ve)}return{button:d,wrapper:i}},$l=r=>{var y,h,T,M,k,L,x,w;let e=(y=r==null?void 0:r.attachments)!=null?y:{};if(e.enabled!==!0)return null;let t=(T=(h=r==null?void 0:r.sendButton)==null?void 0:h.size)!=null?T:"40px",o=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let n=C("input");n.type="file",n.accept=((M=e.allowedTypes)!=null?M:Tn).join(","),n.multiple=((k=e.maxFiles)!=null?k:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=C("div","persona-send-button-wrapper"),s=C("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");s.type="button",s.setAttribute("aria-label",(L=e.buttonTooltipText)!=null?L:"Attach file");let i=(x=e.buttonIconName)!=null?x:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);s.style.width=d,s.style.height=d,s.style.minWidth=d,s.style.minHeight=d,s.style.fontSize="18px",s.style.lineHeight="1",s.style.backgroundColor="transparent",s.style.color="var(--persona-primary, #111827)",s.style.border="none",s.style.borderRadius="6px",s.style.transition="background-color 0.15s ease",s.addEventListener("mouseenter",()=>{s.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),s.addEventListener("mouseleave",()=>{s.style.backgroundColor="transparent"});let f=Ee(i,u,"currentColor",1.5);f?s.appendChild(f):s.textContent="\u{1F4CE}",s.addEventListener("click",v=>{v.preventDefault(),n.click()}),a.appendChild(s);let p=(w=e.buttonTooltipText)!=null?w:"Attach file",m=C("div","persona-send-button-tooltip");return m.textContent=p,a.appendChild(m),{button:s,wrapper:a,input:n,previewsContainer:o}},Vl=r=>{var s,i,d;let e=(s=r==null?void 0:r.statusIndicator)!=null?s:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=C("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=e.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let l=C("a");l.href=e.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=a;return o},jl=()=>C("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ns=r=>{var y,h,T,M,k,L;let{config:e}=r,t=C("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let o=jl(),n=C("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");n.setAttribute("data-persona-composer-form",""),n.style.outline="none";let{textarea:a,attachAutoResize:s}=Ul(e);s();let i=ql(e),d=zl(e),l=$l(e),u=Vl(e);l&&(l.previewsContainer.style.gap="8px",n.append(l.previewsContainer,l.input)),n.append(a);let f=C("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),p=C("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=C("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&p.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(p,m),n.append(f),n.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==(d==null?void 0:d.button)&&x.target!==(d==null?void 0:d.wrapper)&&x.target!==(l==null?void 0:l.button)&&x.target!==(l==null?void 0:l.wrapper)&&a.focus()}),t.append(o,n,u),{footer:t,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(h=d==null?void 0:d.wrapper)!=null?h:null,statusText:u,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(M=l==null?void 0:l.wrapper)!=null?M:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var Bx=()=>{let r=C("button","persona-pill-peek");r.type="button",r.setAttribute("data-persona-pill-peek",""),r.setAttribute("aria-label","Show conversation"),r.setAttribute("tabindex","-1");let e=C("span","persona-pill-peek__icon"),t=Ee("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let o=C("span","persona-pill-peek__text"),n=C("span","persona-pill-peek__caret"),a=Ee("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),r.append(e,o,n),{root:r,textNode:o}},Dx=r=>{var y,h,T,M,k,L;let{config:e}=r,t=C("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let o=jl();o.style.display="none";let n=Vl(e);n.style.display="none";let{textarea:a,attachAutoResize:s}=Ul(e);a.style.maxHeight="100px",s();let i=ql(e),d=zl(e),l=$l(e);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=C("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let f=C("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&f.append(l.wrapper);let p=C("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&p.append(d.wrapper),p.append(i.wrapper),u.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==(d==null?void 0:d.button)&&x.target!==(d==null?void 0:d.wrapper)&&x.target!==(l==null?void 0:l.button)&&x.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&u.append(l.input),u.append(f,a,p),l&&t.append(l.previewsContainer),t.append(u,o,n);let m=u;return{footer:t,suggestions:o,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(h=d==null?void 0:d.wrapper)!=null?h:null,statusText:n,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(M=l==null?void 0:l.wrapper)!=null?M:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:m,leftActions:f,rightActions:p,setSendButtonMode:i.setMode}};var Ox=r=>{var u,f,p,m,y,h,T,M,k,L,x,w,v,E,H,I,P;let e=(f=(u=r==null?void 0:r.launcher)==null?void 0:u.enabled)!=null?f:!0,t=Lr(r);if(Kn(r)){let z=(m=(p=r==null?void 0:r.launcher)==null?void 0:p.composerBar)!=null?m:{},j=C("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(y=z.expandedSize)!=null?y:"anchored",j.style.zIndex=String((T=(h=r==null?void 0:r.launcher)==null?void 0:h.zIndex)!=null?T:so);let ie=C("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ie.style.width="100%",j.appendChild(ie);let ve=C("div","persona-widget-pill-root");return ve.setAttribute("data-persona-composer-bar",""),ve.dataset.state="collapsed",ve.dataset.expandedSize=(M=z.expandedSize)!=null?M:"anchored",ve.style.zIndex=String((L=(k=r==null?void 0:r.launcher)==null?void 0:k.zIndex)!=null?L:so),{wrapper:j,panel:ie,pillRoot:ve}}if(t){let z=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return z.appendChild(j),{wrapper:z,panel:j}}if(!e){let z=C("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=C("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ie=(w=(x=r==null?void 0:r.launcher)==null?void 0:x.width)!=null?w:"100%";return z.style.width=ie,j.style.width="100%",z.appendChild(j),{wrapper:z,panel:j}}let n=(v=r==null?void 0:r.launcher)!=null?v:{},a=n.position&&tn[n.position]?tn[n.position]:tn["bottom-right"],s=C("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(E=r==null?void 0:r.launcher)==null?void 0:E.zIndex)!=null?H:so);let i=C("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(P=(I=r==null?void 0:r.launcher)==null?void 0:I.width)!=null?P:r==null?void 0:r.launcherWidth,l=d!=null?d:Wo;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},jv=(r,e)=>{var x,w,v,E,H,I,P,z,j;let t=C("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Ol(r,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(w=(x=r==null?void 0:r.launcher)==null?void 0:x.clearChat)==null?void 0:w.enabled)!=null?v:!0,s=null,i=null;if(a){let ie=_l(r,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=ie.button,i=ie.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=C("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=C("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 u=C("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let f=C("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");f.textContent=(H=(E=r==null?void 0:r.copy)==null?void 0:E.welcomeTitle)!=null?H:"Hello \u{1F44B}";let p=C("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(P=(I=r==null?void 0:r.copy)==null?void 0:I.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",u.append(f,p);let m=C("div","persona-flex persona-flex-col persona-gap-3"),y=(z=r==null?void 0:r.layout)==null?void 0:z.contentMaxWidth;y&&(m.style.maxWidth=y,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((j=r==null?void 0:r.copy)==null?void 0:j.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let T=C("div","persona-composer-overlay persona-pointer-events-none");T.setAttribute("data-persona-composer-overlay",""),T.style.position="absolute",T.style.left="0",T.style.right="0",T.style.bottom="0",T.style.zIndex="20";let M=Dx({config:r}),{root:k,textNode:L}=Bx();return t.append(d,n,l,T),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:m,composerOverlay:T,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:f,introSubtitle:p,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:C("span"),headerTitle:C("span"),headerSubtitle:C("span"),header:d,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,peekBanner:k,peekTextNode:L}},_x=(r,e=!0)=>{var T,M,k,L,x,w,v,E,H;if(Kn(r))return jv(r,e);let t=C("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let o=(T=r==null?void 0:r.layout)==null?void 0:T.header,n=((M=r==null?void 0:r.layout)==null?void 0:M.showHeader)!==!1,a=o?os(r,o,{showClose:e}):kn({config:r,showClose:e}),s=C("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");s.id="persona-scroll-container",s.setAttribute("data-persona-theme-zone","messages"),s.style.setProperty("scrollbar-gutter","stable");let i=C("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Lr(r)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=C("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(L=(k=r==null?void 0:r.copy)==null?void 0:k.welcomeTitle)!=null?L:"Hello \u{1F44B}";let l=C("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(w=(x=r==null?void 0:r.copy)==null?void 0:x.welcomeSubtitle)!=null?w:"Ask anything about your account or products.",i.append(d,l);let u=C("div","persona-flex persona-flex-col persona-gap-3"),f=(v=r==null?void 0:r.layout)==null?void 0:v.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((E=r==null?void 0:r.copy)==null?void 0:E.showWelcomeCard)!==!1||(i.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(i,u);let m=ns({config:r}),y=((H=r==null?void 0:r.layout)==null?void 0:H.showFooter)!==!1;n?Ta(t,a,r):(a.header.style.display="none",Ta(t,a,r)),t.append(s);let h=C("div","persona-composer-overlay persona-pointer-events-none");return h.setAttribute("data-persona-composer-overlay",""),h.style.position="absolute",h.style.left="0",h.style.right="0",h.style.bottom="0",h.style.zIndex="20",y||(m.footer.style.display="none"),t.append(m.footer),t.append(h),{container:t,body:s,messagesWrapper:u,composerOverlay:h,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:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.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 Gv=r=>{switch(r){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}},Kv=(r,e)=>{if(!r)return null;let t=Gv(r);if(t===null)return null;let o=e==null?void 0:e[r],n=o!==void 0?o:t;return n||null},Xv=(r,e)=>{let t=C("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",r),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},Qv=r=>{let e=r.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(r)||e.startsWith("data:image/")||!r.includes(":"))},ou=r=>{let e=r.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(r)||e.startsWith("data:")||!r.includes(":"))},nu=320,Fx=320,Yv=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Jv=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Zv=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),eC=r=>!r.contentParts||r.contentParts.length===0?[]:r.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),tC=(r,e,t)=>{if(r.length===0)return null;try{let o=C("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),t==null||t())};return r.forEach((i,d)=>{var f;let l=C("img");l.alt=((f=i.alt)==null?void 0:f.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=`${nu}px`,l.style.maxHeight=`${Fx}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;n+=1,l.addEventListener("error",()=>{u||(u=!0,n=Math.max(0,n-1),l.remove(),n===0&&s())}),l.addEventListener("load",()=>{u=!0}),Qv(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,n=Math.max(0,n-1),l.remove())}),n===0?(s(),null):o}catch{return t==null||t(),null}},rC=r=>{if(r.length===0)return null;try{let e=C("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return r.forEach(o=>{if(!ou(o.audio))return;let n=C("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${nu}px`,e.appendChild(n),t+=1}),t===0?(e.remove(),null):e}catch{return null}},oC=r=>{if(r.length===0)return null;try{let e=C("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return r.forEach(o=>{if(!ou(o.video))return;let n=C("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${nu}px`,n.style.maxHeight=`${Fx}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(n),t+=1}),t===0?(e.remove(),null):e}catch{return null}},nC=r=>{if(r.length===0)return null;try{let e=C("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return r.forEach(o=>{if(!ou(o.data))return;let n=C("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",e.appendChild(n),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Ma=()=>{let r=document.createElement("div");r.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",r.appendChild(e),r.appendChild(t),r.appendChild(o),r.appendChild(n),r},au=(r,e,t)=>{let o={config:t!=null?t:{},streaming:!0,location:r,defaultRenderer:Ma};if(e){let n=e(o);if(n!==null)return n}return Ma()},aC=(r,e)=>{let t=C("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"),o=e==="user"?r.userAvatar:r.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=C("img");n.src=o,n.alt=e==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(n)}else t.textContent=o,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Nx=(r,e)=>{let t=C("div","persona-text-xs persona-text-persona-muted"),o=new Date(r.createdAt);return e.format?t.textContent=e.format(o):t.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},sC=(r,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),r==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},su=(r,e,t)=>{var m,y,h,T,M,k;let o=(m=e.showCopy)!=null?m:!0,n=(y=e.showUpvote)!=null?y:!0,a=(h=e.showDownvote)!=null?h:!0;if(!o&&!n&&!a){let L=C("div");return L.style.display="none",L.id=`actions-${r.id}`,L.setAttribute("data-actions-for",r.id),L}let s=(T=e.visibility)!=null?T:"hover",i=(M=e.align)!=null?M:"right",d=(k=e.layout)!=null?k:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],f=C("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${s==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${r.id}`,f.setAttribute("data-actions-for",r.id);let p=(L,x,w)=>{let v=Br({icon:L,label:x,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",w),v};return o&&f.appendChild(p("copy","Copy message","copy")),n&&f.appendChild(p("thumbs-up","Upvote","upvote")),a&&f.appendChild(p("thumbs-down","Downvote","downvote")),f},as=(r,e,t,o,n,a)=>{var Z,ne,me,be,ye,Y,ge,Oe,ce,ae,Q,Tt,Ye,De,le,nt,Re;let s=t!=null?t:{},i=(Z=s.layout)!=null?Z:"bubble",d=s.avatar,l=s.timestamp,u=(ne=d==null?void 0:d.show)!=null?ne:!1,f=(me=l==null?void 0:l.show)!=null?me:!1,p=(be=d==null?void 0:d.position)!=null?be:"left",m=(ye=l==null?void 0:l.position)!=null?ye:"below",y=sC(r.role,i),h=C("div",y.join(" "));h.id=`bubble-${r.id}`,h.setAttribute("data-message-id",r.id),h.setAttribute("data-persona-theme-zone",r.role==="user"?"user-message":"assistant-message"),r.role==="user"?(h.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",h.style.color="var(--persona-message-user-text, white)"):r.role==="assistant"&&(h.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",h.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Yv(r),M=(ge=(Y=r.content)==null?void 0:Y.trim())!=null?ge:"",L=T.length>0&&M===ll,x=Wl((ce=(Oe=a==null?void 0:a.widgetConfig)==null?void 0:Oe.features)==null?void 0:ce.streamAnimation),w=(Tt=(Q=(ae=a==null?void 0:a.widgetConfig)==null?void 0:ae.features)==null?void 0:Q.streamAnimation)==null?void 0:Tt.plugins,v=r.role==="assistant"&&x.type!=="none"?ni(x.type,w):null,E=r.role==="assistant"&&((Ye=v==null?void 0:v.isAnimating)==null?void 0:Ye.call(v,r))===!0,H=r.role==="assistant"&&v!==null&&(!!r.streaming||E);H&&(v!=null&&v.bubbleClass)&&h.classList.add(v.bubbleClass);let I=document.createElement("div");I.classList.add("persona-message-content"),H&&v&&(v.containerClass&&I.classList.add(v.containerClass),I.style.setProperty("--persona-stream-step",`${x.speed}ms`),I.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let P=H?Bl((De=r.content)!=null?De:"",x.buffer,v,r,!!r.streaming):(le=r.content)!=null?le:"",z=e({text:P,message:r,streaming:!!r.streaming,raw:r.rawContent}),j=z;H&&(v==null?void 0:v.wrap)==="char"?j=ai(z,"char",r.id,{skipTags:v.skipTags}):H&&(v==null?void 0:v.wrap)==="word"&&(j=ai(z,"word",r.id,{skipTags:v.skipTags}));let ie=null;if(L?(ie=document.createElement("div"),ie.innerHTML=j,ie.style.display="none",I.appendChild(ie)):I.innerHTML=j,H&&(v!=null&&v.useCaret)&&!L&&M){let K=Dl(),he=I.querySelectorAll(".persona-stream-char, .persona-stream-word"),it=he[he.length-1];if(it!=null&&it.parentNode)it.parentNode.insertBefore(K,it.nextSibling);else{let Pt=I.lastElementChild;Pt?Pt.appendChild(K):I.appendChild(K)}}if(f&&m==="inline"&&r.createdAt){let K=Nx(r,l);K.classList.add("persona-ml-2","persona-inline"),I.appendChild(K)}if(T.length>0){let K=tC(T,!L&&!!M,()=>{L&&ie&&(ie.style.display="")});K?h.appendChild(K):L&&ie&&(ie.style.display="")}let ve=Jv(r);if(ve.length>0){let K=rC(ve);K&&h.appendChild(K)}let Xe=Zv(r);if(Xe.length>0){let K=oC(Xe);K&&h.appendChild(K)}let Ae=eC(r);if(Ae.length>0){let K=nC(Ae);K&&h.appendChild(K)}if(h.appendChild(I),f&&m==="below"&&r.createdAt){let K=Nx(r,l);K.classList.add("persona-mt-1"),h.appendChild(K)}let We=r.role==="assistant"?Kv(r.stopReason,(Re=(nt=a==null?void 0:a.widgetConfig)==null?void 0:nt.copy)==null?void 0:Re.stopReasonNotice):null;if(r.streaming&&r.role==="assistant"){let K=!!(P&&P.trim()),he=x.placeholder==="skeleton",it=he&&x.buffer==="line"&&K;if(K)it&&h.appendChild(si());else if(he)h.appendChild(si());else{let Pt=au("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Pt&&h.appendChild(Pt)}}if(We&&r.stopReason&&!r.streaming&&(M||(I.style.display="none"),h.appendChild(Xv(r.stopReason,We))),r.role==="assistant"&&!r.streaming&&r.content&&r.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let K=su(r,o,n);h.appendChild(K)}if(!u||r.role==="system")return h;let Ue=C("div",`persona-flex persona-gap-2 ${r.role==="user"?"persona-flex-row-reverse":""}`),Be=aC(d,r.role);return p==="right"||p==="left"&&r.role==="user"?Ue.append(h,Be):Ue.append(Be,h),h.classList.remove("persona-max-w-[85%]"),h.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ue},Ux=(r,e,t,o,n,a)=>{let s=t!=null?t:{};return r.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:r,config:{},streaming:!!r.streaming}):r.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:r,config:{},streaming:!!r.streaming}):as(r,e,t,o,n,a)};var ss=new Set,iC=(r,e)=>e==null?!1:typeof e=="string"?(r.textContent=e,!0):(r.appendChild(e),!0),lC=(r,e)=>{var o,n;let t=(n=(o=r.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return t?t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
|
|
72
|
-
`):""},
|
|
73
|
-
`);let n=
|
|
74
|
-
`):""},pC=(r,e)=>{var u,f,p,m,y;let t=r.toolCall,o=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,n=(f=o==null?void 0:o.collapsedMode)!=null?f:"tool-call",a=cC(r,(p=o==null?void 0:o.previewMaxLines)!=null?p:3),s=t?Jh(t):"";if(!t)return{summary:s,previewText:a,isActive:!1};let i=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},l=s;return n==="tool-name"?l=((y=t.name)==null?void 0:y.trim())||s:n==="tool-preview"&&a&&(l=a),i&&d.activeTextTemplate?l=Vd(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Vd(t,d.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},zx=(r,e,t)=>{var u;let o=is.has(r),n=(u=t==null?void 0:t.toolCall)!=null?u:{},a=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let d=a.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let f=n.toggleTextColor||n.headerTextColor||"currentColor",p=Ee(o?"chevron-up":"chevron-down",16,f,2);p?l.appendChild(p):l.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},lu=(r,e)=>{var j,ie,ve,Xe,Ae,We,Me,Ue,Be;let t=r.toolCall,o=(j=e==null?void 0:e.toolCall)!=null?j:{},n=C("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(n.id=`bubble-${r.id}`,n.setAttribute("data-message-id",r.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return n;let a=(ve=(ie=e==null?void 0:e.features)==null?void 0:ie.toolCallDisplay)!=null?ve:{},s=a.expandable!==!1,i=s&&is.has(r.id),{summary:d,previewText:l,isActive:u}=pC(r,e),f=C("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");f.type="button",s&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let p=C("div","persona-flex persona-flex-col persona-text-left"),m=C("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let y=String((Xe=t.startedAt)!=null?Xe:Date.now()),h=()=>{let Z=C("span","");return Z.setAttribute("data-tool-elapsed",y),Z.textContent=Xs(t),Z},T=(We=o.renderCollapsedSummary)==null?void 0:We.call(o,{message:r,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Ae=a.collapsedMode)!=null?Ae:"tool-call",isActive:u,config:e!=null?e:{},elapsed:Xs(t),createElapsedElement:h});typeof T=="string"&&T.trim()?(m.textContent=T,p.appendChild(m)):T instanceof HTMLElement?p.appendChild(T):(m.textContent=d,p.appendChild(m));let M=(Me=a.loadingAnimation)!=null?Me:"none",k=o.activeTextTemplate,L=o.completeTextTemplate,x=u?k:L,w=T instanceof HTMLElement,v=(Z,ne,me)=>{let be=me;for(let ye of ne){let Y=C("span","persona-tool-char");Y.style.setProperty("--char-index",String(be)),Y.textContent=ye===" "?"\xA0":ye,Z.appendChild(Y),be++}return be},E=(Z,ne)=>{var Y;m.textContent="";let me=((Y=t.name)==null?void 0:Y.trim())||"tool",be=tl(Z,me),ye=0;for(let ge of be){let Oe=ge.styles.length>0?(()=>{let ce=C("span",ge.styles.map(ae=>`persona-tool-text-${ae}`).join(" "));return m.appendChild(ce),ce})():m;if(ge.isDuration&&u)Oe.appendChild(h());else{let ce=ge.isDuration?Xs(t):ge.text;ne?ye=v(Oe,ce,ye):Oe.appendChild(document.createTextNode(ce))}}};if(!w)if(u&&M!=="none"){let Z=(Ue=o.loadingAnimationDuration)!=null?Ue:2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),x&&E(x,!1);else if(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),M==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),x)E(x,!0);else{let ne=m.textContent||d;m.textContent="",v(m,ne,0)}}else x&&E(x,!1);let H=null;if(s){H=C("div","persona-flex persona-items-center");let Z=o.toggleTextColor||o.headerTextColor||"currentColor",ne=Ee(i?"chevron-up":"chevron-down",16,Z,2);ne?H.appendChild(ne):H.textContent=i?"Hide":"Show";let me=C("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");me.append(H),f.append(p,me)}else f.append(p);let I=C("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","tool"),I.style.display="none",I.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&l){let Z=(Be=o.renderCollapsedPreview)==null?void 0:Be.call(o,{message:r,toolCall:t,defaultPreview:l,isActive:u,config:e!=null?e:{}});dC(I,Z)||(I.textContent=l),I.style.display=""}if(!i&&u&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(f,I),n;let P=C("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(P.style.display=i?"":"none",o.contentBackgroundColor&&(P.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(P.style.color=o.contentTextColor),o.contentPaddingX&&(P.style.paddingLeft=o.contentPaddingX,P.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(P.style.paddingTop=o.contentPaddingY,P.style.paddingBottom=o.contentPaddingY),t.name){let Z=C("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Z.style.color=o.contentTextColor:o.headerTextColor&&(Z.style.color=o.headerTextColor),Z.textContent=t.name,P.appendChild(Z)}if(t.args!==void 0){let Z=C("div","persona-space-y-1"),ne=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ne.style.color=o.labelTextColor),ne.textContent="Arguments";let me=C("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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(me.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(me.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(me.style.color=o.codeBlockTextColor),me.textContent=Ya(t.args),Z.append(ne,me),P.appendChild(Z)}if(t.chunks&&t.chunks.length){let Z=C("div","persona-space-y-1"),ne=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ne.style.color=o.labelTextColor),ne.textContent="Activity";let me=C("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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(me.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(me.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(me.style.color=o.codeBlockTextColor),me.textContent=t.chunks.join(""),Z.append(ne,me),P.appendChild(Z)}if(t.status==="complete"&&t.result!==void 0){let Z=C("div","persona-space-y-1"),ne=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ne.style.color=o.labelTextColor),ne.textContent="Result";let me=C("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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(me.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(me.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(me.style.color=o.codeBlockTextColor),me.textContent=Ya(t.result),Z.append(ne,me),P.appendChild(Z)}if(t.status==="complete"&&typeof t.duration=="number"){let Z=C("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Z.style.color=o.contentTextColor),Z.textContent=`Duration: ${t.duration}ms`,P.appendChild(Z)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let Z=o.toggleTextColor||o.headerTextColor||"currentColor",ne=Ee(i?"chevron-up":"chevron-down",16,Z,2);ne?H.appendChild(ne):H.textContent=i?"Hide":"Show"}P.style.display=i?"":"none",I.style.display=i?"none":I.textContent||I.childNodes.length?"":"none"})(),n.append(f,I,P),n};var Gl=new Map,uC=r=>{let t=(r.startsWith(Cn)?r.slice(Cn.length):r).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return r;let o=t.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},$x=r=>(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,Vx=(r,e)=>{var o,n,a;let t=(n=(o=$x(e))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=Gl.get(r))!=null?a:t==="expanded"},jx=(r,e,t)=>{var s,i;let o=$x(t);r.setAttribute("aria-expanded",e?"true":"false");let n=r.querySelector("[data-approval-details-label]");n&&(n.textContent=e?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=r.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let d=Ee(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&a.appendChild(d)}},Gx=(r,e,t)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),n=e.querySelector("[data-approval-details]");if(!o||!n)return;let a=Vx(r,t);jx(o,a,t),n.style.display=a?"":"none"};var Kl=(r,e)=>{var E,H,I,P,z,j,ie,ve,Xe,Ae,We,Me,Ue,Be,Z;let t=r.approval,o=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,n=(t==null?void 0:t.status)==="pending",a=C("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${r.id}`,a.setAttribute("data-message-id",r.id),a.style.backgroundColor=(E=o==null?void 0:o.backgroundColor)!=null?E:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(H=o==null?void 0:o.borderColor)!=null?H:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return a;let s=C("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=C("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",u=Ee(d,20,l,2);u&&i.appendChild(u);let f=C("div","persona-flex-1 persona-min-w-0"),p=C("div","persona-flex persona-items-center persona-gap-2"),m=C("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(P=o==null?void 0:o.title)!=null?P:"Approval Required",p.appendChild(m),!n){let ne=C("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ne.setAttribute("data-approval-status",t.status),t.status==="approved"?(ne.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ne.style.color="var(--persona-palette-colors-success-700, #15803d)",ne.textContent="Approved"):t.status==="denied"?(ne.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ne.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ne.textContent="Denied"):t.status==="timeout"&&(ne.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ne.style.color="var(--persona-palette-colors-warning-700, #b45309)",ne.textContent="Timeout"),p.appendChild(ne)}f.appendChild(p);let h=t.toolType==="webmcp"||t.toolName.startsWith(Cn)?Hd(t.toolName):void 0,T=(z=o==null?void 0:o.formatDescription)==null?void 0:z.call(o,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...h?{displayTitle:h}:{},...t.reason?{reason:t.reason}:{}}),M=!t.toolName,k=T||(M?t.description:`The assistant wants to use \u201C${h!=null?h:uC(t.toolName)}\u201D.`),L=C("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(L.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(L.style.color=o.descriptionColor),L.textContent=k,f.appendChild(L),t.reason){let ne=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ne.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?ne.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ne.style.color=o.descriptionColor);let me=C("span","persona-font-medium");me.textContent=`${(j=o==null?void 0:o.reasonLabel)!=null?j:"Agent's stated reason:"} `,ne.appendChild(me),ne.appendChild(document.createTextNode(t.reason)),f.appendChild(ne)}let x=(ie=o==null?void 0:o.detailsDisplay)!=null?ie:"collapsed",w=!!t.description&&!M,v=w||!!t.parameters;if(x!=="hidden"&&v){let ne=Vx(r.id,e),me=C("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");me.type="button",me.setAttribute("data-expand-header","true"),me.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(me.style.color=o.descriptionColor);let be=C("span");be.setAttribute("data-approval-details-label","true");let ye=C("span","persona-inline-flex persona-items-center");ye.setAttribute("data-approval-details-chevron","true"),me.append(be,ye),jx(me,ne,e),f.appendChild(me);let Y=C("div");if(Y.setAttribute("data-approval-details","true"),Y.style.display=ne?"":"none",w){let ge=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ge.style.color=o.descriptionColor),ge.textContent=t.description,Y.appendChild(ge)}if(t.parameters){let ge=C("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");o!=null&&o.parameterBackgroundColor&&(ge.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ge.style.color=o.parameterTextColor),ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",ge.textContent=Ya(t.parameters),Y.appendChild(ge)}f.appendChild(Y)}if(n){let ne=C("div","persona-flex persona-gap-2 persona-mt-2");ne.setAttribute("data-approval-buttons","true");let me=C("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");me.type="button",me.style.backgroundColor=(ve=o==null?void 0:o.approveButtonColor)!=null?ve:"var(--persona-approval-approve-bg, #22c55e)",me.style.color=(Xe=o==null?void 0:o.approveButtonTextColor)!=null?Xe:"#ffffff",me.setAttribute("data-approval-action","approve");let be=Ee("shield-check",14,(Ae=o==null?void 0:o.approveButtonTextColor)!=null?Ae:"#ffffff",2);be&&(be.style.marginRight="4px",me.appendChild(be));let ye=document.createTextNode((We=o==null?void 0:o.approveLabel)!=null?We:"Approve");me.appendChild(ye);let Y=C("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");Y.type="button",Y.style.backgroundColor=(Me=o==null?void 0:o.denyButtonColor)!=null?Me:"transparent",Y.style.color=(Ue=o==null?void 0:o.denyButtonTextColor)!=null?Ue:"var(--persona-feedback-error, #dc2626)",Y.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Y.setAttribute("data-approval-action","deny");let ge=Ee("shield-x",14,(Be=o==null?void 0:o.denyButtonTextColor)!=null?Be:"var(--persona-feedback-error, #dc2626)",2);ge&&(ge.style.marginRight="4px",Y.appendChild(ge));let Oe=document.createTextNode((Z=o==null?void 0:o.denyLabel)!=null?Z:"Deny");Y.appendChild(Oe),ne.append(me,Y),f.appendChild(ne)}return s.append(i,f),a.appendChild(s),a};var Kx=r=>{let e=[],t=null;return{buttons:e,render:(n,a,s,i,d,l)=>{r.innerHTML="",e.length=0;let u=(l==null?void 0:l.agentPushed)===!0;if(u||(t=null),!n||!n.length||!u&&(i!=null?i:a?a.getMessages():[]).some(T=>T.role==="user"))return;let f=document.createDocumentFragment(),p=a?a.isStreaming():!1,m=y=>{switch(y){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'}};if(n.forEach(y=>{let h=C("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");h.type="button",h.textContent=y,h.disabled=p,d!=null&&d.fontFamily&&(h.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(h.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(h.style.paddingLeft=d.paddingX,h.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(h.style.paddingTop=d.paddingY,h.style.paddingBottom=d.paddingY),h.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",u&&r.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),a.sendMessage(y))}),f.appendChild(h),e.push(h)}),r.appendChild(f),u){let y=JSON.stringify(n);y!==t&&(t=y,r.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var pi=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of t)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ui=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{t(o.error)}}catch(o){t(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of e)o.put(n)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(o){t(o)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(o){t(o)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{e()},a.onerror=()=>{t(a.error)}}catch(o){t(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{t(o.error)}}catch(o){t(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of e)o.put(n)}catch{}}};var fC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),mC=new Set(["step_start","execution_start"]),gC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),hC=new Set(["step_complete","agent_turn_complete"]),xC=new Set(["flow_complete","agent_complete"]),Xx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Yx=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Do=r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,ka=(r,e)=>{let t=r[e];return Yx(t)?t:void 0};function du(r){return r>0?Math.max(1,Math.ceil(r/4)):0}function Xl(r,e){if(!(r<=0||e===void 0||e<250))return r/(e/1e3)}function yC(r,e){return typeof e.type=="string"?e.type:r}function bC(r){return typeof r.text=="string"?r.text:typeof r.delta=="string"?r.delta:typeof r.content=="string"?r.content:typeof r.chunk=="string"?r.chunk:""}function vC(r,e){return r==="step_delta"||r==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":r!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Qx(r){var o,n,a,s,i;let e=ka(r,"result"),t=[ka(r,"tokens"),ka(r,"totalTokens"),e?ka(e,"tokens"):void 0,ka(r,"usage"),e?ka(e,"usage"):void 0];for(let d of t){if(!d)continue;let l=(n=(o=Do(d.output))!=null?o:Do(d.outputTokens))!=null?n:Do(d.completionTokens);if(l!==void 0)return l}return(i=(a=Do(r.outputTokens))!=null?a:Do(r.completionTokens))!=null?i:e?(s=Do(e.outputTokens))!=null?s:Do(e.completionTokens):void 0}function CC(r){var t,o,n,a,s;let e=ka(r,"result");return(s=(n=(o=(t=Do(r.executionTime))!=null?t:Do(r.executionTimeMs))!=null?o:Do(r.execution_time))!=null?n:Do(r.duration))!=null?s:e?(a=Do(e.executionTime))!=null?a:Do(e.executionTimeMs):void 0}function wC(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var fi=class{constructor(e=wC){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:Xl(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var a;if(!Yx(t)){Xx.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=yC(e,t),n=this.now();if(fC.has(o)){this.startRun(n);return}if(mC.has(o)){this.run||this.startRun(n);return}if(gC.has(o)){if(!vC(o,t))return;let s=bC(t);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let d=i.exactOutputTokens+du(i.visibleCharCount),l=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Xl(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(hC.has(o)){if(!this.run)return;let s=this.run,i=Qx(t);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let d=s.exactOutputTokens>0,l=s.exactOutputTokens+du(s.visibleCharCount),u=this.resolveDuration(s,t,n);this.metric={status:"running",tokensPerSecond:Xl(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(xC.has(o)){if(!this.run)return;let s=this.run,i=Qx(t),d=i!=null?i:s.exactOutputTokens+du(s.visibleCharCount),l=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,t,n);this.metric={status:"complete",tokensPerSecond:Xl(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(Xx.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,o){let n=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=CC(t);return a!=null?a:o-e.startedAt}};function ls(r,e){e&&e.split(/\s+/).forEach(t=>t&&r.classList.add(t))}var AC={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)"}},SC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},TC=["flowName","stepName","reasoningText","text","name","tool","toolName"],MC=100;function kC(r,e){let t={...AC,...e};if(t[r])return t[r];for(let o of Object.keys(t))if(o.endsWith("_")&&r.startsWith(o))return t[o];return SC}function EC(r,e){return`+${((r-e)/1e3).toFixed(3)}s`}function LC(r){let e=new Date(r),t=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),n=String(e.getSeconds()).padStart(2,"0"),a=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${o}:${n}.${a}`}function PC(r,e){try{let t=JSON.parse(r);if(typeof t!="object"||t===null)return null;for(let o of e){let n=o.split("."),a=t;for(let s of n)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function RC(r){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(r):new Promise(t=>{let o=document.createElement("textarea");o.value=r,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),t()})}function IC(r){let e;try{e=JSON.parse(r.payload)}catch{e=r.payload}return JSON.stringify({type:r.type,timestamp:new Date(r.timestamp).toISOString(),payload:e},null,2)}function HC(r){return r.tokensPerSecond===void 0||!Number.isFinite(r.tokensPerSecond)?"-- tok/s":`${r.tokensPerSecond.toFixed(1)} tok/s`}function WC(r){let e=[];return r.outputTokens!==void 0&&e.push(`${r.outputTokens.toLocaleString()} tok`),r.durationMs!==void 0&&e.push(`${(r.durationMs/1e3).toFixed(2)}s`),r.source&&e.push(r.source),e.join(" \xB7 ")}function BC(r,e,t){let o,n;try{n=JSON.parse(r.payload),o=JSON.stringify(n,null,2)}catch{n=r.payload,o=r.payload}let a=e.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&t){let i=a.renderEventStreamPayload({event:r,config:t,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=C("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=C("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function cu(r,e,t,o,n,a,s,i){var p;let d=n.has(r.id),l=C("div","persona-border-b persona-border-persona-divider persona-text-xs");ls(l,(p=o.classNames)==null?void 0:p.eventRow);let u=s.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:r,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>a(r.id)});if(m)return l.appendChild(m),l}return l.appendChild(f()),l;function f(){var j,ie;let m=C("div",""),y=C("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");y.setAttribute("data-event-id",r.id);let h=C("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=Ee(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&h.appendChild(T);let M=C("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(j=o.timestampFormat)!=null?j:"relative";M.textContent=k==="relative"?EC(r.timestamp,t):LC(r.timestamp);let L=null;o.showSequenceNumbers!==!1&&(L=C("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(e+1));let x=kC(r.type,o.badgeColors),w=C("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=x.bg,w.style.color=x.text,w.style.borderColor=x.text+"50",w.textContent=r.type;let v=(ie=o.descriptionFields)!=null?ie:TC,E=PC(r.payload,v),H=null;E&&(H=C("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=E);let I=C("div","persona-flex-1 persona-min-w-0"),P=C("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"),z=Ee("clipboard","12px","currentColor",1.5);return z&&P.appendChild(z),P.addEventListener("click",async ve=>{ve.stopPropagation(),await RC(IC(r)),P.innerHTML="";let Xe=Ee("check","12px","currentColor",1.5);Xe&&P.appendChild(Xe),setTimeout(()=>{P.innerHTML="";let Ae=Ee("clipboard","12px","currentColor",1.5);Ae&&P.appendChild(Ae)},1500)}),y.appendChild(h),y.appendChild(M),L&&y.appendChild(L),y.appendChild(w),H&&y.appendChild(H),y.appendChild(I),y.appendChild(P),m.appendChild(y),d&&m.appendChild(BC(r,s,i)),m}}function Jx(r){var y,h,T,M,k;let{buffer:e,getFullHistory:t,onClose:o,config:n,plugins:a=[],getThroughput:s}=r,i=(y=n==null?void 0:n.features)==null?void 0:y.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(h=i==null?void 0:i.iconName)!=null?h:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",f=(k=(M=n==null?void 0:n.features)==null?void 0:M.eventStream)!=null?k:{},p=a.find(L=>L.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&n){let L=p.renderEventStreamView({config:n,events:e.getAll(),defaultRenderer:()=>m().element,onClose:o});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return m();function m(){let L=f.classNames,x=C("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ls(x,L==null?void 0:L.panel);let w=[],v="",E="",H=null,I=[],P={},z=0,j=Rl(),ie=0,ve=0,Xe=!1,Ae=null,We=!1,Me=0,Ue=new Set,Be=new Map,Z="",ne="",me=null,be,ye,Y,ge,Oe,ce=null,ae=null,Q=null;function Tt(){let Ce=C("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),de=C("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");ls(de,L==null?void 0:L.headerBar);let rt=C("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(rt.textContent="Events",be=C("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"),be.textContent="0",s){ae=C("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ae.style.cursor="help";let Dr=C("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Dr.textContent="Throughput",ce=C("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"),ce.textContent="-- tok/s",Q=C("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"),Q.style.display="none",Q.style.pointerEvents="none";let hr=ae,Sr=Q,Oo=()=>{if(!Sr.textContent)return;let Tr=hr.getBoundingClientRect(),io=Ce.getBoundingClientRect();Sr.style.left=`${Tr.left-io.left}px`,Sr.style.top=`${Tr.bottom-io.top+4}px`,Sr.style.display="block"},je=()=>{Sr.style.display="none"};ae.addEventListener("mouseenter",Oo),ae.addEventListener("mouseleave",je),ae.appendChild(Dr),ae.appendChild(ce)}let Ft=C("div","persona-flex-1");ye=C("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 zt=C("option","");zt.value="",zt.textContent="All events",ye.appendChild(zt),Y=C("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"),Y.type="button",Y.title="Copy All";let vr=Ee("clipboard-copy","12px","currentColor",1.5);vr&&Y.appendChild(vr);let xt=C("span","persona-text-xs");xt.textContent="Copy All",Y.appendChild(xt),de.appendChild(rt),de.appendChild(be),ae&&de.appendChild(ae),de.appendChild(Ft),de.appendChild(ye),de.appendChild(Y);let It=C("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ls(It,L==null?void 0:L.searchBar);let tt=Ee("search","14px","var(--persona-muted, #9ca3af)",1.5),jt=C("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");tt&&jt.appendChild(tt),ge=C("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"),ls(ge,L==null?void 0:L.searchInput),ge.type="text",ge.placeholder="Search event payloads...",Oe=C("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"),Oe.type="button",Oe.style.display="none";let cr=Ee("x","12px","currentColor",2);return cr&&Oe.appendChild(cr),It.appendChild(jt),It.appendChild(ge),It.appendChild(Oe),Ce.appendChild(de),Ce.appendChild(It),Q&&Ce.appendChild(Q),Ce}let Ye,De=a.find(Ce=>Ce.renderEventStreamToolbar);if(De!=null&&De.renderEventStreamToolbar&&n){let Ce=De.renderEventStreamToolbar({config:n,defaultRenderer:()=>Tt(),eventCount:e.getSize(),filteredCount:0,onFilterChange:de=>{v=de,dr(),O()},onSearchChange:de=>{E=de,dr(),O()}});Ye=Ce!=null?Ce:Tt()}else Ye=Tt();let le=C("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");le.style.display="none";function nt(){if(!s||!ce||!ae)return;let Ce=s();ce.textContent=HC(Ce);let de=WC(Ce);Q&&(Q.textContent=de,de||(Q.style.display="none")),de?ae.setAttribute("aria-label",de):ae.removeAttribute("aria-label")}let Re=C("div","persona-flex-1 persona-min-h-0 persona-relative"),K=C("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");K.style.height="100%";let he=C("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");ls(he,L==null?void 0:L.scrollIndicator),he.style.display="none",he.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let it=Ee(l,"14px","currentColor",2);it&&he.appendChild(it);let Pt=C("span","");Pt.textContent=u,he.appendChild(Pt);let te=C("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",Re.appendChild(K),Re.appendChild(te),Re.appendChild(he),x.setAttribute("tabindex","0"),x.appendChild(Ye),x.appendChild(le),x.appendChild(Re);function _e(){let Ce=e.getAll(),de={};for(let xt of Ce)de[xt.type]=(de[xt.type]||0)+1;let rt=Object.keys(de).sort(),Ft=rt.length!==I.length||!rt.every((xt,It)=>xt===I[It]),zt=!Ft&&rt.some(xt=>de[xt]!==P[xt]),Pr=Ce.length!==Object.values(P).reduce((xt,It)=>xt+It,0);if(!Ft&&!zt&&!Pr||(I=rt,P=de,!ye))return;let vr=ye.value;if(ye.options[0].textContent="All events",Ft){for(;ye.options.length>1;)ye.remove(1);for(let xt of rt){let It=C("option","");It.value=xt,It.textContent=`${xt} (${de[xt]||0})`,ye.appendChild(It)}vr&&rt.includes(vr)?ye.value=vr:vr&&(ye.value="",v="")}else for(let xt=1;xt<ye.options.length;xt++){let It=ye.options[xt];It.textContent=`${It.value} (${de[It.value]||0})`}}function Ar(){let Ce=e.getAll();if(v&&(Ce=Ce.filter(de=>de.type===v)),E){let de=E.toLowerCase();Ce=Ce.filter(rt=>rt.type.toLowerCase().includes(de)||rt.payload.toLowerCase().includes(de))}return Ce}function Rt(){return v!==""||E!==""}function dr(){z=0,ie=0,j.resume(),he.style.display="none"}function Yr(Ce){Ue.has(Ce)?Ue.delete(Ce):Ue.add(Ce),me=Ce;let de=K.scrollTop,rt=j.isFollowing();We=!0,j.pause(),O(),K.scrollTop=de,rt&&j.resume(),We=!1}function zr(){return Aa(K,50)}function O(){ve=Date.now(),Xe=!1,nt(),_e();let Ce=e.getEvictedCount();Ce>0?(le.textContent=`${Ce.toLocaleString()} older events truncated`,le.style.display=""):le.style.display="none",w=Ar();let de=w.length,rt=e.getSize()>0;be&&(be.textContent=String(e.getSize())),de===0&&rt&&Rt()?(te.textContent=E?`No events matching '${E}'`:"No events matching filter",te.style.display="",K.style.display="none"):(te.style.display="none",K.style.display=""),Y&&(Y.title=Rt()?`Copy Filtered (${de})`:"Copy All"),d&&!j.isFollowing()&&de>z&&(ie+=de-z,Pt.textContent=u?`${u}${ie>0?` (${ie})`:""}`:"",he.style.display=""),z=de;let Ft=e.getAll(),zt=Ft.length>0?Ft[0].timestamp:0,Pr=new Set(w.map(It=>It.id));for(let It of Ue)Pr.has(It)||Ue.delete(It);let vr=v!==Z||E!==ne,xt=Be.size===0&&w.length>0;if(vr||xt||w.length===0){K.innerHTML="",Be.clear();let It=document.createDocumentFragment();for(let tt=0;tt<w.length;tt++){let jt=cu(w[tt],tt,zt,f,Ue,Yr,a,n);Be.set(w[tt].id,jt),It.appendChild(jt)}K.appendChild(It),Z=v,ne=E,me=null}else{if(me!==null){let tt=Be.get(me);if(tt&&tt.parentNode===K){let jt=w.findIndex(cr=>cr.id===me);if(jt>=0){let cr=cu(w[jt],jt,zt,f,Ue,Yr,a,n);K.insertBefore(cr,tt),tt.remove(),Be.set(me,cr)}}me=null}let It=new Set(w.map(tt=>tt.id));for(let[tt,jt]of Be)It.has(tt)||(jt.remove(),Be.delete(tt));for(let tt=0;tt<w.length;tt++){let jt=w[tt];if(!Be.has(jt.id)){let cr=cu(jt,tt,zt,f,Ue,Yr,a,n);Be.set(jt.id,cr),K.appendChild(cr)}}}j.isFollowing()&&(K.scrollTop=K.scrollHeight)}function fe(){if(Date.now()-ve>=MC){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),O();return}Xe||(Xe=!0,Ae=requestAnimationFrame(()=>{Ae=null,O()}))}let Ie=(Ce,de)=>{if(!Y)return;Y.innerHTML="";let rt=Ee(Ce,"12px","currentColor",1.5);rt&&Y.appendChild(rt);let Ft=C("span","persona-text-xs");Ft.textContent="Copy All",Y.appendChild(Ft),setTimeout(()=>{Y.innerHTML="";let zt=Ee("clipboard-copy","12px","currentColor",1.5);zt&&Y.appendChild(zt);let Pr=C("span","persona-text-xs");Pr.textContent="Copy All",Y.appendChild(Pr),Y.disabled=!1},de)},Je=async()=>{if(Y){Y.disabled=!0;try{let Ce;Rt()?Ce=w:t?(Ce=await t(),Ce.length===0&&(Ce=e.getAll())):Ce=e.getAll();let de=Ce.map(rt=>{try{return JSON.parse(rt.payload)}catch{return rt.payload}});await navigator.clipboard.writeText(JSON.stringify(de,null,2)),Ie("check",1500)}catch{Ie("x",1500)}}},qe=()=>{ye&&(v=ye.value,dr(),O())},ze=()=>{!ge||!Oe||(Oe.style.display=ge.value?"":"none",H&&clearTimeout(H),H=setTimeout(()=>{E=ge.value,dr(),O()},150))},lt=()=>{!ge||!Oe||(ge.value="",E="",Oe.style.display="none",H&&clearTimeout(H),dr(),O())},Mt=()=>{if(We)return;let Ce=K.scrollTop,{action:de,nextLastScrollTop:rt}=Il({following:j.isFollowing(),currentScrollTop:Ce,lastScrollTop:Me,nearBottom:zr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Me=rt,de==="resume"?(j.resume(),ie=0,he.style.display="none"):de==="pause"&&(j.pause(),d&&(Pt.textContent=u,he.style.display=""))},Dt=Ce=>{let de=Hl({following:j.isFollowing(),deltaY:Ce.deltaY,nearBottom:zr(),resumeWhenNearBottom:!0});de==="pause"?(j.pause(),d&&(Pt.textContent=u,he.style.display="")):de==="resume"&&(j.resume(),ie=0,he.style.display="none")},or=()=>{d&&(K.scrollTop=K.scrollHeight,j.resume(),ie=0,he.style.display="none")},X=Ce=>{let de=Ce.target;if(!de||de.closest("button"))return;let rt=de.closest("[data-event-id]");if(!rt)return;let Ft=rt.getAttribute("data-event-id");Ft&&Yr(Ft)},wt=Ce=>{if((Ce.metaKey||Ce.ctrlKey)&&Ce.key==="f"){Ce.preventDefault(),ge==null||ge.focus(),ge==null||ge.select();return}Ce.key==="Escape"&&(ge&&document.activeElement===ge?(lt(),ge.blur(),x.focus()):o&&o())};Y&&Y.addEventListener("click",Je),ye&&ye.addEventListener("change",qe),ge&&ge.addEventListener("input",ze),Oe&&Oe.addEventListener("click",lt),K.addEventListener("scroll",Mt),K.addEventListener("wheel",Dt,{passive:!0}),K.addEventListener("click",X),he.addEventListener("click",or),x.addEventListener("keydown",wt);function ct(){H&&clearTimeout(H),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),Xe=!1,Be.clear(),Y&&Y.removeEventListener("click",Je),ye&&ye.removeEventListener("change",qe),ge&&ge.removeEventListener("input",ze),Oe&&Oe.removeEventListener("click",lt),K.removeEventListener("scroll",Mt),K.removeEventListener("wheel",Dt),K.removeEventListener("click",X),he.removeEventListener("click",or),x.removeEventListener("keydown",wt)}return{element:x,update:fe,destroy:ct}}}function Zx(r,e){let t=typeof r.title=="string"&&r.title?r.title:"Untitled artifact",o=typeof r.artifactId=="string"?r.artifactId:"",n=r.status==="streaming"?"streaming":"complete",s=(typeof r.artifactType=="string"?r.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #171717)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(p);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,f.appendChild(m)}else f.textContent=s;if(l.append(u,f),i.append(d,l),n==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${t}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",o),i.append(p)}return i}var ey=(r,e)=>{var o,n,a;let t=(a=(n=(o=e==null?void 0:e.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(t){let s=typeof r.title=="string"&&r.title?r.title:"Untitled artifact",i=typeof r.artifactId=="string"?r.artifactId:"",d=r.status==="streaming"?"streaming":"complete",l=typeof r.artifactType=="string"?r.artifactType:"markdown",u=t({artifact:{artifactId:i,title:s,artifactType:l,status:d},config:e.config,defaultRenderer:()=>Zx(r,e)});if(u)return u}return Zx(r,e)};var pu=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,o])=>{this.register(t,o)})}},En=new pu;En.register("PersonaArtifactCard",ey);function DC(r){var n;let e=C("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=C("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=r.component?`Component: ${r.component}`:"Component";let o=C("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=r.props)!=null?n:{},null,2),e.appendChild(t),e.appendChild(o),e}function ty(r,e){var ye,Y,ge,Oe;let t=(Y=(ye=r.features)==null?void 0:ye.artifacts)==null?void 0:Y.layout,n=((ge=t==null?void 0:t.toolbarPreset)!=null?ge:"default")==="document",a=(Oe=t==null?void 0:t.panePadding)==null?void 0:Oe.trim(),s=r.markdown?ua(r.markdown):null,i=ja(r.sanitize),d=ce=>{let ae=s?s(ce):fa(ce);return i?i(ae):ae},l=typeof document!="undefined"?C("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};l&&l.addEventListener("click",()=>{var ce;u(),(ce=e.onDismiss)==null||ce.call(e)});let f=C("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");f.setAttribute("data-persona-theme-zone","artifact-pane"),n&&f.classList.add("persona-artifact-pane-document");let p=C("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");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&p.classList.add("persona-artifact-toolbar-document");let m=C("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let y=C("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");y.type="button",y.textContent="Close",y.setAttribute("aria-label","Close artifacts panel"),y.addEventListener("click",()=>{var ce;u(),(ce=e.onDismiss)==null||ce.call(e)});let h="rendered",T=C("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=n?Br({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Br({icon:"eye",label:"Rendered view"}),k=n?Br({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Br({icon:"code-2",label:"Source"}),L=C("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),x=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,w=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,v=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(w&&v&&v.length>0),H=null,I,P=null,z=null;if(n&&(x||w)&&!E){if(I=x?ci({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Br({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ce=Ee("chevron-down",14,"currentColor",2);ce&&I.appendChild(ce)}}else n&&E?(H=C("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),I=x?ci({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Br({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P=Br({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"}}),H.append(I,P)):n?I=Br({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):I=Br({icon:"copy",label:"Copy"});let j=n?Br({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Br({icon:"refresh-cw",label:"Refresh"}),ie=n?Br({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Br({icon:"x",label:"Close"}),ve=()=>{var Ye,De,le;let ce=(Ye=Be.find(nt=>nt.id===Z))!=null?Ye:Be[Be.length-1],ae=(De=ce==null?void 0:ce.id)!=null?De:null,Q=(ce==null?void 0:ce.artifactType)==="markdown"&&(le=ce.markdown)!=null?le:"",Tt=ce?JSON.stringify({component:ce.component,props:ce.props},null,2):"";return{markdown:Q,jsonPayload:Tt,id:ae}},Xe=async()=>{var Ye;let{markdown:ce,jsonPayload:ae}=ve(),Q=(Ye=Be.find(De=>De.id===Z))!=null?Ye:Be[Be.length-1],Tt=(Q==null?void 0:Q.artifactType)==="markdown"?ce:Q?ae:"";try{await navigator.clipboard.writeText(Tt)}catch{}};if(I.addEventListener("click",async()=>{let ce=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(ce&&E){let{markdown:ae,jsonPayload:Q,id:Tt}=ve();try{await ce({actionId:"primary",artifactId:Tt,markdown:ae,jsonPayload:Q})}catch{}return}await Xe()}),P&&(v!=null&&v.length)){let ce=()=>{var Q;return(Q=f.closest("[data-persona-root]"))!=null?Q:document.body},ae=()=>{z=Xn({items:v.map(Q=>({id:Q.id,label:Q.label})),onSelect:async Q=>{let{markdown:Tt,jsonPayload:Ye,id:De}=ve(),le=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{le?await le({actionId:Q,artifactId:De,markdown:Tt,jsonPayload:Ye}):Q==="markdown"||Q==="md"?await navigator.clipboard.writeText(Tt):Q==="json"||Q==="source"?await navigator.clipboard.writeText(Ye):await navigator.clipboard.writeText(Tt||Ye)}catch{}},anchor:H!=null?H:P,position:"bottom-right",portal:ce()})};f.isConnected?ae():requestAnimationFrame(ae),P.addEventListener("click",Q=>{Q.stopPropagation(),z==null||z.toggle()})}j.addEventListener("click",async()=>{var ce;try{await((ce=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:ce.call(t))}catch{}me()}),ie.addEventListener("click",()=>{var ce;u(),(ce=e.onDismiss)==null||ce.call(e)});let Ae=()=>{n&&(M.setAttribute("aria-pressed",h==="rendered"?"true":"false"),k.setAttribute("aria-pressed",h==="source"?"true":"false"))};M.addEventListener("click",()=>{h="rendered",Ae(),me()}),k.addEventListener("click",()=>{h="source",Ae(),me()});let We=C("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");n?(p.replaceChildren(),T.append(M,k),H?L.append(H,j,ie):L.append(I,j,ie),p.append(T,We,L),Ae()):(p.appendChild(m),p.appendChild(y)),a&&(p.style.paddingLeft=a,p.style.paddingRight=a);let Me=C("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"),Ue=C("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Me.style.paddingLeft=a,Me.style.paddingRight=a,Ue.style.padding=a),f.appendChild(p),f.appendChild(Me),f.appendChild(Ue);let Be=[],Z=null,ne=!1,me=()=>{var Tt,Ye,De,le;let ce=n&&Be.length<=1;Me.classList.toggle("persona-hidden",ce),Me.replaceChildren();for(let nt of Be){let Re=C("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");Re.type="button",Re.textContent=nt.title||nt.id.slice(0,8),nt.id===Z&&Re.classList.add("persona-bg-persona-container","persona-border-persona-border"),Re.addEventListener("click",()=>e.onSelect(nt.id)),Me.appendChild(Re)}Ue.replaceChildren();let ae=Z&&Be.find(nt=>nt.id===Z)||Be[Be.length-1];if(!ae)return;if(n){let nt=ae.artifactType==="markdown"?"MD":(Tt=ae.component)!=null?Tt:"Component",K=(ae.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";We.textContent=`${K} \xB7 ${nt}`}else m.textContent="Artifacts";if(ae.artifactType==="markdown"){if(n&&h==="source"){let Re=C("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Re.textContent=(Ye=ae.markdown)!=null?Ye:"",Ue.appendChild(Re);return}let nt=C("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");nt.innerHTML=d((De=ae.markdown)!=null?De:""),Ue.appendChild(nt);return}let Q=ae.component?En.get(ae.component):void 0;if(Q){let Re={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:r,updateProps:()=>{}};try{let K=Q((le=ae.props)!=null?le:{},Re);if(K){Ue.appendChild(K);return}}catch{}}Ue.appendChild(DC(ae))},be=()=>{var ae;let ce=Be.length>0;if(f.classList.toggle("persona-hidden",!ce),l){let Q=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,Ye=((ae=Q==null?void 0:Q.classList.contains("persona-artifact-narrow-host"))!=null?ae:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ce&&Ye&&ne?(l.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:l,update(ce){var ae,Q,Tt;Be=ce.artifacts,Z=(Tt=(Q=ce.selectedId)!=null?Q:(ae=ce.artifacts[ce.artifacts.length-1])==null?void 0:ae.id)!=null?Tt:null,Be.length>0&&(ne=!0),me(),be()},setMobileOpen(ce){ne=ce,!ce&&l?(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):be()}}}function Go(r){var e,t;return((t=(e=r==null?void 0:r.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function ry(r,e){var a,s,i,d;if(r.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),r.style.removeProperty("--persona-artifact-pane-border"),r.style.removeProperty("--persona-artifact-pane-border-left"),!Go(e))return;let t=(s=(a=e.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),n=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();o?(r.classList.add("persona-artifact-border-full"),r.style.setProperty("--persona-artifact-pane-border",o)):n&&(r.classList.add("persona-artifact-border-left"),r.style.setProperty("--persona-artifact-pane-border-left",n))}function OC(r){r.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),r.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),r.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ql(r,e){var d,l,u,f,p,m,y,h,T,M;if(!Go(e)){r.style.removeProperty("--persona-artifact-split-gap"),r.style.removeProperty("--persona-artifact-pane-width"),r.style.removeProperty("--persona-artifact-pane-max-width"),r.style.removeProperty("--persona-artifact-pane-min-width"),r.style.removeProperty("--persona-artifact-pane-bg"),r.style.removeProperty("--persona-artifact-pane-padding"),OC(r),ry(r,e);return}let t=(l=(d=e.features)==null?void 0:d.artifacts)==null?void 0:l.layout;r.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),r.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),r.style.setProperty("--persona-artifact-pane-max-width",(p=t==null?void 0:t.paneMaxWidth)!=null?p:"28rem"),t!=null&&t.paneMinWidth?r.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):r.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();o?r.style.setProperty("--persona-artifact-pane-bg",o):r.style.removeProperty("--persona-artifact-pane-bg");let n=(y=t==null?void 0:t.panePadding)==null?void 0:y.trim();n?r.style.setProperty("--persona-artifact-pane-padding",n):r.style.removeProperty("--persona-artifact-pane-padding");let a=(h=t==null?void 0:t.documentToolbarIconColor)==null?void 0:h.trim();a?r.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):r.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(T=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:T.trim();s?r.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):r.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?r.style.setProperty("--persona-artifact-doc-toggle-active-border",i):r.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ry(r,e)}var oy=["panel","seamless"];function Yl(r,e){var i,d,l,u,f,p;for(let m of oy)r.classList.remove(`persona-artifact-appearance-${m}`);if(r.classList.remove("persona-artifact-unified-split"),r.style.removeProperty("--persona-artifact-pane-radius"),r.style.removeProperty("--persona-artifact-pane-shadow"),r.style.removeProperty("--persona-artifact-unified-outer-radius"),!Go(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",n=oy.includes(o)?o:"panel";r.classList.add(`persona-artifact-appearance-${n}`);let a=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();a&&r.style.setProperty("--persona-artifact-pane-radius",a);let s=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(s&&r.style.setProperty("--persona-artifact-pane-shadow",s),(t==null?void 0:t.unifiedSplitChrome)===!0){r.classList.add("persona-artifact-unified-split");let m=((p=t.unifiedSplitOuterRadius)==null?void 0:p.trim())||a;m&&r.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function ny(r,e){var t,o,n;return!e||!Go(r)?!1:((n=(o=(t=r.features)==null?void 0:t.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function _C(r,e){if(!(r!=null&&r.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(r.trim());return t?Math.max(0,Number(t[1])):e}function NC(r){if(!(r!=null&&r.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(r.trim());return e?Math.max(0,Number(e[1])):null}function FC(r,e,t){return t<e?e:Math.min(t,Math.max(e,r))}function UC(r,e,t,o){let n=r-o-2*e-t;return Math.max(0,n)}function ay(r,e){var s;let o=(s=(e.getComputedStyle(r).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function sy(r,e,t,o,n,a){let s=_C(n,200),i=UC(e,t,o,200);i=Math.max(s,i);let d=NC(a);return d!==null&&(i=Math.min(i,d)),FC(r,s,i)}var iy={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"}},uu=(r,e,t,o)=>{let n=r.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var y,h,T;if(a.dataset.enhanced==="true")return;let s=(y=a.dataset.tvForm)!=null?y:"init";a.dataset.enhanced="true";let i=(h=iy[s])!=null?h:iy.init;a.classList.add("persona-form-card","persona-space-y-4");let d=C("div","persona-space-y-1"),l=C("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let M=C("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var v,E;let k=C("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${e.id}-${s}-${M.name}`;let L=C("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=M.label,k.appendChild(L);let x=(v=M.type)!=null?v:"text",w;x==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=x),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=`${e.id}-${s}-${M.name}`,w.name=M.name,w.placeholder=(E=M.placeholder)!=null?E:"",M.required&&(w.required=!0),k.appendChild(w),u.appendChild(k)});let f=C("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),p=C("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=C("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(T=i.submitLabel)!=null?T:"Submit",f.appendChild(p),f.appendChild(m),u.appendChild(f),a.replaceChildren(d,u),u.addEventListener("submit",async M=>{var w,v;M.preventDefault();let k=(w=t.formEndpoint)!=null?w:"/form",L=new FormData(u),x={};L.forEach((E,H)=>{x[H]=E}),x.type=s,m.disabled=!0,p.textContent="Submitting\u2026";try{let E=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let H=await E.json();p.textContent=(v=H.message)!=null?v:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(E){p.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var fu=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var o;let t=this.plugins.get(e);t&&((o=t.onUnregister)==null||o.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var o,n;return((o=t.priority)!=null?o:0)-((n=e.priority)!=null?n:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let o=new Set(e.map(a=>a.id));return[...t.filter(a=>!o.has(a.id)),...e].sort((a,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=a.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},mi=new fu;var ly=()=>{let r=new Map,e=(n,a)=>(r.has(n)||r.set(n,new Set),r.get(n).add(a),()=>t(n,a)),t=(n,a)=>{var s;(s=r.get(n))==null||s.delete(a)};return{on:e,off:t,emit:(n,a)=>{var s;(s=r.get(n))==null||s.forEach(i=>{try{i(a)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var qC=r=>{let e=r.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:r},zC=r=>{let e=r.trim(),t=e.indexOf("{");if(t===-1)return null;let o=0;for(let n=t;n<e.length;n+=1){let a=e[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return e.slice(t,n+1)}return null},gi=({text:r})=>{if(!r||!r.includes("{"))return null;try{let e=qC(r),t=zC(e);if(!t)return null;let o=JSON.parse(t);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},mu=r=>typeof r=="string"?r:r==null?"":String(r),Ea={message:r=>r.type!=="message"?void 0:{handled:!0,displayText:mu(r.payload.text)},messageAndClick:(r,e)=>{var n;if(r.type!=="message_and_click")return;let t=r.payload,o=mu(t.element);if(o&&((n=e.document)!=null&&n.querySelector)){let a=e.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:mu(t.text)}}},dy=r=>Array.isArray(r)?r.map(e=>String(e)):[],hi=r=>{let e=new Set(dy(r.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(dy(r.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(e);r.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||e.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.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=s?r.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;e.add(a.message.id),o();let d={action:i,message:a.message};r.emit("action:detected",d);for(let l of r.handlers)if(l)try{let u=()=>{r.emit("action:resubmit",d)},f=l(i,{message:a.message,metadata:r.getSessionMetadata(),updateMetadata:r.updateSessionMetadata,document:r.documentRef,triggerResubmit:u});if(!f)continue;if(f.handled){let p=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:p,resubmit:f.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var $C=r=>{if(!r)return null;try{return JSON.parse(r)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},VC=r=>r.map(e=>({...e,streaming:!1})),jC=r=>r.map(e=>({...e,status:"complete"})),Jl=(r="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?$C(t.getItem(r)):null},save:t=>{let o=e();if(o)try{let n={...t,messages:t.messages?VC(t.messages):void 0,artifacts:t.artifacts?jC(t.artifacts):void 0};o.setItem(r,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let t=e();if(t)try{t.removeItem(r)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var ds=Bi(ji(),1);function GC(r){if(!r||typeof r!="object"||!("component"in r))return!1;let e=r.component;return typeof e=="string"&&e.length>0}function KC(r,e){if(!GC(r))return null;let t=r.props&&typeof r.props=="object"&&r.props!==null?r.props:{};return{component:r.component,props:t,raw:e}}function Zl(){let r=null,e=0;return{getExtractedDirective:()=>r,processChunk:t=>{let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(t.length<=e)return r;try{let n=(0,ds.parse)(t,ds.STR|ds.OBJ),a=KC(n,t);a&&(r=a)}catch{}return e=t.length,r},reset:()=>{r=null,e=0}}}function cy(r){return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"&&"props"in r&&typeof r.props=="object"}function ed(r,e){let{config:t,message:o,onPropsUpdate:n}=e,a=En.get(r.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${r.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:t,updateProps:i=>{n&&n(i)}};try{return a(r.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${r.component}":`,i),null}}function py(){let r=Zl();return{processChunk:e=>r.processChunk(e),getDirective:()=>r.getExtractedDirective(),reset:()=>{r.reset()}}}function uy(r){if(typeof r.rawContent=="string"&&r.rawContent.length>0)return r.rawContent;if(typeof r.content=="string"){let e=r.content.trim();if(e.startsWith("{")||e.startsWith("["))return r.content}return null}function td(r){let e=uy(r);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function rd(r){let e=uy(r);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let o=t;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var XC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function od(r){let{onSubmit:e,onDismiss:t,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=XC}=r,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let f=null,p=document.createElement("div");p.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,m.appendChild(y);let h=document.createElement("p");h.className="persona-feedback-subtitle",h.textContent=n,m.appendChild(h),p.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];for(let v=1;v<=5;v++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),E.title=l[v-1],E.dataset.rating=String(v),E.innerHTML=`
|
|
26
|
+
`,r.addEventListener("click",t);let o=a=>{var P,y,w,b,A,H,W,k,N,q,Z,me,Ke;let s=(P=a.launcher)!=null?P:{},i=pr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let Ce=(y=s.title)!=null?y:"Chat Assistant";c.textContent=Ce,c.setAttribute("title",Ce)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Ce=(w=s.subtitle)!=null?w:"Here to help you get answers fast";d.textContent=Ce,d.setAttribute("title",Ce)}let u=r.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let g=r.querySelector("[data-role='launcher-icon']");if(g)if(s.agentIconHidden)g.style.display="none";else{let Ce=(b=s.agentIconSize)!=null?b:"40px";if(g.style.height=Ce,g.style.width=Ce,g.innerHTML="",s.agentIconName){let Ie=parseFloat(Ce)||24,Ue=ve(s.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);Ue?(g.appendChild(Ue),g.style.display=""):(g.textContent=(A=s.agentIconText)!=null?A:"\u{1F4AC}",g.style.display="")}else s.iconUrl?g.style.display="none":(g.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}",g.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(W=s.agentIconSize)!=null?W:"40px";p.style.height=Ce,p.style.width=Ce,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(p.src=s.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(k=s.callToActionIconSize)!=null?k:"32px";m.style.height=Ce,m.style.width=Ce,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Ie=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Ue=parseFloat(Ce)||24,Te=Math.max(Ue-Ie,8),We=ve(s.callToActionIconName,Te,"currentColor",2);We?m.appendChild(We):m.textContent=(N=s.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(q=s.callToActionIconText)!=null?q:"\u2197"}let x=s.position&&To[s.position]?To[s.position]:To["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?T:`${C} ${x}`,i||(r.style.zIndex=String((Z=s.zIndex)!=null?Z:Lr));let E="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(Ke=s.collapsedMaxWidth)!=null?Ke:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var kh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Th(e),a=Eh(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:d,replaceHeader:p=>(c.element.replaceWith(p.header),c.element=p.header,c.iconHolder=p.iconHolder,c.headerTitle=p.headerTitle,c.headerSubtitle=p.headerSubtitle,c.closeButton=p.closeButton,c.closeButtonWrapper=p.closeButtonWrapper,c.clearChatButton=p.clearChatButton,c.clearChatButtonWrapper=p.clearChatButtonWrapper,p),replaceComposer:p=>{d.footer.replaceWith(p),d.footer=p}}},bp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>yp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=yp(e,r);return{instance:n,element:n.element}};var Eb=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}},kb=(e,t)=>{if(!e)return null;let r=Eb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Lb=(e,t)=>{let r=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Pb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},vp=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(":"))},Cp=320,Ph=320,Rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Hb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Bb=(e,t,r)=>{if(e.length===0)return null;try{let o=S("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var g;let d=S("img");d.alt=((g=i.alt)==null?void 0:g.trim())||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Cp}px`,d.style.maxHeight=`${Ph}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;n+=1,d.addEventListener("error",()=>{u||(u=!0,n=Math.max(0,n-1),d.remove(),n===0&&s())}),d.addEventListener("load",()=>{u=!0}),Pb(i.image)?(d.src=i.image,o.appendChild(d)):(u=!0,n=Math.max(0,n-1),d.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},Db=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!vp(o.audio))return;let n=S("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${Cp}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Fb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!vp(o.video))return;let n=S("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${Cp}px`,n.style.maxHeight=`${Ph}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Nb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!vp(o.data))return;let n=S("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ua=()=>{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 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="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},wp=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let n=t(o);if(n!==null)return n}return ua()},Ob=(e,t)=>{let r=S("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"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=S("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},Lh=(e,t,r="div")=>{let o=S(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},_b=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.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 r},Sp=(e,t,r)=>{var x,C,T,E,M,P,y;let o=(x=t.showCopy)!=null?x:!0,n=(C=t.showUpvote)!=null?C:!0,a=(T=t.showDownvote)!=null?T:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let w=S("div");return w.style.display="none",w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id),w}let i=(M=t.visibility)!=null?M:"hover",c=(P=t.align)!=null?P:"right",d=(y=t.layout)!=null?y:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(w,b,A)=>{let H=yr({icon:w,label:b,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",A),H};return o&&p.appendChild(m("copy","Copy message","copy")),s&&p.appendChild(m("volume-2","Read aloud","read-aloud")),n&&p.appendChild(m("thumbs-up","Upvote","upvote")),a&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Ga=(e,t,r,o,n,a)=>{var de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze;let s=r!=null?r:{},i=(de=s.layout)!=null?de:"bubble",c=s.avatar,d=s.timestamp,u=(J=c==null?void 0:c.show)!=null?J:!1,g=(le=d==null?void 0:d.show)!=null?le:!1,p=(ge=c==null?void 0:c.position)!=null?ge:"left",m=(ue=d==null?void 0:d.position)!=null?ue:"below",x=_b(e.role,i),C=S("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Rb(e),E=(ce=(G=e.content)==null?void 0:G.trim())!=null?ce:"",P=T.length>0&&E===Bi,y=sl((ne=(Be=a==null?void 0:a.widgetConfig)==null?void 0:Be.features)==null?void 0:ne.streamAnimation),w=(vt=(ie=(ee=a==null?void 0:a.widgetConfig)==null?void 0:ee.features)==null?void 0:ie.streamAnimation)==null?void 0:vt.plugins,b=e.role==="assistant"&&y.type!=="none"?Ds(y.type,w):null,A=e.role==="assistant"&&((Lt=b==null?void 0:b.isAnimating)==null?void 0:Lt.call(b,e))===!0,H=e.role==="assistant"&&b!==null&&(!!e.streaming||A);H&&(b!=null&&b.bubbleClass)&&C.classList.add(b.bubbleClass);let W=document.createElement("div");W.classList.add("persona-message-content"),H&&b&&(b.containerClass&&W.classList.add(b.containerClass),W.style.setProperty("--persona-stream-step",`${y.speed}ms`),W.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let k=H?il((gt=e.content)!=null?gt:"",y.buffer,b,e,!!e.streaming):(_e=e.content)!=null?_e:"",N=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=N;H&&(b==null?void 0:b.wrap)==="char"?q=Fs(N,"char",e.id,{skipTags:b.skipTags}):H&&(b==null?void 0:b.wrap)==="word"&&(q=Fs(N,"word",e.id,{skipTags:b.skipTags}));let Z=null;if(P?(Z=document.createElement("div"),Z.innerHTML=q,Z.style.display="none",W.appendChild(Z)):W.innerHTML=q,H&&(b!=null&&b.useCaret)&&!P&&E){let Y=ll(),pe=W.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=pe[pe.length-1];if(Me!=null&&Me.parentNode)Me.parentNode.insertBefore(Y,Me.nextSibling);else{let Je=W.lastElementChild;Je?Je.appendChild(Y):W.appendChild(Y)}}if(g&&m==="inline"&&e.createdAt){let Y=Lh(e,d,"span");Y.classList.add("persona-timestamp-inline");let pe=W.lastElementChild;pe?pe.appendChild(Y):W.appendChild(Y)}if(T.length>0){let Y=Bb(T,!P&&!!E,()=>{P&&Z&&(Z.style.display="")});Y?C.appendChild(Y):P&&Z&&(Z.style.display="")}let me=Ib(e);if(me.length>0){let Y=Db(me);Y&&C.appendChild(Y)}let Ke=Wb(e);if(Ke.length>0){let Y=Fb(Ke);Y&&C.appendChild(Y)}let Ce=Hb(e);if(Ce.length>0){let Y=Nb(Ce);Y&&C.appendChild(Y)}if(C.appendChild(W),g&&m==="below"&&e.createdAt){let Y=Lh(e,d);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let Ie=e.role==="assistant"?kb(e.stopReason,(Ze=(be=a==null?void 0:a.widgetConfig)==null?void 0:be.copy)==null?void 0:Ze.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),pe=y.placeholder==="skeleton",Me=pe&&y.buffer==="line"&&Y;if(Y)Me&&C.appendChild(Ns());else if(pe)C.appendChild(Ns());else{let Je=wp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Je&&C.appendChild(Je)}}if(Ie&&e.stopReason&&!e.streaming&&(E||(W.style.display="none"),C.appendChild(Lb(e.stopReason,Ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Y=Sp(e,o,n);C.appendChild(Y)}if(!u||e.role==="system")return C;let Te=S("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),We=Ob(c,e.role);return p==="right"||p==="left"&&e.role==="user"?Te.append(C,We):Te.append(We,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te},Rh=(e,t,r,o,n,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ga(e,t,r,o,n,a)};var Ka=new Set,Ub=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),qb=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
27
|
+
`):""},Ih=(e,t)=>{let r=Ka.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=ve(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},Ap=(e,t)=>{var Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue;let r=e.reasoning,o=S("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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!r)return o;let n=(Ce=(Ke=t==null?void 0:t.features)==null?void 0:Ke.reasoningDisplay)!=null?Ce:{},a=n.expandable!==!1,s=a&&Ka.has(e.id),i=r.status!=="complete",c=qb(e,(Ie=n.previewMaxLines)!=null?Ie:3),d=S("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let u=S("div","persona-flex persona-flex-col persona-text-left"),g=S("span","persona-text-xs persona-text-persona-primary"),p="Thinking...",m=(Ue=t==null?void 0:t.reasoning)!=null?Ue:{},x=String((Te=r.startedAt)!=null?Te:Date.now()),C=()=>{let G=S("span","");return G.setAttribute("data-tool-elapsed",x),G.textContent=Ei(r),G},T=(We=m.renderCollapsedSummary)==null?void 0:We.call(m,{message:e,reasoning:r,defaultSummary:p,previewText:c,isActive:i,config:t!=null?t:{},elapsed:Ei(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,u.appendChild(g)):T instanceof HTMLElement?u.appendChild(T):(g.textContent=p,u.appendChild(g));let E=S("span","persona-text-xs persona-text-persona-primary");E.textContent=Dg(r),u.appendChild(E);let M=(de=n.loadingAnimation)!=null?de:"none",P=m.activeTextTemplate,y=m.completeTextTemplate,w=i?P:y,b=T instanceof HTMLElement,A=(G,ce,Be)=>{let ne=Be;for(let ee of ce){let ie=S("span","persona-tool-char");ie.style.setProperty("--char-index",String(ne)),ie.textContent=ee===" "?"\xA0":ee,G.appendChild(ie),ne++}return ne},H=(G,ce)=>{g.textContent="";let Be=ki(G,""),ne=0;for(let ee of Be){let ie=ee.styles.length>0?(()=>{let vt=S("span",ee.styles.map(Lt=>`persona-tool-text-${Lt}`).join(" "));return g.appendChild(vt),vt})():g;if(ee.isDuration&&i)ie.appendChild(C());else{let vt=ee.isDuration?Ei(r):ee.text;ce?ne=A(ie,vt,ne):ie.appendChild(document.createTextNode(vt))}}};if(!b&&w)if(E.style.display="none",g.style.display="",i&&M!=="none"){let G=(J=m.loadingAnimationDuration)!=null?J:2e3;g.setAttribute("data-preserve-animation","true"),M==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),H(w,!1)):(g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),H(w,!0))}else H(w,!1);else if(!b&&i&&M!=="none"){g.style.display="";let G=(le=m.loadingAnimationDuration)!=null?le:2e3;if(g.setAttribute("data-preserve-animation","true"),M==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ce=g.textContent||p;g.textContent="",A(g,ce,0)}r.status==="complete"&&(g.style.display="none")}else b||(r.status==="complete"?g.style.display="none":g.style.display="");let W=null;if(a){W=S("div","persona-flex persona-items-center");let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.textContent=s?"Hide":"Show";let Be=S("div","persona-flex persona-items-center persona-ml-auto");Be.append(W),d.append(u,Be)}else d.append(u);let k=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let G=(ue=(ge=t==null?void 0:t.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:ue.call(ge,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});Ub(k,G)||(k.textContent=c),k.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(d,k),o;let N=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=s?"":"none";let q=r.chunks.join(""),Z=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=q||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Z),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),W){W.innerHTML="";let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.textContent=s?"Hide":"Show"}N.style.display=s?"":"none",k.style.display=s?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(d,k,N),o};var Xa=new Set,Vb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$b=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
28
|
+
`);let n=Na(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
29
|
+
`):""},zb=(e,t)=>{var u,g,p,m,x;let r=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,n=(g=o==null?void 0:o.collapsedMode)!=null?g:"tool-call",a=$b(e,(p=o==null?void 0:o.previewMaxLines)!=null?p:3),s=r?Fg(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(m=t==null?void 0:t.toolCall)!=null?m:{},d=s;return n==="tool-name"?d=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(d=a),i&&c.activeTextTemplate?d=od(r,c.activeTextTemplate,d):!i&&c.completeTextTemplate&&(d=od(r,c.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},Wh=(e,t,r)=>{var u;let o=Xa.has(e),n=(u=r==null?void 0:r.toolCall)!=null?u:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),d=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=n.toggleTextColor||n.headerTextColor||"currentColor",p=ve(o?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Mp=(e,t)=>{var q,Z,me,Ke,Ce,Ie,Ue,Te,We;let r=e.toolCall,o=(q=t==null?void 0:t.toolCall)!=null?q:{},n=S("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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(me=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Xa.has(e.id),{summary:c,previewText:d,isActive:u}=zb(e,t),g=S("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");g.type="button",s&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let p=S("div","persona-flex persona-flex-col persona-text-left"),m=S("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String((Ke=r.startedAt)!=null?Ke:Date.now()),C=()=>{let de=S("span","");return de.setAttribute("data-tool-elapsed",x),de.textContent=Es(r),de},T=(Ie=o.renderCollapsedSummary)==null?void 0:Ie.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:d,collapsedMode:(Ce=a.collapsedMode)!=null?Ce:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Es(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(m.textContent=T,p.appendChild(m)):T instanceof HTMLElement?p.appendChild(T):(m.textContent=c,p.appendChild(m));let E=(Ue=a.loadingAnimation)!=null?Ue:"none",M=o.activeTextTemplate,P=o.completeTextTemplate,y=u?M:P,w=T instanceof HTMLElement,b=(de,J,le)=>{let ge=le;for(let ue of J){let G=S("span","persona-tool-char");G.style.setProperty("--char-index",String(ge)),G.textContent=ue===" "?"\xA0":ue,de.appendChild(G),ge++}return ge},A=(de,J)=>{var G;m.textContent="";let le=((G=r.name)==null?void 0:G.trim())||"tool",ge=ki(de,le),ue=0;for(let ce of ge){let Be=ce.styles.length>0?(()=>{let ne=S("span",ce.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(ne),ne})():m;if(ce.isDuration&&u)Be.appendChild(C());else{let ne=ce.isDuration?Es(r):ce.text;J?ue=b(Be,ne,ue):Be.appendChild(document.createTextNode(ne))}}};if(!w)if(u&&E!=="none"){let de=(Te=o.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),y&&A(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)A(y,!0);else{let J=m.textContent||c;m.textContent="",b(m,J,0)}}else y&&A(y,!1);let H=null;if(s){H=S("div","persona-flex persona-items-center");let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show";let le=S("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");le.append(H),g.append(p,le)}else g.append(p);let W=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","tool"),W.style.display="none",W.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&d){let de=(We=o.renderCollapsedPreview)==null?void 0:We.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:u,config:t!=null?t:{}});Vb(W,de)||(W.textContent=d),W.style.display=""}if(!i&&u&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(g,W),n;let k=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),r.name){let de=S("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?de.style.color=o.contentTextColor:o.headerTextColor&&(de.style.color=o.headerTextColor),de.textContent=r.name,k.appendChild(de)}if(r.args!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let le=S("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");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Na(r.args),de.append(J,le),k.appendChild(de)}if(r.chunks&&r.chunks.length){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let le=S("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");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=r.chunks.join(""),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&r.result!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let le=S("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");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Na(r.result),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&typeof r.duration=="number"){let de=S("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(de.style.color=o.contentTextColor),de.textContent=`Duration: ${r.duration}ms`,k.appendChild(de)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",W.style.display=i?"none":W.textContent||W.childNodes.length?"":"none"})(),n.append(g,W,k),n};var bl=new Map,jb=e=>{let r=(e.startsWith(tn)?e.slice(tn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Hh=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Bh=(e,t)=>{var o,n,a;let r=(n=(o=Hh(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=bl.get(e))!=null?a:r==="expanded"},Dh=(e,t,r)=>{var s,i;let o=Hh(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let c=ve(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Fh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Bh(e,r);Dh(o,a,r),n.style.display=a?"":"none"};var vl=(e,t)=>{var A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=S("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(A=o==null?void 0:o.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(H=o==null?void 0:o.borderColor)!=null?H:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=S("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=S("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",d=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(W=o==null?void 0:o.titleColor)!=null?W:"currentColor",u=ve(c,20,d,2);u&&i.appendChild(u);let g=S("div","persona-flex-1 persona-min-w-0"),p=S("div","persona-flex persona-items-center persona-gap-2"),m=S("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(k=o==null?void 0:o.title)!=null?k:"Approval Required",p.appendChild(m),!n){let J=S("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",r.status),r.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"):r.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"):r.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"),p.appendChild(J)}g.appendChild(p);let C=r.toolType==="webmcp"||r.toolName.startsWith(tn)?zl(r.toolName):void 0,T=(N=o==null?void 0:o.formatDescription)==null?void 0:N.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...C?{displayTitle:C}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,M=T||(E?r.description:`The assistant wants to use \u201C${C!=null?C:jb(r.toolName)}\u201D.`),P=S("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=M,g.appendChild(P),r.reason){let J=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");J.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?J.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor);let le=S("span","persona-font-medium");le.textContent=`${(q=o==null?void 0:o.reasonLabel)!=null?q:"Agent's stated reason:"} `,J.appendChild(le),J.appendChild(document.createTextNode(r.reason)),g.appendChild(J)}let y=(Z=o==null?void 0:o.detailsDisplay)!=null?Z:"collapsed",w=!!r.description&&!E,b=w||!!r.parameters;if(y!=="hidden"&&b){let J=Bh(e.id,t),le=S("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");le.type="button",le.setAttribute("data-expand-header","true"),le.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(le.style.color=o.descriptionColor);let ge=S("span");ge.setAttribute("data-approval-details-label","true");let ue=S("span","persona-inline-flex persona-items-center");ue.setAttribute("data-approval-details-chevron","true"),le.append(ge,ue),Dh(le,J,t),g.appendChild(le);let G=S("div");if(G.setAttribute("data-approval-details","true"),G.style.display=J?"":"none",w){let ce=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ce.style.color=o.descriptionColor),ce.textContent=r.description,G.appendChild(ce)}if(r.parameters){let ce=S("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");o!=null&&o.parameterBackgroundColor&&(ce.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ce.style.color=o.parameterTextColor),ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",ce.textContent=Na(r.parameters),G.appendChild(ce)}g.appendChild(G)}if(n){let J=S("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let le=S("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");le.type="button",le.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",le.style.color=(Ke=o==null?void 0:o.approveButtonTextColor)!=null?Ke:"#ffffff",le.setAttribute("data-approval-action","approve");let ge=ve("shield-check",14,(Ce=o==null?void 0:o.approveButtonTextColor)!=null?Ce:"#ffffff",2);ge&&(ge.style.marginRight="4px",le.appendChild(ge));let ue=document.createTextNode((Ie=o==null?void 0:o.approveLabel)!=null?Ie:"Approve");le.appendChild(ue);let G=S("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");G.type="button",G.style.backgroundColor=(Ue=o==null?void 0:o.denyButtonColor)!=null?Ue:"transparent",G.style.color=(Te=o==null?void 0:o.denyButtonTextColor)!=null?Te:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let ce=ve("shield-x",14,(We=o==null?void 0:o.denyButtonTextColor)!=null?We:"var(--persona-feedback-error, #dc2626)",2);ce&&(ce.style.marginRight="4px",G.appendChild(ce));let Be=document.createTextNode((de=o==null?void 0:o.denyLabel)!=null?de:"Deny");G.appendChild(Be),J.append(le,G),g.appendChild(J)}return s.append(i,g),a.appendChild(s),a};var Nh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,d)=>{e.innerHTML="",t.length=0;let u=(d==null?void 0:d.agentPushed)===!0;if(u||(r=null),!n||!n.length||!u&&(i!=null?i:a?a.getMessages():[]).some(T=>T.role==="user"))return;let g=document.createDocumentFragment(),p=a?a.isStreaming():!1,m=x=>{switch(x){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'}};if(n.forEach(x=>{let C=S("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");C.type="button",C.textContent=x,C.disabled=p,c!=null&&c.fontFamily&&(C.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(C.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(C.style.paddingLeft=c.paddingX,C.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(C.style.paddingTop=c.paddingY,C.style.paddingBottom=c.paddingY),C.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",u&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),g.appendChild(C),t.push(C)}),e.appendChild(g),u){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var qs=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;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),(r=this.store)==null||r.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 r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.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 Vs=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}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 o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var Gb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Kb=new Set(["step_start","execution_start"]),Xb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Qb=new Set(["step_complete","agent_turn_complete"]),Jb=new Set(["flow_complete","agent_complete"]),Oh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Uh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ao=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,fa=(e,t)=>{let r=e[t];return Uh(r)?r:void 0};function Tp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Cl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Yb(e,t){return typeof t.type=="string"?t.type:e}function Zb(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 ev(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 _h(e){var o,n,a,s,i;let t=fa(e,"result"),r=[fa(e,"tokens"),fa(e,"totalTokens"),t?fa(t,"tokens"):void 0,fa(e,"usage"),t?fa(t,"usage"):void 0];for(let c of r){if(!c)continue;let d=(n=(o=ao(c.output))!=null?o:ao(c.outputTokens))!=null?n:ao(c.completionTokens);if(d!==void 0)return d}return(i=(a=ao(e.outputTokens))!=null?a:ao(e.completionTokens))!=null?i:t?(s=ao(t.outputTokens))!=null?s:ao(t.completionTokens):void 0}function tv(e){var r,o,n,a,s;let t=fa(e,"result");return(s=(n=(o=(r=ao(e.executionTime))!=null?r:ao(e.executionTimeMs))!=null?o:ao(e.execution_time))!=null?n:ao(e.duration))!=null?s:t?(a=ao(t.executionTime))!=null?a:ao(t.executionTimeMs):void 0}function rv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var $s=class{constructor(t=rv){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 r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:Cl(this.metric.outputTokens,r)}}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,r){var a;if(!Uh(r)){Oh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Yb(t,r),n=this.now();if(Gb.has(o)){this.startRun(n);return}if(Kb.has(o)){this.run||this.startRun(n);return}if(Xb.has(o)){if(!ev(o,r))return;let s=Zb(r);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let c=i.exactOutputTokens+Tp(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Cl(c,d),outputTokens:c,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Qb.has(o)){if(!this.run)return;let s=this.run,i=_h(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,d=s.exactOutputTokens+Tp(s.visibleCharCount),u=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Cl(d,u),outputTokens:d,durationMs:u,source:c?"usage":"estimate"};return}if(Jb.has(o)){if(!this.run)return;let s=this.run,i=_h(r),c=i!=null?i:s.exactOutputTokens+Tp(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Cl(c,u),outputTokens:c,durationMs:u,source:d},this.run=null;return}if(Oh.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,o){let n=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=tv(r);return a!=null?a:o-t.startedAt}};function Qa(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var ov={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)"}},nv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},av=["flowName","stepName","reasoningText","text","name","tool","toolName"],sv=100;function iv(e,t){let r={...ov,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return nv}function lv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function dv(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${o}:${n}.${a}`}function cv(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let o of t){let n=o.split("."),a=r;for(let s of n)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function pv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function uv(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 fv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function mv(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 gv(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=S("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]"),c=S("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,i.appendChild(c),i}}function Ep(e,t,r,o,n,a,s,i){var p;let c=n.has(e.id),d=S("div","persona-border-b persona-border-persona-divider persona-text-xs");Qa(d,(p=o.classNames)==null?void 0:p.eventRow);let u=s.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>g(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(g()),d;function g(){var q,Z;let m=S("div",""),x=S("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let C=S("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=ve(c?"chevron-down":"chevron-right","14px","currentColor",2);T&&C.appendChild(T);let E=S("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(q=o.timestampFormat)!=null?q:"relative";E.textContent=M==="relative"?lv(e.timestamp,r):dv(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=S("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let y=iv(e.type,o.badgeColors),w=S("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=y.bg,w.style.color=y.text,w.style.borderColor=y.text+"50",w.textContent=e.type;let b=(Z=o.descriptionFields)!=null?Z:av,A=cv(e.payload,b),H=null;A&&(H=S("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=A);let W=S("div","persona-flex-1 persona-min-w-0"),k=S("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"),N=ve("clipboard","12px","currentColor",1.5);return N&&k.appendChild(N),k.addEventListener("click",async me=>{me.stopPropagation(),await pv(uv(e)),k.innerHTML="";let Ke=ve("check","12px","currentColor",1.5);Ke&&k.appendChild(Ke),setTimeout(()=>{k.innerHTML="";let Ce=ve("clipboard","12px","currentColor",1.5);Ce&&k.appendChild(Ce)},1500)}),x.appendChild(C),x.appendChild(E),P&&x.appendChild(P),x.appendChild(w),H&&x.appendChild(H),x.appendChild(W),x.appendChild(k),m.appendChild(x),c&&m.appendChild(gv(e,s,i)),m}}function qh(e){var x,C,T,E,M;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,d=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",g=(M=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?M:{},p=a.find(P=>P.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&n){let P=p.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=g.classNames,y=S("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Qa(y,P==null?void 0:P.panel);let w=[],b="",A="",H=null,W=[],k={},N=0,q=ol(),Z=0,me=0,Ke=!1,Ce=null,Ie=!1,Ue=0,Te=new Set,We=new Map,de="",J="",le=null,ge,ue,G,ce,Be,ne=null,ee=null,ie=null;function vt(){let oe=S("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=S("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");Qa(we,P==null?void 0:P.headerBar);let De=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(De.textContent="Events",ge=S("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"),ge.textContent="0",s){ee=S("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let so=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");so.textContent="Throughput",ne=S("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"),ne.textContent="-- tok/s",ie=S("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"),ie.style.display="none",ie.style.pointerEvents="none";let Rr=ee,ir=ie,Ur=()=>{if(!ir.textContent)return;let yt=Rr.getBoundingClientRect(),jr=oe.getBoundingClientRect();ir.style.left=`${yt.left-jr.left}px`,ir.style.top=`${yt.bottom-jr.top+4}px`,ir.style.display="block"},ko=()=>{ir.style.display="none"};ee.addEventListener("mouseenter",Ur),ee.addEventListener("mouseleave",ko),ee.appendChild(so),ee.appendChild(ne)}let At=S("div","persona-flex-1");ue=S("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 ar=S("option","");ar.value="",ar.textContent="All events",ue.appendChild(ar),G=S("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"),G.type="button",G.title="Copy All";let wr=ve("clipboard-copy","12px","currentColor",1.5);wr&&G.appendChild(wr);let Ft=S("span","persona-text-xs");Ft.textContent="Copy All",G.appendChild(Ft),we.appendChild(De),we.appendChild(ge),ee&&we.appendChild(ee),we.appendChild(At),we.appendChild(ue),we.appendChild(G);let ot=S("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Qa(ot,P==null?void 0:P.searchBar);let Dt=ve("search","14px","var(--persona-muted, #9ca3af)",1.5),lt=S("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Dt&<.appendChild(Dt),ce=S("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"),Qa(ce,P==null?void 0:P.searchInput),ce.type="text",ce.placeholder="Search event payloads...",Be=S("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"),Be.type="button",Be.style.display="none";let Yt=ve("x","12px","currentColor",2);return Yt&&Be.appendChild(Yt),ot.appendChild(lt),ot.appendChild(ce),ot.appendChild(Be),oe.appendChild(we),oe.appendChild(ot),ie&&oe.appendChild(ie),oe}let Lt,gt=a.find(oe=>oe.renderEventStreamToolbar);if(gt!=null&>.renderEventStreamToolbar&&n){let oe=gt.renderEventStreamToolbar({config:n,defaultRenderer:()=>vt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:we=>{b=we,Wt(),V()},onSearchChange:we=>{A=we,Wt(),V()}});Lt=oe!=null?oe:vt()}else Lt=vt();let _e=S("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");_e.style.display="none";function be(){if(!s||!ne||!ee)return;let oe=s();ne.textContent=fv(oe);let we=mv(oe);ie&&(ie.textContent=we,we||(ie.style.display="none")),we?ee.setAttribute("aria-label",we):ee.removeAttribute("aria-label")}let Ze=S("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=S("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let pe=S("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");Qa(pe,P==null?void 0:P.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Me=ve(d,"14px","currentColor",2);Me&&pe.appendChild(Me);let Je=S("span","");Je.textContent=u,pe.appendChild(Je);let Ge=S("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ge.style.display="none",Ze.appendChild(Y),Ze.appendChild(Ge),Ze.appendChild(pe),y.setAttribute("tabindex","0"),y.appendChild(Lt),y.appendChild(_e),y.appendChild(Ze);function ke(){let oe=t.getAll(),we={};for(let Ft of oe)we[Ft.type]=(we[Ft.type]||0)+1;let De=Object.keys(we).sort(),At=De.length!==W.length||!De.every((Ft,ot)=>Ft===W[ot]),ar=!At&&De.some(Ft=>we[Ft]!==k[Ft]),sr=oe.length!==Object.values(k).reduce((Ft,ot)=>Ft+ot,0);if(!At&&!ar&&!sr||(W=De,k=we,!ue))return;let wr=ue.value;if(ue.options[0].textContent="All events",At){for(;ue.options.length>1;)ue.remove(1);for(let Ft of De){let ot=S("option","");ot.value=Ft,ot.textContent=`${Ft} (${we[Ft]||0})`,ue.appendChild(ot)}wr&&De.includes(wr)?ue.value=wr:wr&&(ue.value="",b="")}else for(let Ft=1;Ft<ue.options.length;Ft++){let ot=ue.options[Ft];ot.textContent=`${ot.value} (${we[ot.value]||0})`}}function je(){let oe=t.getAll();if(b&&(oe=oe.filter(we=>we.type===b)),A){let we=A.toLowerCase();oe=oe.filter(De=>De.type.toLowerCase().includes(we)||De.payload.toLowerCase().includes(we))}return oe}function Cr(){return b!==""||A!==""}function Wt(){N=0,Z=0,q.resume(),pe.style.display="none"}function ur(oe){Te.has(oe)?Te.delete(oe):Te.add(oe),le=oe;let we=Y.scrollTop,De=q.isFollowing();Ie=!0,q.pause(),V(),Y.scrollTop=we,De&&q.resume(),Ie=!1}function Eo(){return da(Y,50)}function V(){me=Date.now(),Ke=!1,be(),ke();let oe=t.getEvictedCount();oe>0?(_e.textContent=`${oe.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",w=je();let we=w.length,De=t.getSize()>0;ge&&(ge.textContent=String(t.getSize())),we===0&&De&&Cr()?(Ge.textContent=A?`No events matching '${A}'`:"No events matching filter",Ge.style.display="",Y.style.display="none"):(Ge.style.display="none",Y.style.display=""),G&&(G.title=Cr()?`Copy Filtered (${we})`:"Copy All"),c&&!q.isFollowing()&&we>N&&(Z+=we-N,Je.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",pe.style.display=""),N=we;let At=t.getAll(),ar=At.length>0?At[0].timestamp:0,sr=new Set(w.map(ot=>ot.id));for(let ot of Te)sr.has(ot)||Te.delete(ot);let wr=b!==de||A!==J,Ft=We.size===0&&w.length>0;if(wr||Ft||w.length===0){Y.innerHTML="",We.clear();let ot=document.createDocumentFragment();for(let Dt=0;Dt<w.length;Dt++){let lt=Ep(w[Dt],Dt,ar,g,Te,ur,a,n);We.set(w[Dt].id,lt),ot.appendChild(lt)}Y.appendChild(ot),de=b,J=A,le=null}else{if(le!==null){let Dt=We.get(le);if(Dt&&Dt.parentNode===Y){let lt=w.findIndex(Yt=>Yt.id===le);if(lt>=0){let Yt=Ep(w[lt],lt,ar,g,Te,ur,a,n);Y.insertBefore(Yt,Dt),Dt.remove(),We.set(le,Yt)}}le=null}let ot=new Set(w.map(Dt=>Dt.id));for(let[Dt,lt]of We)ot.has(Dt)||(lt.remove(),We.delete(Dt));for(let Dt=0;Dt<w.length;Dt++){let lt=w[Dt];if(!We.has(lt.id)){let Yt=Ep(lt,Dt,ar,g,Te,ur,a,n);We.set(lt.id,Yt),Y.appendChild(Yt)}}}q.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function j(){if(Date.now()-me>=sv){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),V();return}Ke||(Ke=!0,Ce=requestAnimationFrame(()=>{Ce=null,V()}))}let he=(oe,we)=>{if(!G)return;G.innerHTML="";let De=ve(oe,"12px","currentColor",1.5);De&&G.appendChild(De);let At=S("span","persona-text-xs");At.textContent="Copy All",G.appendChild(At),setTimeout(()=>{G.innerHTML="";let ar=ve("clipboard-copy","12px","currentColor",1.5);ar&&G.appendChild(ar);let sr=S("span","persona-text-xs");sr.textContent="Copy All",G.appendChild(sr),G.disabled=!1},we)},Xe=async()=>{if(G){G.disabled=!0;try{let oe;Cr()?oe=w:r?(oe=await r(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let we=oe.map(De=>{try{return JSON.parse(De.payload)}catch{return De.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),he("check",1500)}catch{he("x",1500)}}},et=()=>{ue&&(b=ue.value,Wt(),V())},qe=()=>{!ce||!Be||(Be.style.display=ce.value?"":"none",H&&clearTimeout(H),H=setTimeout(()=>{A=ce.value,Wt(),V()},150))},Ne=()=>{!ce||!Be||(ce.value="",A="",Be.style.display="none",H&&clearTimeout(H),Wt(),V())},Pt=()=>{if(Ie)return;let oe=Y.scrollTop,{action:we,nextLastScrollTop:De}=nl({following:q.isFollowing(),currentScrollTop:oe,lastScrollTop:Ue,nearBottom:Eo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ue=De,we==="resume"?(q.resume(),Z=0,pe.style.display="none"):we==="pause"&&(q.pause(),c&&(Je.textContent=u,pe.style.display=""))},Gt=oe=>{let we=al({following:q.isFollowing(),deltaY:oe.deltaY,nearBottom:Eo(),resumeWhenNearBottom:!0});we==="pause"?(q.pause(),c&&(Je.textContent=u,pe.style.display="")):we==="resume"&&(q.resume(),Z=0,pe.style.display="none")},Jt=()=>{c&&(Y.scrollTop=Y.scrollHeight,q.resume(),Z=0,pe.style.display="none")},Pr=oe=>{let we=oe.target;if(!we||we.closest("button"))return;let De=we.closest("[data-event-id]");if(!De)return;let At=De.getAttribute("data-event-id");At&&ur(At)},z=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),ce==null||ce.focus(),ce==null||ce.select();return}oe.key==="Escape"&&(ce&&document.activeElement===ce?(Ne(),ce.blur(),y.focus()):o&&o())};G&&G.addEventListener("click",Xe),ue&&ue.addEventListener("change",et),ce&&ce.addEventListener("input",qe),Be&&Be.addEventListener("click",Ne),Y.addEventListener("scroll",Pt),Y.addEventListener("wheel",Gt,{passive:!0}),Y.addEventListener("click",Pr),pe.addEventListener("click",Jt),y.addEventListener("keydown",z);function Ht(){H&&clearTimeout(H),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ke=!1,We.clear(),G&&G.removeEventListener("click",Xe),ue&&ue.removeEventListener("change",et),ce&&ce.removeEventListener("input",qe),Be&&Be.removeEventListener("click",Ne),Y.removeEventListener("scroll",Pt),Y.removeEventListener("wheel",Gt),Y.removeEventListener("click",Pr),pe.removeEventListener("click",Jt),y.removeEventListener("keydown",z)}return{element:y,update:j,destroy:Ht}}}function Vh(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(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 ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #171717)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(m)}else g.textContent=s;if(d.append(u,g),i.append(c,d),n==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${r}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",o),i.append(p)}return i}var $h=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",d=typeof e.artifactType=="string"?e.artifactType:"markdown",u=r({artifact:{artifactId:i,title:s,artifactType:d,status:c},config:t.config,defaultRenderer:()=>Vh(e,t)});if(u)return u}return Vh(e,t)};var kp=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}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(([r,o])=>{this.register(r,o)})}},dn=new kp;dn.register("PersonaArtifactCard",$h);function hv(e){var n;let t=S("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=S("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function zh(e,t){var ue,G,ce,Be;let r=(G=(ue=e.features)==null?void 0:ue.artifacts)==null?void 0:G.layout,n=((ce=r==null?void 0:r.toolbarPreset)!=null?ce:"default")==="document",a=(Be=r==null?void 0:r.panePadding)==null?void 0:Be.trim(),s=e.markdown?Zn(e.markdown):null,i=Wa(e.sanitize),c=ne=>{let ee=s?s(ne):qo(ne);return i?i(ee):ee},d=typeof document!="undefined"?S("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{d==null||d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};d&&d.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let g=S("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");g.setAttribute("data-persona-theme-zone","artifact-pane"),n&&g.classList.add("persona-artifact-pane-document");let p=S("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");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&p.classList.add("persona-artifact-toolbar-document");let m=S("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=S("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let C="rendered",T=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?yr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yr({icon:"eye",label:"Rendered view"}),M=n?yr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yr({icon:"code-2",label:"Source"}),P=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,b=r==null?void 0:r.documentToolbarCopyMenuItems,A=!!(w&&b&&b.length>0),H=null,W,k=null,N=null;if(n&&(y||w)&&!A){if(W=y?Us({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ne=ve("chevron-down",14,"currentColor",2);ne&&W.appendChild(ne)}}else n&&A?(H=S("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),W=y?Us({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yr({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"}}),H.append(W,k)):n?W=yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):W=yr({icon:"copy",label:"Copy"});let q=n?yr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yr({icon:"refresh-cw",label:"Refresh"}),Z=n?yr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yr({icon:"x",label:"Close"}),me=()=>{var Lt,gt,_e;let ne=(Lt=We.find(be=>be.id===de))!=null?Lt:We[We.length-1],ee=(gt=ne==null?void 0:ne.id)!=null?gt:null,ie=(ne==null?void 0:ne.artifactType)==="markdown"&&(_e=ne.markdown)!=null?_e:"",vt=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:ie,jsonPayload:vt,id:ee}},Ke=async()=>{var Lt;let{markdown:ne,jsonPayload:ee}=me(),ie=(Lt=We.find(gt=>gt.id===de))!=null?Lt:We[We.length-1],vt=(ie==null?void 0:ie.artifactType)==="markdown"?ne:ie?ee:"";try{await navigator.clipboard.writeText(vt)}catch{}};if(W.addEventListener("click",async()=>{let ne=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ne&&A){let{markdown:ee,jsonPayload:ie,id:vt}=me();try{await ne({actionId:"primary",artifactId:vt,markdown:ee,jsonPayload:ie})}catch{}return}await Ke()}),k&&(b!=null&&b.length)){let ne=()=>{var ie;return(ie=g.closest("[data-persona-root]"))!=null?ie:document.body},ee=()=>{N=Fn({items:b.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:vt,jsonPayload:Lt,id:gt}=me(),_e=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:ie,artifactId:gt,markdown:vt,jsonPayload:Lt}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(vt):ie==="json"||ie==="source"?await navigator.clipboard.writeText(Lt):await navigator.clipboard.writeText(vt||Lt)}catch{}},anchor:H!=null?H:k,position:"bottom-right",portal:ne()})};g.isConnected?ee():requestAnimationFrame(ee),k.addEventListener("click",ie=>{ie.stopPropagation(),N==null||N.toggle()})}q.addEventListener("click",async()=>{var ne;try{await((ne=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ne.call(r))}catch{}le()}),Z.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let Ce=()=>{n&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),M.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",Ce(),le()}),M.addEventListener("click",()=>{C="source",Ce(),le()});let Ie=S("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");n?(p.replaceChildren(),T.append(E,M),H?P.append(H,q,Z):P.append(W,q,Z),p.append(T,Ie,P),Ce()):(p.appendChild(m),p.appendChild(x)),a&&(p.style.paddingLeft=a,p.style.paddingRight=a);let Ue=S("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"),Te=S("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ue.style.paddingLeft=a,Ue.style.paddingRight=a,Te.style.padding=a),g.appendChild(p),g.appendChild(Ue),g.appendChild(Te);let We=[],de=null,J=!1,le=()=>{var vt,Lt,gt,_e;let ne=n&&We.length<=1;Ue.classList.toggle("persona-hidden",ne),Ue.replaceChildren();for(let be of We){let Ze=S("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");Ze.type="button",Ze.textContent=be.title||be.id.slice(0,8),be.id===de&&Ze.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ze.addEventListener("click",()=>t.onSelect(be.id)),Ue.appendChild(Ze)}Te.replaceChildren();let ee=de&&We.find(be=>be.id===de)||We[We.length-1];if(!ee)return;if(n){let be=ee.artifactType==="markdown"?"MD":(vt=ee.component)!=null?vt:"Component",Y=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${Y} \xB7 ${be}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(n&&C==="source"){let Ze=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ze.textContent=(Lt=ee.markdown)!=null?Lt:"",Te.appendChild(Ze);return}let be=S("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");be.innerHTML=c((gt=ee.markdown)!=null?gt:""),Te.appendChild(be);return}let ie=ee.component?dn.get(ee.component):void 0;if(ie){let Ze={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=ie((_e=ee.props)!=null?_e:{},Ze);if(Y){Te.appendChild(Y);return}}catch{}}Te.appendChild(hv(ee))},ge=()=>{var ee;let ne=We.length>0;if(g.classList.toggle("persona-hidden",!ne),d){let ie=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,Lt=((ee=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&Lt&&J?(d.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:d,update(ne){var ee,ie,vt;We=ne.artifacts,de=(vt=(ie=ne.selectedId)!=null?ie:(ee=ne.artifacts[ne.artifacts.length-1])==null?void 0:ee.id)!=null?vt:null,We.length>0&&(J=!0),le(),ge()},setMobileOpen(ne){J=ne,!ne&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ge()}}}function xo(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function jh(e,t){var a,s,i,c;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"),!xo(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(c=r==null?void 0:r.paneBorderLeft)==null?void 0:c.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function xv(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 wl(e,t){var c,d,u,g,p,m,x,C,T,E;if(!xo(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"),xv(e),jh(e,t);return}let r=(d=(c=t.features)==null?void 0:c.artifacts)==null?void 0:d.layout;e.style.setProperty("--persona-artifact-split-gap",(u=r==null?void 0:r.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(g=r==null?void 0:r.paneWidth)!=null?g:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(p=r==null?void 0:r.paneMaxWidth)!=null?p:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(T=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:T.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=r==null?void 0:r.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"),jh(e,t)}var Gh=["panel","seamless"];function Sl(e,t){var i,c,d,u,g,p;for(let m of Gh)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"),!xo(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=Gh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(u=r==null?void 0:r.paneBorderRadius)==null?void 0:u.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(g=r==null?void 0:r.paneShadow)==null?void 0:g.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((p=r.unifiedSplitOuterRadius)==null?void 0:p.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Kh(e,t){var r,o,n;return!t||!xo(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function yv(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function bv(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 vv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function Cv(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Xh(e,t){var s;let o=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Qh(e,t,r,o,n,a){let s=yv(n,200),i=Cv(t,r,o,200);i=Math.max(s,i);let c=bv(a);return c!==null&&(i=Math.min(i,c)),vv(e,s,i)}var Jh={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"}},Lp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,C,T;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(C=Jh[s])!=null?C:Jh.init;a.classList.add("persona-form-card","persona-space-y-4");let c=S("div","persona-space-y-1"),d=S("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,c.appendChild(d),i.description){let E=S("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var b,A;let M=S("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${t.id}-${s}-${E.name}`;let P=S("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=E.label,M.appendChild(P);let y=(b=E.type)!=null?b:"text",w;y==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=y),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}-${s}-${E.name}`,w.name=E.name,w.placeholder=(A=E.placeholder)!=null?A:"",E.required&&(w.required=!0),M.appendChild(w),u.appendChild(M)});let g=S("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),p=S("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=S("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(T=i.submitLabel)!=null?T:"Submit",g.appendChild(p),g.appendChild(m),u.appendChild(g),a.replaceChildren(c,u),u.addEventListener("submit",async E=>{var w,b;E.preventDefault();let M=(w=r.formEndpoint)!=null?w:"/form",P=new FormData(u),y={};P.forEach((A,H)=>{y[H]=A}),y.type=s,m.disabled=!0,p.textContent="Submitting\u2026";try{let A=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let H=await A.json();p.textContent=(b=H.message)!=null?b:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(A){p.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Pp=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,c;return((i=s.priority)!=null?i:0)-((c=a.priority)!=null?c:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},zs=new Pp;var Yh=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var wv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Sv=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},js=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wv(e),r=Sv(t);if(!r)return null;let o=JSON.parse(r);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Rp=e=>typeof e=="string"?e:e==null?"":String(e),ma={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Rp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Rp(r.element);if(o&&((n=t.document)!=null&&n.querySelector)){let a=t.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Rp(r.text)}}},Zh=e=>Array.isArray(e)?e.map(t=>String(t)):[],Gs=e=>{let t=new Set(Zh(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Zh(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.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=s?e.parsers.reduce((d,u)=>d||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let u=()=>{e.emit("action:resubmit",c)},g=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let p=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:p,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:r}};var Av=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}},Mv=e=>e.map(t=>({...t,streaming:!1})),Tv=e=>e.map(t=>({...t,status:"complete"})),Al=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Av(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?Mv(r.messages):void 0,artifacts:r.artifacts?Tv(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ja=Pa(bi(),1);function Ev(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function kv(e,t){if(!Ev(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function Ml(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e;try{let n=(0,Ja.parse)(r,Ja.STR|Ja.OBJ),a=kv(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function ex(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Tl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=dn.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function tx(){let e=Ml();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rx(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 El(e){let t=rx(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function kl(e){let t=rx(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let o=r;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Lv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ll(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:d=Lv}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,p=document.createElement("div");p.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=n,m.appendChild(C),p.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let b=1;b<=5;b++){let A=document.createElement("button");A.type="button",A.className="persona-feedback-rating-btn persona-feedback-star-btn",A.setAttribute("role","radio"),A.setAttribute("aria-checked","false"),A.setAttribute("aria-label",`${b} star${b>1?"s":""}: ${d[b-1]}`),A.title=d[b-1],A.dataset.rating=String(b),A.innerHTML=`
|
|
75
30
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
76
31
|
<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>
|
|
77
32
|
</svg>
|
|
78
|
-
`,E.addEventListener("click",()=>{f=v,M.forEach((H,I)=>{let P=I<v;H.classList.toggle("selected",P),H.setAttribute("aria-checked",I===v-1?"true":"false")})}),M.push(E),T.appendChild(E)}p.appendChild(T);let k=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=a,k.rows=3,k.setAttribute("aria-label","Additional comments"),v.appendChild(k),p.appendChild(v)}let L=document.createElement("div");L.className="persona-feedback-actions";let x=document.createElement("button");x.type="button",x.className="persona-feedback-btn persona-feedback-btn-skip",x.textContent=i,x.addEventListener("click",()=>{t==null||t(),u.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=s,w.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let v=(k==null?void 0:k.value.trim())||void 0;await e(f,v),u.remove()}catch(v){w.disabled=!1,w.textContent=s,console.error("[CSAT Feedback] Failed to submit:",v)}}),L.appendChild(x),L.appendChild(w),p.appendChild(L),u.appendChild(p),u}function nd(r){let{onSubmit:e,onDismiss:t,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=r,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let p=null,m=document.createElement("div");m.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,y.appendChild(h);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=n,y.appendChild(T),m.appendChild(y);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-nps",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=l;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=u,k.appendChild(L),k.appendChild(x);let w=document.createElement("div");w.className="persona-feedback-numbers";let v=[];for(let z=0;z<=10;z++){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 ${z} out of 10`),j.textContent=String(z),j.dataset.rating=String(z),z<=6?j.classList.add("persona-feedback-detractor"):z<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{p=z,v.forEach((ie,ve)=>{ie.classList.toggle("selected",ve===z),ie.setAttribute("aria-checked",ve===z?"true":"false")})}),v.push(j),w.appendChild(j)}M.appendChild(k),M.appendChild(w),m.appendChild(M);let E=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=a,E.rows=3,E.setAttribute("aria-label","Additional comments"),z.appendChild(E),m.appendChild(z)}let H=document.createElement("div");H.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",()=>{t==null||t(),f.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=s,P.addEventListener("click",async()=>{if(p===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let z=(E==null?void 0:E.value.trim())||void 0;await e(p,z),f.remove()}catch(z){P.disabled=!1,P.textContent=s,console.error("[NPS Feedback] Failed to submit:",z)}}),H.appendChild(I),H.appendChild(P),m.appendChild(H),f.appendChild(m),f}var cs="persona-chat-history",QC=30*1e3,YC={"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 JC(r){var o,n,a;if(!r)return[];let e=[],t=Array.from((o=r.items)!=null?o:[]);for(let s of t){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(n=YC[i.type])!=null?n:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let s of Array.from((a=r.files)!=null?a:[]))s.type.startsWith("image/")&&e.push(s);return e}function ad(r){if(!r)return!1;let e=r.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function ZC(r){var e,t,o,n,a,s,i,d,l;return r?r===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=r.storage)!=null?e:"session",keyPrefix:(t=r.keyPrefix)!=null?t:"persona-",persist:{openState:(n=(o=r.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=r.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(d=(i=r.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=r.clearOnChatClear)!=null?l:!0}:null}function ew(r){try{let e=r==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var gu=r=>!r||typeof r!="object"?{}:{...r},fy=r=>r.map(e=>({...e,streaming:!1})),my=(r,e,t)=>{let o=r!=null&&r.markdown?ua(r.markdown):null,n=ja(r==null?void 0:r.sanitize);return r!=null&&r.postprocessMessage&&n&&(r==null?void 0:r.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."),a=>{var l,u,f;let s=(l=a.text)!=null?l:"",i=(u=a.message.rawContent)!=null?u:null;if(e){let p=e.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});p!==null&&(s=p.text,p.persist||(a.message.__skipPersist=!0),p.resubmit&&!a.streaming&&t&&t())}let d;return r!=null&&r.postprocessMessage?d=r.postprocessMessage({...a,text:s,raw:(f=i!=null?i:a.text)!=null?f:""}):o?d=o(s):d=fa(s),n?n(d):d}};function gy(r){var i,d,l,u;let e=C("div","persona-attachment-drop-overlay");r!=null&&r.background&&e.style.setProperty("--persona-drop-overlay-bg",r.background),(r==null?void 0:r.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",r.backdropBlur),r!=null&&r.border&&e.style.setProperty("--persona-drop-overlay-border",r.border),r!=null&&r.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",r.borderRadius),r!=null&&r.inset&&e.style.setProperty("--persona-drop-overlay-inset",r.inset),r!=null&&r.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",r.labelSize),r!=null&&r.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",r.labelColor);let t=(i=r==null?void 0:r.iconName)!=null?i:"upload",o=(d=r==null?void 0:r.iconSize)!=null?d:"48px",n=(l=r==null?void 0:r.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(u=r==null?void 0:r.iconStrokeWidth)!=null?u:.5,s=Ee(t,o,n,a);if(s&&e.appendChild(s),r!=null&&r.label){let f=C("span","persona-drop-overlay-label");f.textContent=r.label,e.appendChild(f)}return e}var sd=(r,e,t)=>{var Gu,Ku,Xu,Qu,Yu,Ju,Zu,ef,tf,rf,of,nf,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,Cf,wf,Af,Sf,Tf,Mf,kf,Ef,Lf,Pf,Rf,If,Hf,Wf,Bf,Df,Of,_f,Nf,Ff,Uf,qf,zf;if(r==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');r.id&&!r.getAttribute("data-persona-instance")&&r.setAttribute("data-persona-instance",r.id),r.hasAttribute("data-persona-root")||r.setAttribute("data-persona-root","true");let o=Tl(e),n=mi.getForInstance(o.plugins);o.components&&En.registerAll(o.components);let a=ly(),i=o.persistState===!1?null:(Gu=o.storageAdapter)!=null?Gu:Jl(),d={},l=null,u=!1,f=c=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:S}=g;return S&&(u=!0),b}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let b=g!=null?g:{messages:[],metadata:{}};return f(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=f(g);b.metadata&&(d=gu(b.metadata)),(Ku=b.messages)!=null&&Ku.length&&(o={...o,initialMessages:b.messages}),(Xu=b.artifacts)!=null&&Xu.length&&(o={...o,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Qu=b.selectedArtifactId)!=null?Qu:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=f({messages:[],metadata:{}});(Yu=c.messages)!=null&&Yu.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let p=()=>d,m=c=>{var b;d=(b=c({...d}))!=null?b:{},Wa()},y=o.actionParsers&&o.actionParsers.length?o.actionParsers:[gi],h=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ea.message,Ea.messageAndClick],T=hi({parsers:y,handlers:h,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let M=(Zu=(Ju=o.launcher)==null?void 0:Ju.enabled)!=null?Zu:!0,k=(tf=(ef=o.launcher)==null?void 0:ef.autoExpand)!=null?tf:!1,L=(rf=o.autoFocusInput)!=null?rf:!1,x=k,w=M,v=(nf=(of=o.layout)==null?void 0:of.header)==null?void 0:nf.layout,E=!1,H=()=>Kn(o),I=()=>M||H(),P=H()?!1:M?k:!0,z=!1,j=null,ie=()=>{z=!0,j&&clearTimeout(j),j=setTimeout(()=>{z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),z=!1)},1e4)},ve=my(o,T,ie),Xe=(sf=(af=o.features)==null?void 0:af.showReasoning)!=null?sf:!0,Ae=(df=(lf=o.features)==null?void 0:lf.showToolCalls)!=null?df:!0,We=(pf=(cf=o.features)==null?void 0:cf.showEventStreamToggle)!=null?pf:!1,Me=(ff=(uf=o.features)==null?void 0:uf.scrollToBottom)!=null?ff:{},Ue=(gf=(mf=o.features)==null?void 0:mf.scrollBehavior)!=null?gf:{},Z=`${(xf=typeof o.persistState=="object"?(hf=o.persistState)==null?void 0:hf.keyPrefix:void 0)!=null?xf:"persona-"}event-stream`,ne=We?new ui(Z):null,me=(vf=(bf=(yf=o.features)==null?void 0:yf.eventStream)==null?void 0:bf.maxEvents)!=null?vf:2e3,be=We?new pi(me,ne):null,ye=We?new fi:null,Y=null,ge=!1,Oe=null,ce=0;ne==null||ne.open().then(()=>be==null?void 0:be.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ae={onCopy:c=>{var g,b;a.emit("message:copy",c),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(c.id,"copy").catch(S=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(b=(g=o.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;a.emit("message:feedback",c),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(c.messageId,c.type).catch(S=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(b=(g=o.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},Q=(Cf=o.statusIndicator)!=null?Cf:{},Tt=c=>{var g,b,S,W;return c==="idle"?(g=Q.idleText)!=null?g:ao.idle:c==="connecting"?(b=Q.connectingText)!=null?b:ao.connecting:c==="connected"?(S=Q.connectedText)!=null?S:ao.connected:c==="error"?(W=Q.errorText)!=null?W:ao.error:ao[c]};function Ye(c,g,b,S){if(S==="idle"&&b.idleLink){c.textContent="";let W=document.createElement("a");W.href=b.idleLink,W.target="_blank",W.rel="noopener noreferrer",W.textContent=g,W.style.color="inherit",W.style.textDecoration="none",c.appendChild(W)}else c.textContent=g}let{wrapper:De,panel:le,pillRoot:nt}=Ox(o),Re=_x(o,I()),{container:K,body:he,messagesWrapper:it,suggestions:Pt,textarea:te,sendButton:_e,sendButtonWrapper:Ar,composerForm:Rt,statusText:dr,introTitle:Yr,introSubtitle:zr,closeButton:O,iconHolder:fe,headerTitle:Ie,headerSubtitle:Je,header:qe,footer:ze,actionsRow:lt,leftActions:Mt,rightActions:Dt}=Re,or=Re.setSendButtonMode,X=Re.micButton,wt=Re.micButtonWrapper,ct=Re.attachmentButton,Ce=Re.attachmentButtonWrapper,de=Re.attachmentInput,rt=Re.attachmentPreviewsContainer;K.classList.add("persona-relative"),he.classList.add("persona-relative");let Ft=12,zt=()=>{var c;return(c=Me.label)!=null?c:""},Pr=()=>{var c;return(c=Me.iconName)!=null?c:"arrow-down"},vr=()=>Me.enabled!==!1,xt=()=>{var c;return(c=Ue.mode)!=null?c:"follow"},It=()=>{var c;return(c=Ue.anchorTopOffset)!=null?c:16},tt=C("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 jt=C("span","persona-flex persona-items-center"),cr=C("span",""),Dr=C("span","");Dr.setAttribute("data-persona-scroll-to-bottom-count",""),Dr.style.display="none",tt.append(jt,cr,Dr),K.appendChild(tt);let hr=C("div","persona-stream-anchor-spacer");hr.setAttribute("aria-hidden","true"),hr.setAttribute("data-persona-anchor-spacer",""),hr.style.flexShrink="0",hr.style.pointerEvents="none",hr.style.height="0px",he.appendChild(hr);let Sr=()=>{let g=ze.style.display==="none"?0:ze.offsetHeight;tt.style.bottom=`${g+Ft}px`};Sr();let Oo=()=>{let c=!!zt();tt.setAttribute("aria-label",zt()||"Jump to latest"),tt.title=zt(),tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),jt.innerHTML="";let g=Ee(Pr(),"14px","currentColor",2);g?(jt.appendChild(g),jt.style.display=""):jt.style.display="none",cr.textContent=zt(),cr.style.display=c?"":"none"};Oo();let je=null,Tr=null,io=n.find(c=>c.renderHeader);if(io!=null&&io.renderHeader){let c=io.renderHeader({config:o,defaultRenderer:()=>{let g=kn({config:o,showClose:I()});return Ta(K,g,o),g.header},onClose:()=>Gt(!1,"user")});if(c){let g=K.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),qe=c)}}let _o=()=>{var g,b,S,W;if(!be)return;if(ge=!0,!Y&&be&&(Y=Jx({buffer:be,getFullHistory:()=>be.getAllFromStore(),onClose:()=>lo(),config:o,plugins:n,getThroughput:()=>{var F;return(F=ye==null?void 0:ye.getMetric())!=null?F:{status:"idle"}}})),Y&&(he.style.display="none",(g=ze.parentNode)==null||g.insertBefore(Y.element,ze),Y.update()),At){At.style.boxShadow=`inset 0 0 0 1.5px ${Ao.actionIconColor}`;let F=(W=(S=(b=o.features)==null?void 0:b.eventStream)==null?void 0:S.classNames)==null?void 0:W.toggleButtonActive;F&&F.split(/\s+/).forEach(q=>q&&At.classList.add(q))}let c=()=>{if(!ge)return;let F=Date.now();F-ce>=200&&(Y==null||Y.update(),ce=F),Oe=requestAnimationFrame(c)};ce=0,Oe=requestAnimationFrame(c),To(),a.emit("eventStream:opened",{timestamp:Date.now()})},lo=()=>{var c,g,b;if(ge){if(ge=!1,Y&&Y.element.remove(),he.style.display="",At){At.style.boxShadow="";let S=(b=(g=(c=o.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;S&&S.split(/\s+/).forEach(W=>W&&At.classList.remove(W))}Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),To(),a.emit("eventStream:closed",{timestamp:Date.now()})}},At=null;if(We){let c=(Af=(wf=o.features)==null?void 0:wf.eventStream)==null?void 0:Af.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:"");At=C("button",g),At.style.width="28px",At.style.height="28px",At.style.color=Ao.actionIconColor,At.type="button",At.setAttribute("aria-label","Event Stream"),At.title="Event Stream";let b=Ee("activity","18px","currentColor",1.5);b&&At.appendChild(b);let S=Re.clearChatButtonWrapper,W=Re.closeButtonWrapper,F=S||W;F&&F.parentNode===qe?qe.insertBefore(At,F):qe.appendChild(At),At.addEventListener("click",()=>{ge?lo():_o()})}let rn=c=>{var S,W,F;let g=o.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let q=c.querySelector("[data-persona-composer-form]");q!=null&&q.parentNode?q.parentNode.insertBefore(b,q):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let q=C("input");q.type="file",q.accept=((S=g.allowedTypes)!=null?S:Tn).join(","),q.multiple=((W=g.maxFiles)!=null?W:4)>1,q.style.display="none",q.setAttribute("aria-label",(F=g.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(q)}},No=n.find(c=>c.renderComposer);if(No!=null&&No.renderComposer){let c=o.composer,g=No.renderComposer({config:o,defaultRenderer:()=>ns({config:o}).footer,onSubmit:b=>{var q;if(!U||U.isStreaming())return;let S=b.trim(),W=(q=je==null?void 0:je.hasAttachments())!=null?q:!1;if(!S&&!W)return;V();let F;W&&(F=[],F.push(...je.getContentParts()),S&&F.push(Qs(S))),U.sendMessage(S,{contentParts:F}),W&&je.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{de==null||de.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{o.composer={...o.composer,selectedModelId:b},o.agent&&(o.agent={...o.agent,model:b})},onVoiceToggle:((Sf=o.voiceRecognition)==null?void 0:Sf.enabled)===!0?()=>{Tr==null||Tr()}:void 0});g&&(ze.replaceWith(g),ze=g)}let mn=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),S=c.querySelector("[data-persona-composer-submit]"),W=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");g&&(Rt=g),b&&(te=b),S&&(_e=S),W&&(X=W,wt=W.parentElement),F&&(dr=F);let q=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");q&&(Pt=q);let G=c.querySelector(".persona-attachment-button");G&&(ct=G,Ce=G.parentElement),de=c.querySelector('input[type="file"]'),rt=c.querySelector(".persona-attachment-previews");let N=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(lt=N)};rn(ze),mn(ze);let Jr=(Lf=(Tf=o.layout)==null?void 0:Tf.contentMaxWidth)!=null?Lf:H()?(Ef=(kf=(Mf=o.launcher)==null?void 0:Mf.composerBar)==null?void 0:kf.contentMaxWidth)!=null?Ef:"720px":void 0;if(Jr&&(it.style.maxWidth=Jr,it.style.marginLeft="auto",it.style.marginRight="auto",it.style.width="100%"),Jr&&Rt&&!H()&&(Rt.style.maxWidth=Jr,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),Jr&&Pt&&!H()&&(Pt.style.maxWidth=Jr,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Jr&&rt&&!H()&&(rt.style.maxWidth=Jr,rt.style.marginLeft="auto",rt.style.marginRight="auto"),(Pf=o.attachments)!=null&&Pf.enabled&&de&&rt){je=wa.fromConfig(o.attachments),je.setPreviewsContainer(rt),de.addEventListener("change",b=>{let S=b.target;je==null||je.handleFileSelect(S.files),S.value=""});let c=o.attachments.dropOverlay,g=gy(c);K.appendChild(g)}(()=>{var S,W;let c=(W=(S=o.layout)==null?void 0:S.slots)!=null?W:{},g=F=>{switch(F){case"body-top":return K.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return it;case"footer-top":return Pt;case"composer":return Rt;case"footer-bottom":return dr;default:return null}},b=(F,q)=>{var G;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")qe.insertBefore(q,qe.firstChild);else if(F==="header-right")qe.appendChild(q);else{let N=qe.querySelector(".persona-flex-col");N?(G=N.parentNode)==null||G.insertBefore(q,N.nextSibling):qe.appendChild(q)}break;case"body-top":{let N=he.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(q):he.insertBefore(q,he.firstChild);break}case"body-bottom":he.appendChild(q);break;case"footer-top":Pt.replaceWith(q);break;case"footer-bottom":dr.replaceWith(q);break;default:break}};for(let[F,q]of Object.entries(c))if(q)try{let G=q({config:o,defaultContent:()=>g(F)});G&&b(F,G)}catch(G){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,G)}})();let $r=c=>{var q,G;let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let S=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!S)return;let W=S.getAttribute("data-message-id");if(!W)return;let F=b.getAttribute("data-bubble-type");if(F==="reasoning")ss.has(W)?ss.delete(W):ss.add(W),qx(W,S);else if(F==="tool")is.has(W)?is.delete(W):is.add(W),zx(W,S,o);else if(F==="approval"){let N=o.approval!==!1?o.approval:void 0,Se=((q=N==null?void 0:N.detailsDisplay)!=null?q:"collapsed")==="expanded",xe=(G=Gl.get(W))!=null?G:Se;Gl.set(W,!xe),Gx(W,S,o)}Cr.delete(W)};it.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$r(c))}),it.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$r(c))});let Fo=new Map;it.addEventListener("click",c=>{var q;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let S=b.closest("[data-actions-for]");if(!S)return;let W=S.getAttribute("data-actions-for");if(!W)return;let F=b.getAttribute("data-action");if(F==="copy"){let N=U.getMessages().find(Se=>Se.id===W);if(N&&ae.onCopy){let Se=N.content||"";navigator.clipboard.writeText(Se).then(()=>{b.classList.add("persona-message-action-success");let xe=Ee("check",14,"currentColor",2);xe&&(b.innerHTML="",b.appendChild(xe)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let se=Ee("copy",14,"currentColor",2);se&&(b.innerHTML="",b.appendChild(se))},2e3)}).catch(xe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",xe)}),ae.onCopy(N)}}else if(F==="upvote"||F==="downvote"){let N=((q=Fo.get(W))!=null?q:null)===F,Se=F==="upvote"?"thumbs-up":"thumbs-down";if(N){Fo.delete(W),b.classList.remove("persona-message-action-active");let xe=Ee(Se,14,"currentColor",2);xe&&(b.innerHTML="",b.appendChild(xe))}else{let xe=F==="upvote"?"downvote":"upvote",se=S.querySelector(`[data-action="${xe}"]`);if(se){se.classList.remove("persona-message-action-active");let Ze=Ee(xe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ze&&(se.innerHTML="",se.appendChild(Ze))}Fo.set(W,F),b.classList.add("persona-message-action-active");let ke=Ee(Se,14,"currentColor",2);ke&&(ke.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(ke)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Te=U.getMessages().find(ft=>ft.id===W);Te&&ae.onFeedback&&ae.onFeedback({type:F,messageId:Te.id,message:Te})}}}),it.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let S=b.closest(".persona-approval-bubble");if(!S)return;let W=S.getAttribute("data-message-id");if(!W)return;let F=b.getAttribute("data-approval-action");if(!F)return;let q=F==="approve"?"approved":"denied",N=U.getMessages().find(xe=>xe.id===W);if(!(N!=null&&N.approval))return;let Se=S.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?U.resolveWebMcpApproval(W,q):U.resolveApproval(N.approval,q)});let mt=null,co=null,po={artifacts:[],selectedId:null},Or=!1,Wt={current:null};it.addEventListener("click",c=>{var se,ke,Ge,Te,ft;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let S=b.getAttribute("data-download-artifact");if(!S||((Ge=(ke=(se=o.features)==null?void 0:se.artifacts)==null?void 0:ke.onArtifactAction)==null?void 0:Ge.call(ke,{type:"download",artifactId:S}))===!0)return;let F=U.getArtifactById(S),q=F==null?void 0:F.markdown,G=(F==null?void 0:F.title)||"artifact";if(!q){let Ze=b.closest("[data-open-artifact]"),bt=Ze==null?void 0:Ze.closest("[data-message-id]"),vt=bt==null?void 0:bt.getAttribute("data-message-id");if(vt){let Pe=U.getMessages().find(Qe=>Qe.id===vt);if(Pe!=null&&Pe.rawContent)try{let Qe=JSON.parse(Pe.rawContent);q=(Te=Qe==null?void 0:Qe.props)==null?void 0:Te.markdown,G=((ft=Qe==null?void 0:Qe.props)==null?void 0:ft.title)||G}catch{}}}if(!q)return;let N=new Blob([q],{type:"text/markdown"}),Se=URL.createObjectURL(N),xe=document.createElement("a");xe.href=Se,xe.download=`${G}.md`,xe.click(),URL.revokeObjectURL(Se)}),it.addEventListener("click",c=>{var F,q,G;let b=c.target.closest("[data-open-artifact]");if(!b)return;let S=b.getAttribute("data-open-artifact");!S||((G=(q=(F=o.features)==null?void 0:F.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:G.call(q,{type:"open",artifactId:S}))===!0||(c.preventDefault(),c.stopPropagation(),Or=!1,U.selectArtifact(S),eo())}),it.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Vr=Re.composerOverlay,Zr=(c,g,b)=>{var G,N,Se,xe;let S=g.trim();if(!S||!Wt.current)return;let W=(G=c.getAttribute("data-tool-call-id"))!=null?G:"",F=b.source==="free-text";r.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:W,answer:S,answers:b.structured,values:(N=b.values)!=null?N:b.source==="multi"?S.split(", "):[S],isFreeText:F,source:b.source},bubbles:!0,composed:!0})),zn(Vr,W);let q=Wt.current.getMessages().find(se=>{var ke;return((ke=se.toolCall)==null?void 0:ke.id)===W});(Se=q==null?void 0:q.agentMetadata)!=null&&Se.awaitingLocalTool?Wt.current.resolveAskUserQuestion(q,(xe=b.structured)!=null?xe:S):Wt.current.sendMessage(S)},_r=c=>{var W;let g=Wt.current;if(!g)return;let b=(W=c.getAttribute("data-tool-call-id"))!=null?W:"",S=g.getMessages().find(F=>{var q;return((q=F.toolCall)==null?void 0:q.id)===b});S&&g.persistAskUserQuestionProgress(S,{answers:Ki(c,S),currentIndex:jo(c)})},uo=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),fo=c=>{var W,F,q;if(((F=(W=o.features)==null?void 0:W.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let g=jo(c),b=Xa(c);if(g>=b-1)return;let S=(q=Wt.current)==null?void 0:q.getMessages().find(G=>{var N;return((N=G.toolCall)==null?void 0:N.id)===c.getAttribute("data-tool-call-id")});S&&(Xi(c,S,o,g+1),_r(c))};Vr.addEventListener("click",c=>{var F,q,G,N,Se,xe,se,ke,Ge,Te,ft,Ze,bt,vt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let S=b.closest("[data-persona-ask-sheet-for]");if(!S)return;let W=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),W==="dismiss"){let He=(F=S.getAttribute("data-tool-call-id"))!=null?F:"";r.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),zn(Vr,He);let Pe=(q=Wt.current)==null?void 0:q.getMessages().find(Qe=>{var ot;return((ot=Qe.toolCall)==null?void 0:ot.id)===He});(G=Pe==null?void 0:Pe.agentMetadata)!=null&&G.awaitingLocalTool&&((N=Wt.current)==null||N.markAskUserQuestionResolved(Pe),(Se=Wt.current)==null||Se.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(W==="pick"){let He=b.getAttribute("data-option-label");if(!He)return;let Pe=S.getAttribute("data-multi-select")==="true",Qe=qn(S);if(Qe&&Pe){let ot=ha(S)[jo(S)],Ht=new Set(Array.isArray(ot)?ot:[]);Ht.has(He)?Ht.delete(He):Ht.add(He),$n(S,Array.from(Ht)),_r(S);return}if(Qe){$n(S,He),_r(S),fo(S);return}if(Pe){let ot=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",ot?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!ot);let Ht=S.querySelector('[data-ask-user-action="submit-multi"]');Ht&&(Ht.disabled=Nd(S).length===0);return}Zr(S,He,{source:"pick",values:[He]});return}if(W==="submit-multi"){let He=Nd(S);if(He.length===0)return;Zr(S,He.join(", "),{source:"multi",values:He});return}if(W==="open-free-text"){let He=S.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let Pe=He.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(W==="focus-free-text"){let He=S.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(W==="submit-free-text"){let He=S.querySelector('[data-ask-free-text-input="true"]'),Pe=(xe=He==null?void 0:He.value)!=null?xe:"";if(!Pe.trim())return;if(qn(S)){$n(S,Pe.trim()),_r(S),fo(S);return}Zr(S,Pe,{source:"free-text"});return}if(W==="next"||W==="back"){if(!Wt.current)return;let He=(se=S.getAttribute("data-tool-call-id"))!=null?se:"",Pe=Wt.current.getMessages().find(Ne=>{var Fe;return((Fe=Ne.toolCall)==null?void 0:Fe.id)===He});if(!Pe)return;let Qe=S.querySelector('[data-ask-free-text-input="true"]'),ot=(Ge=(ke=Qe==null?void 0:Qe.value)==null?void 0:ke.trim())!=null?Ge:"";if(ot){let Ne=ha(S)[jo(S)];(typeof Ne!="string"||Ne!==ot)&&$n(S,ot)}let Ht=W==="next"?1:-1,D=jo(S)+Ht;Xi(S,Pe,o,D),_r(S);return}if(W==="submit-all"){if(!Wt.current)return;let He=(Te=S.getAttribute("data-tool-call-id"))!=null?Te:"",Pe=Wt.current.getMessages().find(Ne=>{var Fe;return((Fe=Ne.toolCall)==null?void 0:Fe.id)===He});if(!Pe)return;let Qe=S.querySelector('[data-ask-free-text-input="true"]'),ot=(Ze=(ft=Qe==null?void 0:Qe.value)==null?void 0:ft.trim())!=null?Ze:"";ot&&$n(S,ot);let Ht=Ki(S,Pe);Wt.current.persistAskUserQuestionProgress(Pe,{answers:Ht,currentIndex:jo(S)});let D=uo(Ht);Zr(S,D||"(submitted)",{source:"submit-all",structured:Ht});return}if(W==="skip"){if(!Wt.current)return;let He=(bt=S.getAttribute("data-tool-call-id"))!=null?bt:"",Pe=Wt.current.getMessages().find(Fe=>{var we;return((we=Fe.toolCall)==null?void 0:we.id)===He});if(!Pe)return;let Qe=qn(S),ot=jo(S),Ht=Xa(S),D=ot>=Ht-1;if(!Qe){r.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),zn(Vr,He),(vt=Pe.agentMetadata)!=null&&vt.awaitingLocalTool&&(Wt.current.markAskUserQuestionResolved(Pe),Wt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}$n(S,"");let Ne=S.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),D){let Fe=Ki(S,Pe),we=uo(Fe);Zr(S,we||"(skipped)",{source:"submit-all",structured:Fe});return}Xi(S,Pe,o,ot+1),_r(S);return}}),Vr.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let b=c.target;if(!((F=b.matches)!=null&&F.call(b,'[data-ask-free-text-input="true"]')))return;let S=b.closest("[data-persona-ask-sheet-for]");if(!S)return;c.preventDefault();let W=b.value;if(W.trim()){if(qn(S)){$n(S,W.trim()),_r(S),fo(S);return}Zr(S,W,{source:"free-text"})}});let Nr=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=Vr.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let S=Number(c.key),F=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[S-1];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",Nr);let mo=null,$t=null,Fr=null,go=null,on=()=>{};function Uo(){go==null||go(),go=null}let nn=()=>{var q;if(!mo||!$t)return;let c=r.classList.contains("persona-artifact-appearance-seamless"),b=((q=r.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!c||r.classList.contains("persona-artifact-narrow-host")||b){$t.style.removeProperty("position"),$t.style.removeProperty("left"),$t.style.removeProperty("top"),$t.style.removeProperty("bottom"),$t.style.removeProperty("width"),$t.style.removeProperty("z-index");return}let S=mo.firstElementChild;if(!S||S===$t)return;let W=10;$t.style.position="absolute",$t.style.top="0",$t.style.bottom="0",$t.style.width=`${W}px`,$t.style.zIndex="5";let F=S.offsetWidth-W/2;$t.style.left=`${Math.max(0,F)}px`},qo=()=>{},eo=()=>{var b,S,W,F,q;if(!mt||!Go(o))return;Ql(r,o),Yl(r,o),qo();let c=(F=(W=(S=(b=o.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:W.narrowHostMaxWidth)!=null?F:520,g=le.getBoundingClientRect().width||0;r.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),mt.update(po),Or?(mt.setMobileOpen(!1),mt.element.classList.add("persona-hidden"),(q=mt.backdrop)==null||q.classList.add("persona-hidden")):po.artifacts.length>0&&(mt.element.classList.remove("persona-hidden"),mt.setMobileOpen(!0)),on()};if(Go(o)){le.style.position="relative";let c=C("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=C("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(K),mt=ty(o,{onSelect:b=>{var S;return(S=Wt.current)==null?void 0:S.selectArtifact(b)},onDismiss:()=>{Or=!0,eo()}}),mt.element.classList.add("persona-hidden"),mo=g,g.appendChild(c),g.appendChild(mt.element),mt.backdrop&&le.appendChild(mt.backdrop),le.appendChild(g),on=()=>{var S,W,F,q;if(!mo||!mt)return;if(!(((F=(W=(S=o.features)==null?void 0:S.artifacts)==null?void 0:W.layout)==null?void 0:F.resizable)===!0)){Fr==null||Fr(),Fr=null,Uo(),$t&&($t.remove(),$t=null),mt.element.style.removeProperty("width"),mt.element.style.removeProperty("maxWidth");return}if(!$t){let G=C("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");G.setAttribute("role","separator"),G.setAttribute("aria-orientation","vertical"),G.setAttribute("aria-label","Resize artifacts panel"),G.tabIndex=0;let N=r.ownerDocument,Se=(q=N.defaultView)!=null?q:window,xe=se=>{var bt,vt;if(!mt||se.button!==0||r.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;se.preventDefault(),Uo();let ke=se.clientX,Ge=mt.element.getBoundingClientRect().width,Te=(vt=(bt=o.features)==null?void 0:bt.artifacts)==null?void 0:vt.layout,ft=He=>{let Pe=mo.getBoundingClientRect().width,Qe=r.classList.contains("persona-artifact-appearance-seamless"),ot=Qe?0:ay(mo,Se),Ht=Qe?0:G.getBoundingClientRect().width||6,D=Ge-(He.clientX-ke),Ne=sy(D,Pe,ot,Ht,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);mt.element.style.width=`${Ne}px`,mt.element.style.maxWidth="none",nn()},Ze=()=>{N.removeEventListener("pointermove",ft),N.removeEventListener("pointerup",Ze),N.removeEventListener("pointercancel",Ze),go=null;try{G.releasePointerCapture(se.pointerId)}catch{}};go=Ze,N.addEventListener("pointermove",ft),N.addEventListener("pointerup",Ze),N.addEventListener("pointercancel",Ze);try{G.setPointerCapture(se.pointerId)}catch{}};G.addEventListener("pointerdown",xe),$t=G,mo.insertBefore(G,mt.element),Fr=()=>{G.removeEventListener("pointerdown",xe)}}if($t){let G=po.artifacts.length>0&&!Or;$t.classList.toggle("persona-hidden",!G),nn()}},qo=()=>{var Se,xe,se,ke,Ge,Te,ft,Ze,bt,vt,He,Pe,Qe,ot;if(!M||!mt||((xe=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?xe:!1)||Lr(o)&&Bo(o).reveal==="emerge")return;let S=(se=r.ownerDocument.defaultView)!=null?se:window,W=(Ge=(ke=o.launcher)==null?void 0:ke.mobileFullscreen)!=null?Ge:!0,F=(ft=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?ft:640;if(W&&S.innerWidth<=F||!ny(o,M))return;let q=(vt=(bt=(Ze=o.launcher)==null?void 0:Ze.width)!=null?bt:o.launcherWidth)!=null?vt:Wo,G=(ot=(Qe=(Pe=(He=o.features)==null?void 0:He.artifacts)==null?void 0:Pe.layout)==null?void 0:Qe.expandedPanelWidth)!=null?ot:"min(720px, calc(100vw - 24px))";po.artifacts.length>0&&!Or?(le.style.width=G,le.style.maxWidth=G):(le.style.width=q,le.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(co=new ResizeObserver(()=>{eo()}),co.observe(le))}else le.appendChild(K),H()&&nt&&(Re.peekBanner&&nt.appendChild(Re.peekBanner),nt.appendChild(ze));r.appendChild(De),nt&&r.appendChild(nt);let to=()=>{var Ne,Fe,we,Qt,Kt,ir,Bt,ar,Po,wr,st,Ut,kr,Vo,Ro,ta,ra,Fa,Ua,ur,oa,On,_n,yn,na,Yo,pt,Ir;if(H()){le.style.width="100%",le.style.maxWidth="100%";let Zt=(Fe=(Ne=o.launcher)==null?void 0:Ne.composerBar)!=null?Fe:{},Yt=De.dataset.state==="expanded",Et=(we=Zt.expandedSize)!=null?we:"anchored";if(!(Yt&&Et!=="fullscreen")){K.style.background="",K.style.border="",K.style.borderRadius="",K.style.overflow="",K.style.boxShadow="";return}let _t=(Kt=(Qt=o.theme)==null?void 0:Qt.components)==null?void 0:Kt.panel,oo=rs(o),ho=(yo,aa)=>{var Es;return yo==null||yo===""?aa:(Es=es(oo,yo))!=null?Es:yo},dn="1px solid var(--persona-border)",qr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",xo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";K.style.background="var(--persona-surface, #ffffff)",K.style.border=ho(_t==null?void 0:_t.border,dn),K.style.borderRadius=ho(_t==null?void 0:_t.borderRadius,xo),K.style.boxShadow=ho(_t==null?void 0:_t.shadow,qr),K.style.overflow="hidden";return}let c=Lr(o),g=(Bt=(ir=o.launcher)==null?void 0:ir.sidebarMode)!=null?Bt:!1,b=c||g||((Po=(ar=o.launcher)==null?void 0:ar.fullHeight)!=null?Po:!1),S=((wr=o.launcher)==null?void 0:wr.enabled)===!1,W=(Ut=(st=o.theme)==null?void 0:st.components)==null?void 0:Ut.panel,F=rs(o),q=(Zt,Yt)=>{var Et;return Zt==null||Zt===""?Yt:(Et=es(F,Zt))!=null?Et:Zt},G=(kr=r.ownerDocument.defaultView)!=null?kr:window,N=(Ro=(Vo=o.launcher)==null?void 0:Vo.mobileFullscreen)!=null?Ro:!0,Se=(ra=(ta=o.launcher)==null?void 0:ta.mobileBreakpoint)!=null?ra:640,xe=G.innerWidth<=Se,se=N&&xe&&M,ke=(Ua=(Fa=o.launcher)==null?void 0:Fa.position)!=null?Ua:"bottom-left",Ge=ke==="bottom-left"||ke==="top-left",Te=(oa=(ur=o.launcher)==null?void 0:ur.zIndex)!=null?oa:so,ft=g||se?"none":"1px solid var(--persona-border)",Ze=se?"none":g?Ge?"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&&!se&&(Ze="none",ft="none");let bt=g||se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",vt=q(W==null?void 0:W.border,ft),He=q(W==null?void 0:W.shadow,Ze),Pe=q(W==null?void 0:W.borderRadius,bt),Qe=he.scrollTop;r.style.cssText="",De.style.cssText="",le.style.cssText="",K.style.cssText="",he.style.cssText="",ze.style.cssText="";let ot=()=>{var Yt;if(Qe<=0)return;((Yt=he.ownerDocument.defaultView)!=null?Yt:window).requestAnimationFrame(()=>{if(he.scrollTop===Qe)return;let Et=he.scrollHeight-he.clientHeight;Et<=0||(he.scrollTop=Math.min(Qe,Et))})};if(se){De.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"),De.style.cssText=`
|
|
33
|
+
`,A.addEventListener("click",()=>{g=b,E.forEach((H,W)=>{let k=W<b;H.classList.toggle("selected",k),H.setAttribute("aria-checked",W===b-1?"true":"false")})}),E.push(A),T.appendChild(A)}p.appendChild(T);let M=null;if(c){let b=document.createElement("div");b.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),b.appendChild(M),p.appendChild(b)}let P=document.createElement("div");P.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),u.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=s,w.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let b=(M==null?void 0:M.value.trim())||void 0;await t(g,b),u.remove()}catch(b){w.disabled=!1,w.textContent=s,console.error("[CSAT Feedback] Failed to submit:",b)}}),P.appendChild(y),P.appendChild(w),p.appendChild(P),u.appendChild(p),u}function Pl(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,lowLabel:d="Not likely",highLabel:u="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let p=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,x.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=n,x.appendChild(T),m.appendChild(x);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 M=document.createElement("div");M.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=d;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=u,M.appendChild(P),M.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-numbers";let b=[];for(let N=0;N<=10;N++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${N} out of 10`),q.textContent=String(N),q.dataset.rating=String(N),N<=6?q.classList.add("persona-feedback-detractor"):N<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{p=N,b.forEach((Z,me)=>{Z.classList.toggle("selected",me===N),Z.setAttribute("aria-checked",me===N?"true":"false")})}),b.push(q),w.appendChild(q)}E.appendChild(M),E.appendChild(w),m.appendChild(E);let A=null;if(c){let N=document.createElement("div");N.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),N.appendChild(A),m.appendChild(N)}let H=document.createElement("div");H.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{r==null||r(),g.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=s,k.addEventListener("click",async()=>{if(p===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let N=(A==null?void 0:A.value.trim())||void 0;await t(p,N),g.remove()}catch(N){k.disabled=!1,k.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),H.appendChild(W),H.appendChild(k),m.appendChild(H),g.appendChild(m),g}var Ya="persona-chat-history",Pv=30*1e3,Rv={"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 Iv(e){var o,n,a;if(!e)return[];let t=[],r=Array.from((o=e.items)!=null?o:[]);for(let s of r){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let c=(n=Rv[i.type])!=null?n:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${c}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&t.push(s);return t}function Rl(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 Wv(e){var t,r,o,n,a,s,i,c,d;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:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(d=e.clearOnChatClear)!=null?d:!0}:null}function Hv(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Ip=e=>!e||typeof e!="object"?{}:{...e},ox=e=>e.map(t=>({...t,streaming:!1})),nx=(e,t,r)=>{let o=e!=null&&e.markdown?Zn(e.markdown):null,n=Wa(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(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."),a=>{var d,u,g;let s=(d=a.text)!=null?d:"",i=(u=a.message.rawContent)!=null?u:null;if(t){let p=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});p!==null&&(s=p.text,p.persist||(a.message.__skipPersist=!0),p.resubmit&&!a.streaming&&r&&r())}let c;return e!=null&&e.postprocessMessage?c=e.postprocessMessage({...a,text:s,raw:(g=i!=null?i:a.text)!=null?g:""}):o?c=o(s):c=qo(s),n?n(c):c}};function ax(e){var i,c,d,u;let t=S("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 r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(d=e==null?void 0:e.iconColor)!=null?d:"rgba(59, 130, 246, 0.6)",a=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=ve(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let g=S("span","persona-drop-overlay-label");g.textContent=e.label,t.appendChild(g)}return t}var Il=(e,t,r)=>{var fu,mu,gu,hu,xu,yu,bu,vu,Cu,wu,Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Ru,Iu,Wu,Hu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,$u,zu,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf,df;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 o=Ji(t),n=zs.getForInstance(o.plugins);o.components&&dn.registerAll(o.components);let a=Yh(),i=o.persistState===!1?null:(fu=o.storageAdapter)!=null?fu:Al(),c={},d=null,u=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:v}=f;return v&&(u=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return g(h)});else{let f=l!=null?l:{messages:[],metadata:{}},h=g(f);h.metadata&&(c=Ip(h.metadata)),(mu=h.messages)!=null&&mu.length&&(o={...o,initialMessages:h.messages}),(gu=h.artifacts)!=null&&gu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(hu=h.selectedArtifactId)!=null?hu:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});(xu=l.messages)!=null&&xu.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>c,m=l=>{var h;c=(h=l({...c}))!=null?h:{},wa()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[js],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick],T=Gs({parsers:x,handlers:C,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let E=(bu=(yu=o.launcher)==null?void 0:yu.enabled)!=null?bu:!0,M=(Cu=(vu=o.launcher)==null?void 0:vu.autoExpand)!=null?Cu:!1,P=(wu=o.autoFocusInput)!=null?wu:!1,y=M,w=E,b=(Au=(Su=o.layout)==null?void 0:Su.header)==null?void 0:Au.layout,A=!1,H=()=>Dn(o),W=()=>E||H(),k=H()?!1:E?M:!0,N=!1,q=null,Z=()=>{N=!0,q&&clearTimeout(q),q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},me=nx(o,T,Z),Ke=(Tu=(Mu=o.features)==null?void 0:Mu.showReasoning)!=null?Tu:!0,Ce=(ku=(Eu=o.features)==null?void 0:Eu.showToolCalls)!=null?ku:!0,Ie=(Pu=(Lu=o.features)==null?void 0:Lu.showEventStreamToggle)!=null?Pu:!1,Ue=(Iu=(Ru=o.features)==null?void 0:Ru.scrollToBottom)!=null?Iu:{},Te=(Hu=(Wu=o.features)==null?void 0:Wu.scrollBehavior)!=null?Hu:{},de=`${(Du=typeof o.persistState=="object"?(Bu=o.persistState)==null?void 0:Bu.keyPrefix:void 0)!=null?Du:"persona-"}event-stream`,J=Ie?new Vs(de):null,le=(Ou=(Nu=(Fu=o.features)==null?void 0:Fu.eventStream)==null?void 0:Nu.maxEvents)!=null?Ou:2e3,ge=Ie?new qs(le,J):null,ue=Ie?new $s:null,G=null,ce=!1,Be=null,ne=0;J==null||J.open().then(()=>ge==null?void 0:ge.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={onCopy:l=>{var f,h;a.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,l)},onFeedback:l=>{var f,h;a.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,l)}},ie=(_u=o.statusIndicator)!=null?_u:{},vt=l=>{var f,h,v,R;return l==="idle"?(f=ie.idleText)!=null?f:kr.idle:l==="connecting"?(h=ie.connectingText)!=null?h:kr.connecting:l==="connected"?(v=ie.connectedText)!=null?v:kr.connected:l==="error"?(R=ie.errorText)!=null?R:kr.error:kr[l]};function Lt(l,f,h,v){if(v==="idle"&&h.idleLink){l.textContent="";let R=document.createElement("a");R.href=h.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=f,R.style.color="inherit",R.style.textDecoration="none",l.appendChild(R)}else l.textContent=f}let gt=kh({config:o,showClose:W()}),{wrapper:_e,panel:be,pillRoot:Ze}=gt.shell,Y=gt.panelElements,{container:pe,body:Me,messagesWrapper:Je,suggestions:Ge,textarea:ke,sendButton:je,sendButtonWrapper:Cr,composerForm:Wt,statusText:ur,introTitle:Eo,introSubtitle:V,closeButton:j,iconHolder:he,headerTitle:Xe,headerSubtitle:et,header:qe,footer:Ne,actionsRow:Pt,leftActions:Gt,rightActions:Jt}=Y,Pr=Y.setSendButtonMode,z=Y.micButton,Ht=Y.micButtonWrapper,oe=Y.attachmentButton,we=Y.attachmentButtonWrapper,De=Y.attachmentInput,At=Y.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Me.classList.add("persona-relative");let ar=12,sr=()=>{var l;return(l=Ue.label)!=null?l:""},wr=()=>{var l;return(l=Ue.iconName)!=null?l:"arrow-down"},Ft=()=>Ue.enabled!==!1,ot=()=>{var l;return(l=Te.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},lt=S("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");lt.type="button",lt.style.display="none",lt.setAttribute("data-persona-scroll-to-bottom","true");let Yt=S("span","persona-flex persona-items-center"),so=S("span",""),Rr=S("span","");Rr.setAttribute("data-persona-scroll-to-bottom-count",""),Rr.style.display="none",lt.append(Yt,so,Rr),pe.appendChild(lt);let ir=S("div","persona-stream-anchor-spacer");ir.setAttribute("aria-hidden","true"),ir.setAttribute("data-persona-anchor-spacer",""),ir.style.flexShrink="0",ir.style.pointerEvents="none",ir.style.height="0px",Me.appendChild(ir);let Ur=()=>{let f=Ne.style.display==="none"?0:Ne.offsetHeight;lt.style.bottom=`${f+ar}px`};Ur();let ko=()=>{let l=!!sr();lt.setAttribute("aria-label",sr()||"Jump to latest"),lt.title=sr(),lt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Yt.innerHTML="";let f=ve(wr(),"14px","currentColor",2);f?(Yt.appendChild(f),Yt.style.display=""):Yt.style.display="none",so.textContent=sr(),so.style.display=l?"":"none"};ko();let yt=null,jr=null,Lo=n.find(l=>l.renderHeader);if(Lo!=null&&Lo.renderHeader){let l=Lo.renderHeader({config:o,defaultRenderer:()=>{let f=ln({config:o,showClose:W()});return pa(pe,f,o),f.header},onClose:()=>I(!1,"user")});if(l){let f=pe.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),qe=l,gt.header.element=l)}}let zo=()=>{var f,h,v,R;if(!ge)return;if(ce=!0,!G&&ge&&(G=qh({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>yo(),config:o,plugins:n,getThroughput:()=>{var F;return(F=ue==null?void 0:ue.getMetric())!=null?F:{status:"idle"}}})),G&&(Me.style.display="none",(f=Ne.parentNode)==null||f.insertBefore(G.element,Ne),G.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${_r.actionIconColor}`;let F=(R=(v=(h=o.features)==null?void 0:h.eventStream)==null?void 0:v.classNames)==null?void 0:R.toggleButtonActive;F&&F.split(/\s+/).forEach($=>$&&ht.classList.add($))}let l=()=>{if(!ce)return;let F=Date.now();F-ne>=200&&(G==null||G.update(),ne=F),Be=requestAnimationFrame(l)};ne=0,Be=requestAnimationFrame(l),$r(),a.emit("eventStream:opened",{timestamp:Date.now()})},yo=()=>{var l,f,h;if(ce){if(ce=!1,G&&G.element.remove(),Me.style.display="",ht){ht.style.boxShadow="";let v=(h=(f=(l=o.features)==null?void 0:l.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;v&&v.split(/\s+/).forEach(R=>R&&ht.classList.remove(R))}Be!==null&&(cancelAnimationFrame(Be),Be=null),$r(),a.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Ie){let l=(qu=(Uu=o.features)==null?void 0:Uu.eventStream)==null?void 0:qu.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"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ht=S("button",f),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=ve("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let v=Y.clearChatButtonWrapper,R=Y.closeButtonWrapper,F=v||R;F&&F.parentNode===qe?qe.insertBefore(ht,F):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}let Nn=l=>{var R,F,$,O,D;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=(R=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?R:l.querySelector(".persona-attachment-previews");if(!h){h=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ae=l.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):l.insertBefore(h,l.firstChild)}if(!((F=l.querySelector("[data-persona-composer-attachment-input]"))!=null?F:l.querySelector('input[type="file"]'))){let ae=S("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=(($=f.allowedTypes)!=null?$:an).join(","),ae.multiple=((O=f.maxFiles)!=null?O:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ae)}},Po=n.find(l=>l.renderComposer);if(Po!=null&&Po.renderComposer){let l=o.composer,f=Po.renderComposer({config:o,defaultRenderer:()=>ja({config:o}).footer,onSubmit:h=>{var $;if(!_||_.isStreaming())return;let v=h.trim(),R=($=yt==null?void 0:yt.hasAttachments())!=null?$:!1;if(!v&&!R)return;tt();let F;R&&(F=[],F.push(...yt.getContentParts()),v&&F.push(ks(v))),_.sendMessage(v,{contentParts:F}),R&&yt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{De==null||De.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Vu=o.voiceRecognition)==null?void 0:Vu.enabled)===!0?()=>{jr==null||jr()}:void 0});f&&(gt.replaceComposer(f),Ne=gt.composer.footer)}let On=l=>{let f=(...se)=>{for(let Q of se){let ye=l.querySelector(Q);if(ye)return ye}return null},h=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),R=l.querySelector("[data-persona-composer-submit]"),F=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");h&&(Wt=h),v&&(ke=v),R&&(je=R),F&&(z=F,Ht=F.parentElement),$&&(ur=$);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ge=O);let D=f("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(oe=D,we=D.parentElement),De=f("[data-persona-composer-attachment-input]",'input[type="file"]'),At=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Pt=ae)};Nn(Ne),On(Ne);let qr=(Ku=($u=o.layout)==null?void 0:$u.contentMaxWidth)!=null?Ku:H()?(Gu=(ju=(zu=o.launcher)==null?void 0:zu.composerBar)==null?void 0:ju.contentMaxWidth)!=null?Gu:"720px":void 0;if(qr&&(Je.style.maxWidth=qr,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%"),qr&&Wt&&!H()&&(Wt.style.maxWidth=qr,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),qr&&Ge&&!H()&&(Ge.style.maxWidth=qr,Ge.style.marginLeft="auto",Ge.style.marginRight="auto"),qr&&At&&!H()&&(At.style.maxWidth=qr,At.style.marginLeft="auto",At.style.marginRight="auto"),(Xu=o.attachments)!=null&&Xu.enabled&&De&&At){yt=la.fromConfig(o.attachments),yt.setPreviewsContainer(At),De.addEventListener("change",h=>{let v=h.target;yt==null||yt.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,f=ax(l);pe.appendChild(f)}(()=>{var v,R;let l=(R=(v=o.layout)==null?void 0:v.slots)!=null?R:{},f=F=>{switch(F){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Je;case"footer-top":return Ge;case"composer":return Wt;case"footer-bottom":return ur;default:return null}},h=(F,$)=>{var O;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")qe.insertBefore($,qe.firstChild);else if(F==="header-right")qe.appendChild($);else{let D=qe.querySelector(".persona-flex-col");D?(O=D.parentNode)==null||O.insertBefore($,D.nextSibling):qe.appendChild($)}break;case"body-top":{let D=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith($):Me.insertBefore($,Me.firstChild);break}case"body-bottom":Me.appendChild($);break;case"footer-top":Ge.replaceWith($);break;case"footer-bottom":ur.replaceWith($);break;default:break}};for(let[F,$]of Object.entries(l))if($)try{let O=$({config:o,defaultContent:()=>f(F)});O&&h(F,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,O)}})();let cn=l=>{var $,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let v=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")Ka.has(R)?Ka.delete(R):Ka.add(R),Ih(R,v);else if(F==="tool")Xa.has(R)?Xa.delete(R):Xa.add(R),Wh(R,v,o);else if(F==="approval"){let D=o.approval!==!1?o.approval:void 0,ae=(($=D==null?void 0:D.detailsDisplay)!=null?$:"collapsed")==="expanded",se=(O=bl.get(R))!=null?O:ae;bl.set(R,!se),Fh(R,v,o)}Bo.delete(R)};Je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))}),Je.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))});let jo=new Map,pn=null,un="idle",_n={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Un=(l,f)=>{let{icon:h,label:v}=_n[f];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let R=ve(h,14,"currentColor",2);R&&(l.innerHTML="",l.appendChild(R))},fn=()=>{Je.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{var F;let h=f.closest("[data-actions-for]"),v=(F=h==null?void 0:h.getAttribute("data-actions-for"))!=null?F:null;Un(f,v&&v===pn?un:"idle")})};Je.addEventListener("click",l=>{var $;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest("[data-actions-for]");if(!v)return;let R=v.getAttribute("data-actions-for");if(!R)return;let F=h.getAttribute("data-action");if(F==="copy"){let D=_.getMessages().find(ae=>ae.id===R);if(D&&ee.onCopy){let ae=D.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let se=ve("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=ve("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),ee.onCopy(D)}}else if(F==="read-aloud")_.toggleReadAloud(R);else if(F==="upvote"||F==="downvote"){let D=(($=jo.get(R))!=null?$:null)===F,ae=F==="upvote"?"thumbs-up":"thumbs-down";if(D){jo.delete(R),h.classList.remove("persona-message-action-active");let se=ve(ae,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=F==="upvote"?"downvote":"upvote",Q=v.querySelector(`[data-action="${se}"]`);if(Q){Q.classList.remove("persona-message-action-active");let $e=ve(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Q.innerHTML="",Q.appendChild($e))}jo.set(R,F),h.classList.add("persona-message-action-active");let ye=ve(ae,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=_.getMessages().find(nt=>nt.id===R);Se&&ee.onFeedback&&ee.onFeedback({type:F,messageId:Se.id,message:Se})}}}),Je.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest(".persona-approval-bubble");if(!v)return;let R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-approval-action");if(!F)return;let $=F==="approve"?"approved":"denied",D=_.getMessages().find(se=>se.id===R);if(!(D!=null&&D.approval))return;let ae=v.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Q=>{Q.disabled=!0,Q.style.opacity="0.5",Q.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?_.resolveWebMcpApproval(R,$):_.resolveApproval(D.approval,$)});let Ct=null,Gr=null,Kr={artifacts:[],selectedId:null},Ir=!1,Mt={current:null};Je.addEventListener("click",l=>{var Q,ye,He,Se,nt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.getAttribute("data-download-artifact");if(!v||((He=(ye=(Q=o.features)==null?void 0:Q.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:He.call(ye,{type:"download",artifactId:v}))===!0)return;let F=_.getArtifactById(v),$=F==null?void 0:F.markdown,O=(F==null?void 0:F.title)||"artifact";if(!$){let $e=h.closest("[data-open-artifact]"),ut=$e==null?void 0:$e.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Ee=_.getMessages().find(ze=>ze.id===st);if(Ee!=null&&Ee.rawContent)try{let ze=JSON.parse(Ee.rawContent);$=(Se=ze==null?void 0:ze.props)==null?void 0:Se.markdown,O=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||O}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),ae=URL.createObjectURL(D),se=document.createElement("a");se.href=ae,se.download=`${O}.md`,se.click(),URL.revokeObjectURL(ae)}),Je.addEventListener("click",l=>{var F,$,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let v=h.getAttribute("data-open-artifact");!v||((O=($=(F=o.features)==null?void 0:F.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:O.call($,{type:"open",artifactId:v}))===!0||(l.preventDefault(),l.stopPropagation(),Ir=!1,_.selectArtifact(v),Jr())}),Je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;f.hasAttribute("data-open-artifact")&&(l.preventDefault(),f.click())});let io=Y.composerOverlay,lo=(l,f,h)=>{var O,D,ae,se;let v=f.trim();if(!v||!Mt.current)return;let R=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:v,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?v.split(", "):[v],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),Ln(io,R);let $=Mt.current.getMessages().find(Q=>{var ye;return((ye=Q.toolCall)==null?void 0:ye.id)===R});(ae=$==null?void 0:$.agentMetadata)!=null&&ae.awaitingLocalTool?Mt.current.resolveAskUserQuestion($,(se=h.structured)!=null?se:v):Mt.current.sendMessage(v)},Xr=l=>{var R;let f=Mt.current;if(!f)return;let h=(R=l.getAttribute("data-tool-call-id"))!=null?R:"",v=f.getMessages().find(F=>{var $;return(($=F.toolCall)==null?void 0:$.id)===h});v&&f.persistAskUserQuestionProgress(v,{answers:Ci(l,v),currentIndex:ho(l)})},mn=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Go=l=>{var R,F,$;if(((F=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let f=ho(l),h=Da(l);if(f>=h-1)return;let v=($=Mt.current)==null?void 0:$.getMessages().find(O=>{var D;return((D=O.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});v&&(wi(l,v,o,f+1),Xr(l))};io.addEventListener("click",l=>{var F,$,O,D,ae,se,Q,ye,He,Se,nt,$e,ut,st;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;let R=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),R==="dismiss"){let Le=(F=v.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le);let Ee=($=Mt.current)==null?void 0:$.getMessages().find(ze=>{var Qe;return((Qe=ze.toolCall)==null?void 0:Qe.id)===Le});(O=Ee==null?void 0:Ee.agentMetadata)!=null&&O.awaitingLocalTool&&((D=Mt.current)==null||D.markAskUserQuestionResolved(Ee),(ae=Mt.current)==null||ae.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(R==="pick"){let Le=h.getAttribute("data-option-label");if(!Le)return;let Ee=v.getAttribute("data-multi-select")==="true",ze=kn(v);if(ze&&Ee){let Qe=ta(v)[ho(v)],xt=new Set(Array.isArray(Qe)?Qe:[]);xt.has(Le)?xt.delete(Le):xt.add(Le),Pn(v,Array.from(xt)),Xr(v);return}if(ze){Pn(v,Le),Xr(v),Go(v);return}if(Ee){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let xt=v.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Jl(v).length===0);return}lo(v,Le,{source:"pick",values:[Le]});return}if(R==="submit-multi"){let Le=Jl(v);if(Le.length===0)return;lo(v,Le.join(", "),{source:"multi",values:Le});return}if(R==="open-free-text"){let Le=v.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let Ee=Le.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(R==="focus-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(R==="submit-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]'),Ee=(se=Le==null?void 0:Le.value)!=null?se:"";if(!Ee.trim())return;if(kn(v)){Pn(v,Ee.trim()),Xr(v),Go(v);return}lo(v,Ee,{source:"free-text"});return}if(R==="next"||R==="back"){if(!Mt.current)return;let Le=(Q=v.getAttribute("data-tool-call-id"))!=null?Q:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=(He=(ye=ze==null?void 0:ze.value)==null?void 0:ye.trim())!=null?He:"";if(Qe){let Re=ta(v)[ho(v)];(typeof Re!="string"||Re!==Qe)&&Pn(v,Qe)}let xt=R==="next"?1:-1,B=ho(v)+xt;wi(v,Ee,o,B),Xr(v);return}if(R==="submit-all"){if(!Mt.current)return;let Le=(Se=v.getAttribute("data-tool-call-id"))!=null?Se:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=($e=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?$e:"";Qe&&Pn(v,Qe);let xt=Ci(v,Ee);Mt.current.persistAskUserQuestionProgress(Ee,{answers:xt,currentIndex:ho(v)});let B=mn(xt);lo(v,B||"(submitted)",{source:"submit-all",structured:xt});return}if(R==="skip"){if(!Mt.current)return;let Le=(ut=v.getAttribute("data-tool-call-id"))!=null?ut:"",Ee=Mt.current.getMessages().find(Pe=>{var fe;return((fe=Pe.toolCall)==null?void 0:fe.id)===Le});if(!Ee)return;let ze=kn(v),Qe=ho(v),xt=Da(v),B=Qe>=xt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le),(st=Ee.agentMetadata)!=null&&st.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Ee),Mt.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}Pn(v,"");let Re=v.querySelector('[data-ask-free-text-input="true"]');if(Re&&(Re.value=""),B){let Pe=Ci(v,Ee),fe=mn(Pe);lo(v,fe||"(skipped)",{source:"submit-all",structured:Pe});return}wi(v,Ee,o,Qe+1),Xr(v);return}}),io.addEventListener("keydown",l=>{var F;if(l.key!=="Enter")return;let h=l.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let R=h.value;if(R.trim()){if(kn(v)){Pn(v,R.trim()),Xr(v),Go(v);return}lo(v,R,{source:"free-text"})}});let gn=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=io.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),F=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];F&&(l.preventDefault(),F.click())};document.addEventListener("keydown",gn);let Qr=null,Nt=null,Wr=null,co=null,hn=()=>{};function Ko(){co==null||co(),co=null}let xn=()=>{var $;if(!Qr||!Nt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Nt.style.removeProperty("position"),Nt.style.removeProperty("left"),Nt.style.removeProperty("top"),Nt.style.removeProperty("bottom"),Nt.style.removeProperty("width"),Nt.style.removeProperty("z-index");return}let v=Qr.firstElementChild;if(!v||v===Nt)return;let R=10;Nt.style.position="absolute",Nt.style.top="0",Nt.style.bottom="0",Nt.style.width=`${R}px`,Nt.style.zIndex="5";let F=v.offsetWidth-R/2;Nt.style.left=`${Math.max(0,F)}px`},Ro=()=>{},Jr=()=>{var h,v,R,F,$;if(!Ct||!xo(o))return;wl(e,o),Sl(e,o),Ro();let l=(F=(R=(v=(h=o.features)==null?void 0:h.artifacts)==null?void 0:v.layout)==null?void 0:R.narrowHostMaxWidth)!=null?F:520,f=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l),Ct.update(Kr),Ir?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),($=Ct.backdrop)==null||$.classList.add("persona-hidden")):Kr.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),hn()};if(xo(o)){be.style.position="relative";let l=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(pe),Ct=zh(o,{onSelect:h=>{var v;return(v=Mt.current)==null?void 0:v.selectArtifact(h)},onDismiss:()=>{Ir=!0,Jr()}}),Ct.element.classList.add("persona-hidden"),Qr=f,f.appendChild(l),f.appendChild(Ct.element),Ct.backdrop&&be.appendChild(Ct.backdrop),be.appendChild(f),hn=()=>{var v,R,F,$;if(!Qr||!Ct)return;if(!(((F=(R=(v=o.features)==null?void 0:v.artifacts)==null?void 0:R.layout)==null?void 0:F.resizable)===!0)){Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Nt){let O=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let D=e.ownerDocument,ae=($=D.defaultView)!=null?$:window,se=Q=>{var ut,st;if(!Ct||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Q.preventDefault(),Ko();let ye=Q.clientX,He=Ct.element.getBoundingClientRect().width,Se=(st=(ut=o.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,nt=Le=>{let Ee=Qr.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Qe=ze?0:Xh(Qr,ae),xt=ze?0:O.getBoundingClientRect().width||6,B=He-(Le.clientX-ye),Re=Qh(B,Ee,Qe,xt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);Ct.element.style.width=`${Re}px`,Ct.element.style.maxWidth="none",xn()},$e=()=>{D.removeEventListener("pointermove",nt),D.removeEventListener("pointerup",$e),D.removeEventListener("pointercancel",$e),co=null;try{O.releasePointerCapture(Q.pointerId)}catch{}};co=$e,D.addEventListener("pointermove",nt),D.addEventListener("pointerup",$e),D.addEventListener("pointercancel",$e);try{O.setPointerCapture(Q.pointerId)}catch{}};O.addEventListener("pointerdown",se),Nt=O,Qr.insertBefore(O,Ct.element),Wr=()=>{O.removeEventListener("pointerdown",se)}}if(Nt){let O=Kr.artifacts.length>0&&!Ir;Nt.classList.toggle("persona-hidden",!O),xn()}},Ro=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe;if(!E||!Ct||((se=(ae=o.launcher)==null?void 0:ae.sidebarMode)!=null?se:!1)||pr(o)&&no(o).reveal==="emerge")return;let v=(Q=e.ownerDocument.defaultView)!=null?Q:window,R=(He=(ye=o.launcher)==null?void 0:ye.mobileFullscreen)!=null?He:!0,F=(nt=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?nt:640;if(R&&v.innerWidth<=F||!Kh(o,E))return;let $=(st=(ut=($e=o.launcher)==null?void 0:$e.width)!=null?ut:o.launcherWidth)!=null?st:oo,O=(Qe=(ze=(Ee=(Le=o.features)==null?void 0:Le.artifacts)==null?void 0:Ee.layout)==null?void 0:ze.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Kr.artifacts.length>0&&!Ir?(be.style.width=O,be.style.maxWidth=O):(be.style.width=$,be.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Gr=new ResizeObserver(()=>{Jr()}),Gr.observe(be))}else be.appendChild(pe),H()&&Ze&&(Y.peekBanner&&Ze.appendChild(Y.peekBanner),Ze.appendChild(Ne));e.appendChild(_e),Ze&&e.appendChild(Ze);let xe=()=>{var Re,Pe,fe,Ut,Ot,Kt,bt,zt,eo,or,Ye,Rt,cr,go,to,jn,Gn,ka,La,Xt,Kn,Mn,Tn,en,Xn,wo,rt,gr;if(H()){be.style.width="100%",be.style.maxWidth="100%";let Vt=(Pe=(Re=o.launcher)==null?void 0:Re.composerBar)!=null?Pe:{},qt=_e.dataset.state==="expanded",ft=(fe=Vt.expandedSize)!=null?fe:"anchored";if(!(qt&&ft!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let St=(Ot=(Ut=o.theme)==null?void 0:Ut.components)==null?void 0:Ot.panel,Tr=$a(o),Br=(Fr,Qn)=>{var gs;return Fr==null||Fr===""?Qn:(gs=qa(Tr,Fr))!=null?gs:Fr},Uo="1px solid var(--persona-border)",vr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Dr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Br(St==null?void 0:St.border,Uo),pe.style.borderRadius=Br(St==null?void 0:St.borderRadius,Dr),pe.style.boxShadow=Br(St==null?void 0:St.shadow,vr),pe.style.overflow="hidden";return}let l=pr(o),f=(bt=(Kt=o.launcher)==null?void 0:Kt.sidebarMode)!=null?bt:!1,h=l||f||((eo=(zt=o.launcher)==null?void 0:zt.fullHeight)!=null?eo:!1),v=((or=o.launcher)==null?void 0:or.enabled)===!1,R=(Rt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Rt.panel,F=$a(o),$=(Vt,qt)=>{var ft;return Vt==null||Vt===""?qt:(ft=qa(F,Vt))!=null?ft:Vt},O=(cr=e.ownerDocument.defaultView)!=null?cr:window,D=(to=(go=o.launcher)==null?void 0:go.mobileFullscreen)!=null?to:!0,ae=(Gn=(jn=o.launcher)==null?void 0:jn.mobileBreakpoint)!=null?Gn:640,se=O.innerWidth<=ae,Q=D&&se&&E,ye=(La=(ka=o.launcher)==null?void 0:ka.position)!=null?La:"bottom-left",He=ye==="bottom-left"||ye==="top-left",Se=(Kn=(Xt=o.launcher)==null?void 0:Xt.zIndex)!=null?Kn:Lr,nt=f||Q?"none":"1px solid var(--persona-border)",$e=Q?"none":f?He?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Q&&($e="none",nt="none");let ut=f||Q?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=$(R==null?void 0:R.border,nt),Le=$(R==null?void 0:R.shadow,$e),Ee=$(R==null?void 0:R.borderRadius,ut),ze=Me.scrollTop;e.style.cssText="",_e.style.cssText="",be.style.cssText="",pe.style.cssText="",Me.style.cssText="",Ne.style.cssText="";let Qe=()=>{var qt;if(ze<=0)return;((qt=Me.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Me.scrollTop===ze)return;let ft=Me.scrollHeight-Me.clientHeight;ft<=0||(Me.scrollTop=Math.min(ze,ft))})};if(Q){_e.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"),_e.style.cssText=`
|
|
79
34
|
position: fixed !important;
|
|
80
35
|
inset: 0 !important;
|
|
81
36
|
width: 100% !important;
|
|
@@ -85,9 +40,9 @@ _Details: ${t.message}_`:o}var Zs=r=>({isError:!0,content:[{type:"text",text:r}]
|
|
|
85
40
|
padding: 0 !important;
|
|
86
41
|
display: flex !important;
|
|
87
42
|
flex-direction: column !important;
|
|
88
|
-
z-index: ${
|
|
43
|
+
z-index: ${Se} !important;
|
|
89
44
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
90
|
-
`,
|
|
45
|
+
`,be.style.cssText=`
|
|
91
46
|
position: relative !important;
|
|
92
47
|
display: flex !important;
|
|
93
48
|
flex-direction: column !important;
|
|
@@ -100,7 +55,7 @@ _Details: ${t.message}_`:o}var Zs=r=>({isError:!0,content:[{type:"text",text:r}]
|
|
|
100
55
|
padding: 0 !important;
|
|
101
56
|
box-shadow: none !important;
|
|
102
57
|
border-radius: 0 !important;
|
|
103
|
-
`,
|
|
58
|
+
`,pe.style.cssText=`
|
|
104
59
|
display: flex !important;
|
|
105
60
|
flex-direction: column !important;
|
|
106
61
|
flex: 1 1 0% !important;
|
|
@@ -111,20 +66,20 @@ _Details: ${t.message}_`:o}var Zs=r=>({isError:!0,content:[{type:"text",text:r}]
|
|
|
111
66
|
overflow: hidden !important;
|
|
112
67
|
border-radius: 0 !important;
|
|
113
68
|
border: none !important;
|
|
114
|
-
`,
|
|
69
|
+
`,Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0",A=!0,Qe();return}let xt=(Tn=(Mn=o==null?void 0:o.launcher)==null?void 0:Mn.width)!=null?Tn:o==null?void 0:o.launcherWidth,B=xt!=null?xt:oo;if(!f&&!l)v&&h?(be.style.width="100%",be.style.maxWidth="100%"):(be.style.width=B,be.style.maxWidth=B);else if(l)if(no(o).reveal==="emerge"){let qt=no(o).width;be.style.width=qt,be.style.maxWidth=qt}else be.style.width="100%",be.style.maxWidth="100%";if(Ro(),be.style.boxShadow=Le,be.style.borderRadius=Ee,pe.style.border=st,pe.style.borderRadius=Ee,l&&!Q&&(R==null?void 0:R.border)===void 0&&(pe.style.border="none",no(o).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1 1 0%",_e.style.minHeight="0",_e.style.maxHeight="100%",_e.style.height="100%",v&&(_e.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.height="100%",be.style.overflow="hidden",pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0"),_e.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&&!v&&!l&&((en=To[ye])!=null?en:To["bottom-right"]).split(" ").forEach(qt=>_e.classList.add(qt)),f){let Vt=(wo=(Xn=o.launcher)==null?void 0:Xn.sidebarWidth)!=null?wo:"420px";_e.style.cssText=`
|
|
115
70
|
position: fixed !important;
|
|
116
71
|
top: 0 !important;
|
|
117
72
|
bottom: 0 !important;
|
|
118
|
-
width: ${
|
|
73
|
+
width: ${Vt} !important;
|
|
119
74
|
height: 100vh !important;
|
|
120
75
|
max-height: 100vh !important;
|
|
121
76
|
margin: 0 !important;
|
|
122
77
|
padding: 0 !important;
|
|
123
78
|
display: flex !important;
|
|
124
79
|
flex-direction: column !important;
|
|
125
|
-
z-index: ${
|
|
126
|
-
${
|
|
127
|
-
`,
|
|
80
|
+
z-index: ${Se} !important;
|
|
81
|
+
${He?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
82
|
+
`,be.style.cssText=`
|
|
128
83
|
position: relative !important;
|
|
129
84
|
display: flex !important;
|
|
130
85
|
flex-direction: column !important;
|
|
@@ -135,9 +90,9 @@ _Details: ${t.message}_`:o}var Zs=r=>({isError:!0,content:[{type:"text",text:r}]
|
|
|
135
90
|
min-height: 0 !important;
|
|
136
91
|
margin: 0 !important;
|
|
137
92
|
padding: 0 !important;
|
|
138
|
-
box-shadow: ${
|
|
139
|
-
border-radius: ${
|
|
140
|
-
`,
|
|
93
|
+
box-shadow: ${Le} !important;
|
|
94
|
+
border-radius: ${Ee} !important;
|
|
95
|
+
`,be.style.setProperty("width","100%","important"),be.style.setProperty("max-width","100%","important"),pe.style.cssText=`
|
|
141
96
|
display: flex !important;
|
|
142
97
|
flex-direction: column !important;
|
|
143
98
|
flex: 1 1 0% !important;
|
|
@@ -146,29 +101,29 @@ _Details: ${t.message}_`:o}var Zs=r=>({isError:!0,content:[{type:"text",text:r}]
|
|
|
146
101
|
min-height: 0 !important;
|
|
147
102
|
max-height: 100% !important;
|
|
148
103
|
overflow: hidden !important;
|
|
149
|
-
border-radius: ${
|
|
150
|
-
border: ${
|
|
151
|
-
`,
|
|
104
|
+
border-radius: ${Ee} !important;
|
|
105
|
+
border: ${st} !important;
|
|
106
|
+
`,Ne.style.cssText=`
|
|
152
107
|
flex-shrink: 0 !important;
|
|
153
108
|
border-top: none !important;
|
|
154
109
|
padding: 8px 16px 12px 16px !important;
|
|
155
|
-
`}if(!S&&!c){let Zt="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",Et=g?"":`z-index: ${(Ir=(pt=o.launcher)==null?void 0:pt.zIndex)!=null?Ir:so} !important;`;De.style.cssText+=Zt+Yt+Et}ot()};to(),Vn(r,o),Ql(r,o),Yl(r,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",Nr)});let re=null,A=null;gt.push(()=>{re==null||re(),re=null,A==null||A(),A=null}),co&>.push(()=>{co==null||co.disconnect(),co=null}),gt.push(()=>{Fr==null||Fr(),Fr=null,Uo(),$t&&($t.remove(),$t=null),mt==null||mt.element.style.removeProperty("width"),mt==null||mt.element.style.removeProperty("maxWidth")}),We&>.push(()=>{Oe!==null&&(cancelAnimationFrame(Oe),Oe=null),Y==null||Y.destroy(),Y=null,be==null||be.destroy(),be=null,ne=null});let _=null,ue=()=>{_&&(_(),_=null),o.colorScheme==="auto"&&(_=El(()=>{Vn(r,o)}))};ue(),gt.push(()=>{_&&(_(),_=null)});let $=(Rf=o.features)==null?void 0:Rf.streamAnimation;if($!=null&&$.type&&$.type!=="none"){let c=ni($.type,$.plugins);c&&(Yp(c,r),gt.push(()=>Hx(r)))}let at=Kx(Pt),ut=null,U,nr=c=>{var S,W;if(!U)return;let g=c!=null?c:U.getMessages(),b=((W=(S=o.features)==null?void 0:S.suggestReplies)==null?void 0:W.enabled)!==!1?Yi(g):null;b?at.render(b,U,te,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(F=>F.role==="user")?at.render([],U,te,g):at.render(o.suggestionChips,U,te,g,o.suggestionChipsConfig)},mr=!1,Cr=Sx(),ko=new Map,sr=new Map,Ko=new Map,us=0,Eo=Rl(),Lo=0,Xo=null,Qo=!1,Qn=!1,gn=0,ro=null,an=null,Pa=!1,Yn=!1,Ra=null,bi=4,Ia=24,vi=80,Ha=new Map,Lt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},fs=(Hf=(If=o.voiceRecognition)==null?void 0:If.autoResume)!=null?Hf:!1,zo=c=>{a.emit("voice:state",{active:Lt.active,source:c,timestamp:Date.now()})},So=()=>{m(c=>({...c,voiceState:{active:Lt.active,timestamp:Date.now(),manuallyDeactivated:Lt.manuallyDeactivated}}))},Ci=()=>{var S,W;if(((S=o.voiceRecognition)==null?void 0:S.enabled)===!1)return;let c=gu(d.voiceState),g=!!c.active,b=Number((W=c.timestamp)!=null?W:0);Lt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<QC&&setTimeout(()=>{var F,q;Lt.active||(Lt.manuallyDeactivated=!1,((q=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:q.type)==="runtype"?U.toggleVoice().then(()=>{Lt.active=U.isVoiceActive(),zo("restore"),U.isVoiceActive()&&Ts()}):pr("restore"))},1e3)},wi=()=>U?fy(U.getMessages()).filter(c=>!c.__skipPersist):[];function Wa(c){if(!(i!=null&&i.save))return;let b={messages:c?fy(c):U?wi():[],metadata:d,artifacts:po.artifacts,selectedArtifactId:po.selectedId};try{let S=i.save(b);S instanceof Promise&&S.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let hn=null,ms=()=>De.querySelector("#persona-scroll-container")||he,Pn=()=>{hn!==null&&(cancelAnimationFrame(hn),hn=null),Qo=!1},gs=()=>{Xo!==null&&(cancelAnimationFrame(Xo),Xo=null),Qn=!1,Pn()},hs=()=>{gn>0?(Dr.textContent=String(gn),Dr.style.display="",tt.setAttribute("aria-label",`${zt()||"Jump to latest"} (${gn} new)`)):(Dr.textContent="",Dr.style.display="none",tt.setAttribute("aria-label",zt()||"Jump to latest"))},xs=()=>{gn!==0&&(gn=0,hs())},ys=()=>xt()==="follow"?!Eo.isFollowing():!Aa(he,Ia),To=()=>{if(!vr()||ge){tt.parentNode&&tt.remove(),tt.style.display="none";return}tt.parentNode!==K&&K.appendChild(tt),Sr();let g=Mn(he)>0&&ys();g||xs(),tt.style.display=g?"":"none"},Ba=()=>{Eo.pause()&&(gs(),To())},sn=()=>{Eo.resume(),xs(),To()},ln=(c=!1)=>{xt()==="follow"&&Eo.isFollowing()&&(!c&&!mr||(Xo!==null&&(cancelAnimationFrame(Xo),Xo=null),Qn=!0,Xo=requestAnimationFrame(()=>{Xo=null,Qn=!1,Eo.isFollowing()&&Ai(ms(),c?220:140)})))},bs=(c,g,b,S=()=>!0)=>{let W=c.scrollTop,F=g(),q=F-W;Pn();let G=performance.now();Qo=!0;let N=xe=>1-Math.pow(1-xe,3),Se=xe=>{if(!S()){Pn();return}let se=g();se!==F&&(F=se,q=F-W);let ke=xe-G,Ge=Math.min(ke/b,1),Te=N(Ge),ft=W+q*Te;c.scrollTop=ft,Lo=c.scrollTop,Ge<1?hn=requestAnimationFrame(Se):(c.scrollTop=F,Lo=c.scrollTop,hn=null,Qo=!1)};hn=requestAnimationFrame(Se)},Ai=(c,g=500)=>{let b=Mn(c)-c.scrollTop;if(Math.abs(b)<1){Lo=c.scrollTop;return}if(Math.abs(b)>=vi){Pn(),Qo=!0,c.scrollTop=Mn(c),Lo=c.scrollTop,Qo=!1;return}bs(c,()=>Mn(c),g,()=>Eo.isFollowing())},vs=()=>{let c=ms();Qo=!0,c.scrollTop=Mn(c),Lo=c.scrollTop,Qo=!1,To()},Cs=c=>{hr.style.height=`${Math.max(0,Math.round(c))}px`,ro&&(ro.spacerHeight=Math.max(0,c))},Jn=()=>{an!==null&&(cancelAnimationFrame(an),an=null),Pn(),ro=null,hr.style.height="0px"},Si=c=>{an!==null&&cancelAnimationFrame(an),an=requestAnimationFrame(()=>{var Se;an=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=he.querySelector(`[data-message-id="${g}"]`);if(!b)return;let S=0,W=b;for(;W&&W!==he;)S+=W.offsetTop,W=W.offsetParent;let F=(Se=ro==null?void 0:ro.spacerHeight)!=null?Se:0,q=he.scrollHeight-F,{targetScrollTop:G,spacerHeight:N}=Lx({anchorOffsetTop:S,topOffset:It(),viewportHeight:he.clientHeight,contentHeight:q});ro={initialSpacerHeight:N,contentHeightAtAnchor:q,spacerHeight:N},Cs(N),bs(he,()=>G,220)})},Ti=()=>{if(xt()==="follow"){if(!Eo.isFollowing()||Aa(he,1))return;ln(!mr);return}if(ro&&ro.initialSpacerHeight>0){let c=he.scrollHeight-ro.spacerHeight,g=Px({initialSpacerHeight:ro.initialSpacerHeight,contentHeightAtAnchor:ro.contentHeightAtAnchor,currentContentHeight:c});g!==ro.spacerHeight&&Cs(g)}To()},Mi=c=>{let g=xt();g==="follow"?(sn(),ln(!0)):g==="anchor-top"&&Si(c)},ki=c=>{let g=new Map;c.forEach(b=>{let S=Ha.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!S&&b.role==="assistant"&&(a.emit("assistant:message",b),!Yn&&xt()!=="anchor-top"&&ys()&&(gn+=1,hs(),To())),b.role==="assistant"&&(S!=null&&S.streaming)&&b.streaming===!1&&a.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(S?b.approval.status!=="pending"&&a.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):a.emit("approval:requested",{approval:b.approval,message:b}))}),Ha.clear(),g.forEach((b,S)=>{Ha.set(S,b)})},Zn=(c,g,b)=>{var vt,He,Pe,Qe,ot,Ht;let S=document.createElement("div"),F=(()=>{var Ne;let D=n.find(Fe=>Fe.renderLoadingIndicator);if(D!=null&&D.renderLoadingIndicator)return D.renderLoadingIndicator;if((Ne=o.loadingIndicator)!=null&&Ne.render)return o.loadingIndicator.render})(),q=(D,Ne)=>Ne==null?!1:typeof Ne=="string"?(D.textContent=Ne,!0):(D.appendChild(Ne),!0),G=new Set,N=new Set,Se=n.some(D=>D.renderAskUserQuestion),xe=[],se=[],ke=o.enableComponentStreaming!==!1,Ge=n.some(D=>D.renderApproval)&&o.approval!==!1,Te=[];if(g.forEach(D=>{var st,Ut,kr,Vo,Ro,ta,ra,Fa,Ua,ur,oa,On,_n,yn,na,Yo;G.add(D.id);let Ne=Se&&wn(D),Fe=Ge&&D.variant==="approval"&&!!D.approval,we=!Ne&&D.role==="assistant"&&!D.variant&&ke&&td(D);if(!Fe&&Ko.has(D.id)){let pt=c.querySelector(`#wrapper-${D.id}`);pt==null||pt.removeAttribute("data-preserve-runtime"),Ko.delete(D.id)}if(!we&&sr.has(D.id)){let pt=c.querySelector(`#wrapper-${D.id}`);pt==null||pt.removeAttribute("data-preserve-runtime"),sr.delete(D.id)}let Qt=wn(D)?`:${(st=D.agentMetadata)!=null&&st.askUserQuestionAnswered?"a":"u"}:${(Ut=D.agentMetadata)!=null&&Ut.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",Kt=Ax(D,us)+Qt,ir=Ne||Fe||we?null:Tx(Cr,D.id,Kt);if(ir){S.appendChild(ir.cloneNode(!0)),wn(D)&&((kr=D.toolCall)!=null&&kr.id)&&((Vo=D.agentMetadata)==null?void 0:Vo.awaitingLocalTool)===!0&&!((Ro=D.agentMetadata)!=null&&Ro.askUserQuestionAnswered)&&(N.add(D.toolCall.id),Qa(D,o,Re.composerOverlay));return}let Bt=null,ar=n.find(pt=>!!(D.variant==="reasoning"&&pt.renderReasoning||D.variant==="tool"&&pt.renderToolCall||!D.variant&&pt.renderMessage)),Po=(ta=o.layout)==null?void 0:ta.messages;if(wn(D)&&((ra=D.agentMetadata)==null?void 0:ra.askUserQuestionAnswered)===!0){ko.delete(D.id);let pt=c.querySelector(`#wrapper-${D.id}`);pt==null||pt.removeAttribute("data-preserve-runtime");return}if(js(D)&&((Ua=(Fa=o.features)==null?void 0:Fa.suggestReplies)==null?void 0:Ua.enabled)!==!1)return;if(wn(D)&&((oa=(ur=o.features)==null?void 0:ur.askUserQuestion)==null?void 0:oa.enabled)!==!1){let pt=n.find(Ir=>typeof Ir.renderAskUserQuestion=="function");if(pt&&Wt.current){let Ir=ko.get(D.id),Zt=Ir!==Kt,Yt=null;if(Zt){let{payload:_t,complete:oo}=An(D),ho=D.id,dn=()=>{var qr;return(qr=Wt.current)==null?void 0:qr.getMessages().find(xo=>xo.id===ho)};Yt=pt.renderAskUserQuestion({message:D,payload:_t,complete:oo,resolve:qr=>{var yo;let xo=dn();xo&&((yo=Wt.current)==null||yo.resolveAskUserQuestion(xo,qr))},dismiss:()=>{var xo,yo,aa;let qr=dn();(xo=qr==null?void 0:qr.agentMetadata)!=null&&xo.awaitingLocalTool&&((yo=Wt.current)==null||yo.markAskUserQuestionResolved(qr),(aa=Wt.current)==null||aa.resolveAskUserQuestion(qr,"(dismissed)"))},config:o})}let Et=Ir!=null;if(Zt&&Yt===null&&!Et){((On=D.agentMetadata)==null?void 0:On.awaitingLocalTool)===!0&&!((_n=D.agentMetadata)!=null&&_n.askUserQuestionAnswered)&&(N.add(D.toolCall.id),Qa(D,o,Re.composerOverlay));return}let fr=document.createElement("div");fr.className="persona-flex",fr.id=`wrapper-${D.id}`,fr.setAttribute("data-wrapper-id",D.id),fr.setAttribute("data-ask-plugin-stub","true"),fr.setAttribute("data-preserve-runtime","true"),S.appendChild(fr),xe.push({messageId:D.id,fingerprint:Kt,bubble:Yt});return}else{((yn=D.agentMetadata)==null?void 0:yn.awaitingLocalTool)===!0&&!((na=D.agentMetadata)!=null&&na.askUserQuestionAnswered)&&(N.add(D.toolCall.id),Qa(D,o,Re.composerOverlay));return}}else if(Fe){let pt=n.find(Et=>typeof Et.renderApproval=="function"),Zt=Ko.get(D.id)!==Kt,Yt=null;if(Zt&&(pt!=null&&pt.renderApproval)){let Et=D.id,fr=(_t,oo)=>{var dn,qr,xo;let ho=(dn=Wt.current)==null?void 0:dn.getMessages().find(yo=>yo.id===Et);ho!=null&&ho.approval&&(ho.approval.toolType==="webmcp"?(qr=Wt.current)==null||qr.resolveWebMcpApproval(ho.id,_t):(xo=Wt.current)==null||xo.resolveApproval(ho.approval,_t,oo))};Yt=pt.renderApproval({message:D,defaultRenderer:()=>Kl(D,o),config:o,approve:_t=>fr("approved",_t),deny:_t=>fr("denied",_t)})}if(Zt&&Yt===null){let Et=c.querySelector(`#wrapper-${D.id}`);Et==null||Et.removeAttribute("data-preserve-runtime"),Ko.delete(D.id),Bt=Kl(D,o)}else{let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${D.id}`,Et.setAttribute("data-wrapper-id",D.id),Et.setAttribute("data-approval-plugin-stub","true"),Et.setAttribute("data-preserve-runtime","true"),S.appendChild(Et),Te.push({messageId:D.id,fingerprint:Kt,bubble:Yt});return}}else if(ar)if(D.variant==="reasoning"&&D.reasoning&&ar.renderReasoning){if(!Xe)return;Bt=ar.renderReasoning({message:D,defaultRenderer:()=>iu(D,o),config:o})}else if(D.variant==="tool"&&D.toolCall&&ar.renderToolCall){if(!Ae)return;Bt=ar.renderToolCall({message:D,defaultRenderer:()=>lu(D,o),config:o})}else ar.renderMessage&&(Bt=ar.renderMessage({message:D,defaultRenderer:()=>{let pt=as(D,b,Po,o.messageActions,ae,{loadingIndicatorRenderer:F,widgetConfig:o});return D.role!=="user"&&uu(pt,D,o,U),pt},config:o}));if(!Bt&&we){let pt=rd(D);if(pt){let Ir=sr.get(D.id),Zt=Ir!==Kt,Yt=o.wrapComponentDirectiveInBubble!==!1,Et=null;if(Zt){let fr=ed(pt,{config:o,message:D,transform:b});if(fr)if(Yt){let _t=document.createElement("div");if(_t.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(" "),_t.id=`bubble-${D.id}`,_t.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let oo=document.createElement("div");oo.className="persona-mb-3 persona-text-sm persona-leading-relaxed",oo.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),_t.appendChild(oo)}_t.appendChild(fr),Et=_t}else{let _t=document.createElement("div");if(_t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",_t.id=`bubble-${D.id}`,_t.setAttribute("data-message-id",D.id),_t.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let oo=document.createElement("div");oo.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",oo.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),_t.appendChild(oo)}_t.appendChild(fr),Et=_t}}if(Et||Ir!=null){let fr=document.createElement("div");fr.className="persona-flex",fr.id=`wrapper-${D.id}`,fr.setAttribute("data-wrapper-id",D.id),fr.setAttribute("data-component-directive-stub","true"),fr.setAttribute("data-preserve-runtime","true"),Yt||fr.classList.add("persona-w-full"),S.appendChild(fr),se.push({messageId:D.id,fingerprint:Kt,bubble:Et});return}}}if(!Bt)if(D.variant==="reasoning"&&D.reasoning){if(!Xe)return;Bt=iu(D,o)}else if(D.variant==="tool"&&D.toolCall){if(!Ae)return;Bt=lu(D,o)}else if(D.variant==="approval"&&D.approval){if(o.approval===!1)return;Bt=Kl(D,o)}else{let pt=(Yo=o.layout)==null?void 0:Yo.messages;pt!=null&&pt.renderUserMessage&&D.role==="user"?Bt=pt.renderUserMessage({message:D,config:o,streaming:!!D.streaming}):pt!=null&&pt.renderAssistantMessage&&D.role==="assistant"?Bt=pt.renderAssistantMessage({message:D,config:o,streaming:!!D.streaming}):Bt=as(D,b,pt,o.messageActions,ae,{loadingIndicatorRenderer:F,widgetConfig:o}),D.role!=="user"&&Bt&&uu(Bt,D,o,U)}let wr=document.createElement("div");wr.className="persona-flex",wr.id=`wrapper-${D.id}`,wr.setAttribute("data-wrapper-id",D.id),D.role==="user"&&wr.classList.add("persona-justify-end"),(Bt==null?void 0:Bt.getAttribute("data-persona-component-directive"))==="true"&&wr.classList.add("persona-w-full"),wr.appendChild(Bt),Mx(Cr,D.id,Kt,wr),S.appendChild(wr)}),Re.composerOverlay&&Re.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Fe=Ne.getAttribute("data-persona-ask-sheet-for");Fe&&!N.has(Fe)&&zn(Re.composerOverlay,Fe)}),(He=(vt=o.features)==null?void 0:vt.toolCallDisplay)!=null&&He.grouped){let D=[],Ne=[];g.forEach(Fe=>{if(Fe.variant==="tool"&&Fe.toolCall&&Ae){Ne.push(Fe);return}Ne.length>1&&D.push(Ne),Ne=[]}),Ne.length>1&&D.push(Ne),D.forEach((Fe,we)=>{var st,Ut;let Qt=Fe.map(kr=>Array.from(S.children).find(Vo=>Vo instanceof HTMLElement&&Vo.getAttribute("data-wrapper-id")===kr.id)).filter(kr=>!!kr);if(Qt.length<2)return;let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id=`wrapper-tool-group-${we}-${Fe[0].id}`,Kt.setAttribute("data-wrapper-id",`tool-group-${we}-${Fe[0].id}`);let ir=document.createElement("div");ir.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",ir.setAttribute("data-persona-tool-group","true");let Bt=document.createElement("div");Bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ar=`Called ${Fe.length} tools`,Po=(Ut=(st=o.toolCall)==null?void 0:st.renderGroupedSummary)==null?void 0:Ut.call(st,{messages:Fe,toolCalls:Fe.map(kr=>kr.toolCall).filter(kr=>!!kr),defaultSummary:ar,config:o});q(Bt,Po)||(Bt.textContent=ar);let wr=document.createElement("div");wr.className="persona-tool-group-stack persona-flex persona-flex-col",ir.append(Bt,wr),Kt.appendChild(ir),Qt[0].before(Kt),Qt.forEach((kr,Vo)=>{let Ro=document.createElement("div");Ro.className="persona-tool-group-item persona-relative",Ro.setAttribute("data-persona-tool-group-item","true"),Vo<Qt.length-1&&Ro.setAttribute("data-persona-tool-group-connector","true"),Ro.appendChild(kr),wr.appendChild(Ro)})})}kx(Cr,G);let ft=g.some(D=>D.role==="assistant"&&D.streaming),Ze=g[g.length-1],bt=(Ze==null?void 0:Ze.role)==="assistant"&&!Ze.streaming&&Ze.variant!=="approval";if(mr&&g.some(D=>D.role==="user")&&!ft&&!bt){let D={config:o,streaming:!0,location:"standalone",defaultRenderer:Ma},Ne=n.find(we=>we.renderLoadingIndicator),Fe=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(Fe=Ne.renderLoadingIndicator(D)),Fe===null&&((Pe=o.loadingIndicator)!=null&&Pe.render)&&(Fe=o.loadingIndicator.render(D)),Fe===null&&(Fe=Ma()),Fe){let we=document.createElement("div"),Qt=((Qe=o.loadingIndicator)==null?void 0:Qe.showBubble)!==!1;we.className=Qt?["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(" "),we.setAttribute("data-typing-indicator","true"),we.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",we.appendChild(Fe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-typing-indicator",Kt.setAttribute("data-wrapper-id","typing-indicator"),Kt.appendChild(we),S.appendChild(Kt)}}if(!mr&&g.length>0){let D=g[g.length-1],Ne={config:o,lastMessage:D,messageCount:g.length},Fe=n.find(Qt=>Qt.renderIdleIndicator),we=null;if(Fe!=null&&Fe.renderIdleIndicator&&(we=Fe.renderIdleIndicator(Ne)),we===null&&((ot=o.loadingIndicator)!=null&&ot.renderIdle)&&(we=o.loadingIndicator.renderIdle(Ne)),we){let Qt=document.createElement("div"),Kt=((Ht=o.loadingIndicator)==null?void 0:Ht.showBubble)!==!1;Qt.className=Kt?["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(" "),Qt.setAttribute("data-idle-indicator","true"),Qt.appendChild(we);let ir=document.createElement("div");ir.className="persona-flex",ir.id="wrapper-idle-indicator",ir.setAttribute("data-wrapper-id","idle-indicator"),ir.appendChild(Qt),S.appendChild(ir)}}if(Ll(c,S),xe.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Fe}of xe){let we=c.querySelector(`#wrapper-${D}`);we&&Fe!==null&&(we.replaceChildren(Fe),we.setAttribute("data-bubble-fp",Ne),ko.set(D,Ne))}if(ko.size>0)for(let D of ko.keys())G.has(D)||ko.delete(D);if(se.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Fe}of se){let we=c.querySelector(`#wrapper-${D}`);we&&Fe!==null&&(we.replaceChildren(Fe),we.setAttribute("data-bubble-fp",Ne),sr.set(D,Ne))}if(sr.size>0)for(let D of sr.keys())G.has(D)||sr.delete(D);if(Te.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Fe}of Te){let we=c.querySelector(`#wrapper-${D}`);we&&Fe!==null&&(we.replaceChildren(Fe),we.setAttribute("data-bubble-fp",Ne),Ko.set(D,Ne))}if(Ko.size>0)for(let D of Ko.keys())G.has(D)||Ko.delete(D)},Rn=null,Ei=()=>{var b;if(Rn)return;let c=S=>{let W=S.composedPath();W.includes(De)||nt&&W.includes(nt)||Gt(!1,"user")};Rn=c,((b=r.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},ws=()=>{var g;if(!Rn)return;((g=r.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Rn,!0),Rn=null};gt.push(()=>ws());let In=null,Li=()=>{var b;if(In)return;let c=S=>{S.key==="Escape"&&(S.isComposing||Gt(!1,"user"))};In=c,((b=r.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},As=()=>{var g;if(!In)return;((g=r.ownerDocument)!=null?g:document).removeEventListener("keydown",In,!0),In=null};gt.push(()=>As());let Hn=!1,Ss=new Set,Pi=()=>{var g,b,S,W;let c=(S=(b=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:S.streamAnimation;return c||((W=o.features)==null?void 0:W.streamAnimation)},xn=()=>{var bt,vt,He,Pe;if(!H())return;let c=Re.peekBanner,g=Re.peekTextNode;if(!c||!g)return;if(P){c.classList.remove("persona-pill-peek--visible");return}let b=(bt=U==null?void 0:U.getMessages())!=null?bt:[],S;for(let Qe=b.length-1;Qe>=0;Qe--){let ot=b[Qe];if(ot.role==="assistant"&&ot.content){S=ot;break}}if(!S){c.classList.remove("persona-pill-peek--visible");return}let W=S.content,F=!!S.streaming,q=Pi(),G=Wl(q),N=G.type!=="none"?ni(G.type,q==null?void 0:q.plugins):null,Se=((vt=N==null?void 0:N.isAnimating)==null?void 0:vt.call(N,S))===!0,xe=N!==null&&(F||Se);xe&&N&&!Ss.has(N.name)&&(Yp(N,r),Ss.add(N.name));let se=xe&&(N!=null&&N.containerClass)?N.containerClass:null,ke=(He=g.dataset.personaPeekStreamClass)!=null?He:null;ke&&ke!==se&&(g.classList.remove(ke),delete g.dataset.personaPeekStreamClass),se&&ke!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),xe?(g.style.setProperty("--persona-stream-step",`${G.speed}ms`),g.style.setProperty("--persona-stream-duration",`${G.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ge=xe?Bl(W,G.buffer,N,S,F):W;if(xe&&G.placeholder==="skeleton"&&F&&(!Ge||!Ge.trim())){let Qe=document.createElement("div"),ot=si();ot.classList.add("persona-pill-peek__skeleton"),Qe.appendChild(ot),Ll(g,Qe)}else{let Qe=Math.max(0,Ge.length-100),ot=Ge.length>100?Ge.slice(-100):Ge,Ht=fa(ot);if(!xe||!N){let D=Ge.length>100?`\u2026${ot}`:ot;g.textContent!==D&&(g.textContent=D)}else{let D=Ht;(N.wrap==="char"||N.wrap==="word")&&(D=ai(Ht,N.wrap,`peek-${S.id}`,{skipTags:N.skipTags,startIndex:Qe}));let Ne=document.createElement("div");if(Ne.innerHTML=D,N.useCaret&&ot.length>0){let Fe=Dl(),we=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Qt=we[we.length-1];Qt!=null&&Qt.parentNode?Qt.parentNode.insertBefore(Fe,Qt.nextSibling):Ne.appendChild(Fe)}Ll(g,Ne),(Pe=N.onAfterRender)==null||Pe.call(N,{container:g,bubble:c,messageId:S.id,message:S,speed:G.speed,duration:G.duration})}}let Ze=mr||Hn;c.classList.toggle("persona-pill-peek--visible",Ze)};if(H()){let c=Re.peekBanner;if(c){let S=W=>{W.preventDefault(),W.stopPropagation(),Gt(!0,"user")};c.addEventListener("pointerdown",S),gt.push(()=>{c.removeEventListener("pointerdown",S)})}let g=()=>{Hn||(Hn=!0,xn())},b=()=>{Hn&&(Hn=!1,xn())};le.addEventListener("pointerenter",g),le.addEventListener("pointerleave",b),gt.push(()=>{le.removeEventListener("pointerenter",g),le.removeEventListener("pointerleave",b)}),nt&&(nt.addEventListener("pointerenter",g),nt.addEventListener("pointerleave",b),gt.push(()=>{nt.removeEventListener("pointerenter",g),nt.removeEventListener("pointerleave",b)}))}let Ri=c=>{var ke,Ge,Te,ft,Ze,bt,vt,He;let g=(Ge=(ke=o.launcher)==null?void 0:ke.composerBar)!=null?Ge:{},b=(Te=g.expandedSize)!=null?Te:"anchored",S=(ft=g.bottomOffset)!=null?ft:"16px",W=g.collapsedMaxWidth,F=(Ze=g.expandedMaxWidth)!=null?Ze:"880px",q=(bt=g.expandedTopOffset)!=null?bt:"5vh",G=(vt=g.modalMaxWidth)!=null?vt:"880px",N=(He=g.modalMaxHeight)!=null?He:"min(90vh, 800px)",Se="calc(100vw - 32px)",xe="var(--persona-pill-area-height, 80px)",se=De.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",nt){let Pe=nt.style;Pe.bottom=S,Pe.width=W!=null?W:""}if(c&&b!=="fullscreen"){if(b==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=G,se.maxWidth=Se,se.maxHeight=N,se.height=N;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${S} + ${xe})`,se.top=q,se.width=F,se.maxWidth=Se}},Wn=()=>{var N,Se,xe,se,ke,Ge,Te,ft;if(!I())return;if(H()){let bt=(xe=((Se=(N=o.launcher)==null?void 0:N.composerBar)!=null?Se:{}).expandedSize)!=null?xe:"anchored",vt=P?"expanded":"collapsed";De.dataset.state=vt,De.dataset.expandedSize=bt,nt&&(nt.dataset.state=vt,nt.dataset.expandedSize=bt),De.style.removeProperty("display"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ri(P),K.style.display=P?"flex":"none",to(),P?(Ei(),Li()):(ws(),As()),xn();return}let c=Lr(o),g=(se=r.ownerDocument.defaultView)!=null?se:window,b=(Ge=(ke=o.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Ge:640,S=(ft=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?ft:!0,W=g.innerWidth<=b,F=S&&W&&M,q=Bo(o).reveal;P?(De.style.removeProperty("display"),De.style.display=c?"flex":"",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),xr?xr.element.style.display="none":yr&&(yr.style.display="none")):(c?c&&(q==="overlay"||q==="push")&&!F?(De.style.removeProperty("display"),De.style.display="flex",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.setProperty("display","none","important"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.display="",De.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),xr?xr.element.style.display=c?"none":"":yr&&(yr.style.display=c?"none":""))},Gt=(c,g="user")=>{var F,q;if(!I()||P===c)return;let b=P;P=c,Wn();let S=(()=>{var Te,ft,Ze,bt,vt,He,Pe,Qe,ot,Ht;let G=(ft=(Te=o.launcher)==null?void 0:Te.sidebarMode)!=null?ft:!1,N=(Ze=r.ownerDocument.defaultView)!=null?Ze:window,Se=(vt=(bt=o.launcher)==null?void 0:bt.mobileFullscreen)!=null?vt:!0,xe=(Pe=(He=o.launcher)==null?void 0:He.mobileBreakpoint)!=null?Pe:640,se=N.innerWidth<=xe,ke=Lr(o)&&Se&&se,Ge=H()&&((Ht=(ot=(Qe=o.launcher)==null?void 0:Qe.composerBar)==null?void 0:ot.expandedSize)!=null?Ht:"fullscreen")==="fullscreen";return G||Se&&se&&M||ke||Ge})();if(P&&S){if(!re){let G=r.getRootNode(),N=G instanceof ShadowRoot?G.host:r.closest(".persona-host");N&&(re=Jp(N,(q=(F=o.launcher)==null?void 0:F.zIndex)!=null?q:so))}A||(A=Zp(r.ownerDocument))}else P||(re==null||re(),re=null,A==null||A(),A=null);P&&(Ms(),xt()==="follow"?ln(!0):vs());let W={open:P,source:g,timestamp:Date.now()};P&&!b?a.emit("widget:opened",W):!P&&b&&a.emit("widget:closed",W),a.emit("widget:state",{open:P,launcherEnabled:M,voiceActive:Lt.active,streaming:U.isStreaming()})},Da=c=>{or(c?"stop":"send"),X&&(X.disabled=c),at.buttons.forEach(g=>{g.disabled=c}),ze.dataset.personaComposerStreaming=c?"true":"false",ze.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Oa=()=>{Lt.active||te&&te.focus()};a.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Oa(),200)});let ea=()=>{var b,S,W,F,q,G,N,Se,xe,se,ke;Yr.textContent=(S=(b=o.copy)==null?void 0:b.welcomeTitle)!=null?S:"Hello \u{1F44B}",zr.textContent=(F=(W=o.copy)==null?void 0:W.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",te.placeholder=(G=(q=o.copy)==null?void 0:q.inputPlaceholder)!=null?G:"How can I help...";let c=he.querySelector("[data-persona-intro-card]");if(c){let Ge=((N=o.copy)==null?void 0:N.showWelcomeCard)!==!1;c.style.display=Ge?"":"none",Ge?(he.classList.remove("persona-gap-3"),he.classList.add("persona-gap-6")):(he.classList.remove("persona-gap-6"),he.classList.add("persona-gap-3"))}!((xe=(Se=o.sendButton)==null?void 0:Se.useIcon)!=null&&xe)&&!(U!=null&&U.isStreaming())&&(_e.textContent=(ke=(se=o.copy)==null?void 0:se.sendButtonLabel)!=null?ke:"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))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Ke=null,R=()=>{Ke==null&&(Ke=setInterval(()=>{let c=it.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ke),Ke=null;return}let g=Date.now();c.forEach(b=>{let S=Number(b.getAttribute("data-tool-elapsed"));S&&(b.textContent=Zi(g-S))})},100))};if(U=new Za(o,{onMessagesChanged(c){var S;Zn(it,c,ve),R(),nr(c),ln(!mr),ki(c);let g=[...c].reverse().find(W=>W.role==="user");c.length===0&&Jn(),!Pa||Yn?(Pa=!0,Ra=(S=g==null?void 0:g.id)!=null?S:null):g&&g.id!==Ra&&(Ra=g.id,Mi(g.id));let b=Lt.lastUserMessageId;g&&g.id!==b&&(Lt.lastUserMessageId=g.id,a.emit("user:message",g)),Lt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wa(c),xn()},onStatusChanged(c){var S;let g=(S=o.statusIndicator)!=null?S:{};Ye(dr,(W=>{var F,q,G,N;return W==="idle"?(F=g.idleText)!=null?F:ao.idle:W==="connecting"?(q=g.connectingText)!=null?q:ao.connecting:W==="connected"?(G=g.connectedText)!=null?G:ao.connected:W==="error"?(N=g.errorText)!=null?N:ao.error:ao[W]})(c),g,c)},onStreamingChanged(c){mr=c,Da(c),U&&Zn(it,U.getMessages(),ve),c||ln(!0),xn()},onVoiceStatusChanged(c){var g,b;if(((b=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":Bn(),rb();break;case"speaking":Bn(),ob();break;default:c==="idle"&&U.isBargeInActive()?(Bn(),Ts(),X==null||X.setAttribute("aria-label","End voice session")):(Lt.active=!1,Bn(),zo("system"),So());break}},onArtifactsState(c){po=c,eo(),Wa()}}),Wt.current=U,Pa=!0,((Bf=(Wf=o.voiceRecognition)==null?void 0:Wf.provider)==null?void 0:Bf.type)==="runtype")try{U.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&U.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(be||o.onSSEEvent)&&U.setSSEEventCallback((c,g)=>{var b;(b=o.onSSEEvent)==null||b.call(o,c,g),ye==null||ye.processEvent(c,g),be==null||be.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,S;if(c){if(c.metadata&&(d=gu(c.metadata),T.syncFromMetadata()),(g=c.messages)!=null&&g.length){Yn=!0;try{U.hydrateMessages(c.messages)}finally{Yn=!1}}(b=c.artifacts)!=null&&b.length&&U.hydrateArtifacts(c.artifacts,(S=c.selectedArtifactId)!=null?S:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let V=()=>{var g,b,S;!H()||P||!((S=(b=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||S)||Gt(!0,"auto")},B=c=>{var W;if(c.preventDefault(),U.isStreaming()){U.cancel(),ye==null||ye.reset(),Y==null||Y.update();return}let g=te.value.trim(),b=(W=je==null?void 0:je.hasAttachments())!=null?W:!1;if(!g&&!b)return;V();let S;b&&(S=[],S.push(...je.getContentParts()),g&&S.push(Qs(g))),te.value="",te.style.height="auto",Le(),U.sendMessage(g,{contentParts:S}),b&&je.clearAttachments()},oe=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},pe={...Pl},J=!1,Le=()=>{pe={...Pl}},Ve=()=>U.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),yt=c=>{if(!te)return;J=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),J=!1;let g=te.value.length;te.setSelectionRange(g,g)},dt=()=>{J||Le()},Vt=c=>{if(te){if(oe()&&(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=wx({direction:c.key==="ArrowUp"?"up":"down",history:Ve(),currentValue:te.value,atStart:g,state:pe});if(pe=b.state,b.handled){c.preventDefault(),b.value!==void 0&&yt(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(U.isStreaming()){c.preventDefault();return}Le(),c.preventDefault(),_e.click()}}},Jt=c=>{c.key!=="Escape"||c.isComposing||U.isStreaming()&&c.composedPath().includes(K)&&(U.cancel(),ye==null||ye.reset(),Y==null||Y.update(),Le(),c.preventDefault(),c.stopImmediatePropagation())},Rr=async c=>{var b;if(((b=o.attachments)==null?void 0:b.enabled)!==!0||!je)return;let g=JC(c.clipboardData);g.length!==0&&(c.preventDefault(),await je.handleFiles(g))},ht=null,kt=!1,gr=null,et=null,jr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,pr=(c="user")=>{var F,q,G,N,Se,xe,se;if(kt||U.isStreaming())return;let g=jr();if(!g)return;ht=new g;let S=(q=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?q:2e3;ht.continuous=!0,ht.interimResults=!0,ht.lang="en-US";let W=te.value;ht.onresult=ke=>{let Ge="",Te="";for(let Ze=0;Ze<ke.results.length;Ze++){let bt=ke.results[Ze],vt=bt[0].transcript;bt.isFinal?Ge+=vt+" ":Te=vt}let ft=W+Ge+Te;te.value=ft,gr&&clearTimeout(gr),(Ge||Te)&&(gr=window.setTimeout(()=>{let Ze=te.value.trim();Ze&&ht&&kt&&(Ur(),te.value="",te.style.height="auto",U.sendMessage(Ze,{viaVoice:!0}))},S))},ht.onerror=ke=>{ke.error!=="no-speech"&&Ur()},ht.onend=()=>{if(kt){let ke=te.value.trim();ke&&ke!==W.trim()&&(te.value="",te.style.height="auto",U.sendMessage(ke,{viaVoice:!0})),Ur()}};try{if(ht.start(),kt=!0,Lt.active=!0,c!=="system"&&(Lt.manuallyDeactivated=!1),zo(c),So(),X){let ke=(G=o.voiceRecognition)!=null?G:{};et={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:(N=ke.iconName)!=null?N:"mic",iconSize:parseFloat((se=(xe=ke.iconSize)!=null?xe:(Se=o.sendButton)==null?void 0:Se.size)!=null?se:"40")||24};let Ge=ke.recordingBackgroundColor,Te=ke.recordingIconColor,ft=ke.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=Ge!=null?Ge:"var(--persona-voice-recording-bg, #ef4444)",X.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let Ze=X.querySelector("svg");Ze&&Ze.setAttribute("stroke",Te)}ft&&(X.style.borderColor=ft),X.setAttribute("aria-label","Stop voice recognition")}}catch{Ur("system")}},Ur=(c="user")=>{if(kt){if(kt=!1,gr&&(clearTimeout(gr),gr=null),ht){try{ht.stop()}catch{}ht=null}if(Lt.active=!1,zo(c),So(),X){if(X.classList.remove("persona-voice-recording"),et){X.style.backgroundColor=et.backgroundColor,X.style.color=et.color,X.style.borderColor=et.borderColor;let g=X.querySelector("svg");g&&g.setAttribute("stroke",et.color||"currentColor"),et=null}X.setAttribute("aria-label","Start voice recognition")}}},tb=(c,g)=>{var bt,vt,He,Pe,Qe,ot,Ht,D;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((bt=c==null?void 0:c.provider)==null?void 0:bt.type)==="runtype";if(!(b||S))return null;let F=C("div","persona-send-button-wrapper"),q=C("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");q.type="button",q.setAttribute("aria-label","Start voice recognition");let G=(vt=c==null?void 0:c.iconName)!=null?vt:"mic",N=(He=g==null?void 0:g.size)!=null?He:"40px",Se=(Pe=c==null?void 0:c.iconSize)!=null?Pe:N,xe=parseFloat(Se)||24,se=(Qe=c==null?void 0:c.backgroundColor)!=null?Qe:g==null?void 0:g.backgroundColor,ke=(ot=c==null?void 0:c.iconColor)!=null?ot:g==null?void 0:g.textColor;q.style.width=Se,q.style.height=Se,q.style.minWidth=Se,q.style.minHeight=Se,q.style.fontSize="18px",q.style.lineHeight="1",ke?q.style.color=ke:q.style.color="var(--persona-text, #111827)";let Te=Ee(G,xe,ke||"currentColor",1.5);Te?q.appendChild(Te):q.textContent="\u{1F3A4}",se?q.style.backgroundColor=se:q.style.backgroundColor="",c!=null&&c.borderWidth&&(q.style.borderWidth=c.borderWidth,q.style.borderStyle="solid"),c!=null&&c.borderColor&&(q.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(q.style.paddingLeft=c.paddingX,q.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(q.style.paddingTop=c.paddingY,q.style.paddingBottom=c.paddingY),F.appendChild(q);let ft=(Ht=c==null?void 0:c.tooltipText)!=null?Ht:"Start voice recognition";if(((D=c==null?void 0:c.showTooltip)!=null?D:!1)&&ft){let Ne=C("div","persona-send-button-tooltip");Ne.textContent=ft,F.appendChild(Ne)}return{micButton:q,micButtonWrapper:F}},cd=()=>{var g,b,S,W,F;if(!X||et)return;let c=(g=o.voiceRecognition)!=null?g:{};et={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((F=(W=c.iconSize)!=null?W:(S=o.sendButton)==null?void 0:S.size)!=null?F:"40")||24}},pd=(c,g)=>{var F,q,G,N,Se;if(!X)return;let b=X.querySelector("svg");b&&b.remove();let S=(Se=et==null?void 0:et.iconSize)!=null?Se:parseFloat((N=(G=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?G:(q=o.sendButton)==null?void 0:q.size)!=null?N:"40")||24,W=Ee(c,S,g,1.5);W&&X.appendChild(W)},Ii=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ts=()=>{var W;if(!X)return;cd();let c=(W=o.voiceRecognition)!=null?W:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,S=c.recordingBorderColor;if(Ii(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",X.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let F=X.querySelector("svg");F&&F.setAttribute("stroke",b)}S&&(X.style.borderColor=S),X.setAttribute("aria-label","Stop voice recognition")},rb=()=>{var G,N,Se,xe,se,ke,Ge,Te;if(!X)return;cd();let c=(G=o.voiceRecognition)!=null?G:{},g=U.getVoiceInterruptionMode(),b=(N=c.processingIconName)!=null?N:"loader",S=(xe=(Se=c.processingIconColor)!=null?Se:et==null?void 0:et.color)!=null?xe:"",W=(ke=(se=c.processingBackgroundColor)!=null?se:et==null?void 0:et.backgroundColor)!=null?ke:"",F=(Te=(Ge=c.processingBorderColor)!=null?Ge:et==null?void 0:et.borderColor)!=null?Te:"";Ii(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=W,X.style.borderColor=F;let q=S||"currentColor";X.style.color=q,pd(b,q),X.setAttribute("aria-label","Processing voice input"),g==="none"&&(X.style.cursor="default")},ob=()=>{var Se,xe,se,ke,Ge,Te,ft,Ze,bt,vt,He,Pe;if(!X)return;cd();let c=(Se=o.voiceRecognition)!=null?Se:{},g=U.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",S=(xe=c.speakingIconName)!=null?xe:b,W=(Te=c.speakingIconColor)!=null?Te:g==="barge-in"?(ke=(se=c.recordingIconColor)!=null?se:et==null?void 0:et.color)!=null?ke:"":(Ge=et==null?void 0:et.color)!=null?Ge:"",F=(bt=c.speakingBackgroundColor)!=null?bt:g==="barge-in"?(ft=c.recordingBackgroundColor)!=null?ft:"var(--persona-voice-recording-bg, #ef4444)":(Ze=et==null?void 0:et.backgroundColor)!=null?Ze:"",q=(Pe=c.speakingBorderColor)!=null?Pe:g==="barge-in"?(vt=c.recordingBorderColor)!=null?vt:"":(He=et==null?void 0:et.borderColor)!=null?He:"";Ii(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=F,X.style.borderColor=q;let G=W||"currentColor";X.style.color=G,pd(S,G);let N=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",N),g==="none"&&(X.style.cursor="default"),g==="barge-in"&&X.classList.add("persona-voice-recording")},Bn=()=>{var c,g,b;X&&(Ii(),et&&(X.style.backgroundColor=(c=et.backgroundColor)!=null?c:"",X.style.color=(g=et.color)!=null?g:"",X.style.borderColor=(b=et.borderColor)!=null?b:"",pd(et.iconName,et.color||"currentColor"),et=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},Hi=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=U.getVoiceStatus(),S=U.getVoiceInterruptionMode();if(S==="none"&&(b==="processing"||b==="speaking"))return;if(S==="cancel"&&(b==="processing"||b==="speaking")){U.stopVoicePlayback();return}if(U.isBargeInActive()){U.stopVoicePlayback(),U.deactivateBargeIn().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,So(),zo("user"),Bn()});return}U.toggleVoice().then(()=>{Lt.active=U.isVoiceActive(),Lt.manuallyDeactivated=!U.isVoiceActive(),So(),zo("user"),U.isVoiceActive()?Ts():Bn()});return}if(kt){let b=te.value.trim();Lt.manuallyDeactivated=!0,So(),Ur("user"),b&&(te.value="",te.style.height="auto",U.sendMessage(b))}else Lt.manuallyDeactivated=!1,So(),pr("user")};Tr=Hi,X&&(X.addEventListener("click",Hi),gt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(U.isVoiceActive()&&U.toggleVoice(),Bn()):Ur("system"),X&&X.removeEventListener("click",Hi)}));let nb=a.on("assistant:complete",()=>{fs&&(Lt.active||Lt.manuallyDeactivated||fs==="assistant"&&!Lt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!Lt.active&&!Lt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?U.toggleVoice().then(()=>{Lt.active=U.isVoiceActive(),zo("auto"),U.isVoiceActive()&&Ts()}):pr("auto"))},600))});gt.push(nb);let ab=a.on("action:resubmit",()=>{setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)});gt.push(ab);let _a=()=>{Gt(!P,"user")},xr=null,yr=null;if(M&&!H()){let c=n.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>di(o,_a).element,onToggle:_a});g&&(yr=g)}yr||(xr=di(o,_a))}xr?r.appendChild(xr.element):yr&&r.appendChild(yr),Wn(),nr(),ea(),Da(U.isStreaming()),xt()==="follow"?ln(!0):vs(),Ci(),L&&(!M||H()?setTimeout(()=>Oa(),0):P&&setTimeout(()=>Oa(),200));let Ms=()=>{var N,Se,xe,se,ke,Ge,Te,ft,Ze,bt,vt,He,Pe,Qe,ot,Ht,D,Ne,Fe,we,Qt,Kt;if(H()){Sr(),Wn();return}let c=Lr(o),g=(Se=(N=o.launcher)==null?void 0:N.sidebarMode)!=null?Se:!1,b=c||g||((se=(xe=o.launcher)==null?void 0:xe.fullHeight)!=null?se:!1),S=(ke=r.ownerDocument.defaultView)!=null?ke:window,W=(Te=(Ge=o.launcher)==null?void 0:Ge.mobileFullscreen)!=null?Te:!0,F=(Ze=(ft=o.launcher)==null?void 0:ft.mobileBreakpoint)!=null?Ze:640,q=S.innerWidth<=F,G=W&&q&&M;try{if(G){to(),Vn(r,o);return}if(E&&(E=!1,to(),Vn(r,o)),!M&&!c){le.style.height="",le.style.width="";return}if(!g&&!c){let ir=(vt=(bt=o==null?void 0:o.launcher)==null?void 0:bt.width)!=null?vt:o==null?void 0:o.launcherWidth,Bt=ir!=null?ir:Wo;le.style.width=Bt,le.style.maxWidth=Bt}if(qo(),!b){let ir=S.innerHeight,Bt=64,ar=(Pe=(He=o.launcher)==null?void 0:He.heightOffset)!=null?Pe:0,Po=Math.max(200,ir-Bt),wr=Math.min(640,Po),st=Math.max(200,wr-ar);le.style.height=`${st}px`}}finally{if(Sr(),Wn(),P&&M){let Bt=((Qe=r.ownerDocument.defaultView)!=null?Qe:window).innerWidth<=((Ht=(ot=o.launcher)==null?void 0:ot.mobileBreakpoint)!=null?Ht:640),ar=(Ne=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?Ne:!1,Po=(we=(Fe=o.launcher)==null?void 0:Fe.mobileFullscreen)!=null?we:!0,wr=Lr(o)&&Po&&Bt,st=ar||Po&&Bt&&M||wr;if(st&&!A){let Ut=r.getRootNode(),kr=Ut instanceof ShadowRoot?Ut.host:r.closest(".persona-host");kr&&!re&&(re=Jp(kr,(Kt=(Qt=o.launcher)==null?void 0:Qt.zIndex)!=null?Kt:so)),A=Zp(r.ownerDocument)}else st||(re==null||re(),re=null,A==null||A(),A=null)}}};Ms();let Iu=(Df=r.ownerDocument.defaultView)!=null?Df:window;if(Iu.addEventListener("resize",Ms),gt.push(()=>Iu.removeEventListener("resize",Ms)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Sr()});c.observe(ze),gt.push(()=>c.disconnect())}Lo=he.scrollTop;let Hu=Mn(he),sb=()=>{let c=he.getRootNode(),g=typeof c.getSelection=="function"?c.getSelection():null;return g!=null?g:he.ownerDocument.getSelection()},ud=()=>Ex(sb(),he),Wu=()=>{let c=he.scrollTop,g=Mn(he),b=g<Hu;if(Hu=g,xt()!=="follow"){Lo=c,To();return}let{action:S,nextLastScrollTop:W}=Il({following:Eo.isFollowing(),currentScrollTop:c,lastScrollTop:Lo,nearBottom:Aa(he,Ia),userScrollThreshold:bi,isAutoScrolling:Qo||Qn||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Lo=W,S==="resume"){ud()||sn();return}S==="pause"&&Ba()};if(he.addEventListener("scroll",Wu,{passive:!0}),gt.push(()=>he.removeEventListener("scroll",Wu)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ti()});c.observe(it),c.observe(he),gt.push(()=>c.disconnect())}let Bu=()=>{xt()==="follow"&&Eo.isFollowing()&&ud()&&Ba()},Du=he.ownerDocument;Du.addEventListener("selectionchange",Bu),gt.push(()=>{Du.removeEventListener("selectionchange",Bu)});let Ou=c=>{if(xt()!=="follow")return;let g=Hl({following:Eo.isFollowing(),deltaY:c.deltaY,nearBottom:Aa(he,Ia),resumeWhenNearBottom:!0});g==="pause"?Ba():g==="resume"&&!ud()&&sn()};he.addEventListener("wheel",Ou,{passive:!0}),gt.push(()=>he.removeEventListener("wheel",Ou)),tt.addEventListener("click",()=>{Jn(),he.scrollTop=he.scrollHeight,Lo=he.scrollTop,sn(),ln(!0),To()}),gt.push(()=>tt.remove()),gt.push(()=>{gs(),Jn()});let _u=()=>{O&&(ut&&(O.removeEventListener("click",ut),ut=null),I()?(O.style.display="",ut=()=>{Gt(!1,"user")},O.addEventListener("click",ut)):O.style.display="none")};_u(),(()=>{let{clearChatButton:c}=Re;c&&c.addEventListener("click",()=>{U.clearMessages(),Cr.clear(),sn(),zn(Re.composerOverlay);try{localStorage.removeItem(cs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==cs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},T.syncFromMetadata(),be==null||be.clear(),ye==null||ye.reset(),Y==null||Y.update()})})(),Rt&&Rt.addEventListener("submit",B),te==null||te.addEventListener("keydown",Vt),te==null||te.addEventListener("input",dt),te==null||te.addEventListener("paste",Rr);let Nu=(Of=r.ownerDocument)!=null?Of:document;Nu.addEventListener("keydown",Jt,!0);let Fu="persona-attachment-drop-active",ks=0,fd=()=>{ks=0,K.classList.remove(Fu)},Na=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&je!==null},Uu=c=>{!ad(c.dataTransfer)||!Na()||(ks++,ks===1&&K.classList.add(Fu))},qu=c=>{!ad(c.dataTransfer)||!Na()||(ks--,ks<=0&&fd())},zu=c=>{!ad(c.dataTransfer)||!Na()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},$u=c=>{var b;if(!ad(c.dataTransfer)||!Na())return;c.preventDefault(),c.stopPropagation(),fd();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&je.handleFiles(g)},Dn=!0;K.addEventListener("dragenter",Uu,Dn),K.addEventListener("dragleave",qu,Dn),r.addEventListener("dragover",zu,Dn),r.addEventListener("drop",$u,Dn);let Wi=r.ownerDocument,Vu=c=>{Na()&&c.preventDefault()},ju=c=>{Na()&&c.preventDefault()};Wi.addEventListener("dragover",Vu),Wi.addEventListener("drop",ju),gt.push(()=>{Rt&&Rt.removeEventListener("submit",B),te==null||te.removeEventListener("keydown",Vt),te==null||te.removeEventListener("input",dt),te==null||te.removeEventListener("paste",Rr),Nu.removeEventListener("keydown",Jt,!0)}),gt.push(()=>{K.removeEventListener("dragenter",Uu,Dn),K.removeEventListener("dragleave",qu,Dn),r.removeEventListener("dragover",zu,Dn),r.removeEventListener("drop",$u,Dn),Wi.removeEventListener("dragover",Vu),Wi.removeEventListener("drop",ju),fd()}),gt.push(()=>{U.cancel()}),xr?gt.push(()=>{xr==null||xr.destroy()}):yr&>.push(()=>{yr==null||yr.remove()});let Mr={update(c){var oo,ho,dn,qr,xo,yo,aa,Es,$f,Vf,jf,Gf,Kf,Xf,Qf,Yf,Jf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,Cm,wm,Am,Sm,Tm,Mm,km,Em,Lm,Pm,Rm,Im,Hm,Wm,Bm,Dm,Om,_m,Nm,Fm,Um,qm,zm,$m,Vm,jm,Gm,Km,Xm,Qm,Ym,Jm,Zm,eg,tg,rg,og,ng,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,vg,Cg,wg,Ag,Sg,Tg,Mg,kg,Eg,Lg,Pg,Rg,Ig,Hg,Wg,Bg,Dg,Og,_g,Ng,Fg,Ug,qg;let g=o.toolCall,b=o.messageActions,S=(oo=o.layout)==null?void 0:oo.messages,W=o.colorScheme,F=o.loadingIndicator,q=o.iterationDisplay,G=(ho=o.features)==null?void 0:ho.showReasoning,N=(dn=o.features)==null?void 0:dn.showToolCalls,Se=(qr=o.features)==null?void 0:qr.toolCallDisplay,xe=(xo=o.features)==null?void 0:xo.reasoningDisplay;o={...o,...c},to(),Vn(r,o),Ql(r,o),Yl(r,o),eo(),o.colorScheme!==W&&ue();let se=mi.getForInstance(o.plugins);n.length=0,n.push(...se),M=(aa=(yo=o.launcher)==null?void 0:yo.enabled)!=null?aa:!0,k=($f=(Es=o.launcher)==null?void 0:Es.autoExpand)!=null?$f:!1,Xe=(jf=(Vf=o.features)==null?void 0:Vf.showReasoning)!=null?jf:!0,Ae=(Kf=(Gf=o.features)==null?void 0:Gf.showToolCalls)!=null?Kf:!0,Me=(Qf=(Xf=o.features)==null?void 0:Xf.scrollToBottom)!=null?Qf:{};let ke=xt();Ue=(Jf=(Yf=o.features)==null?void 0:Yf.scrollBehavior)!=null?Jf:{},ke!==xt()&&(Jn(),sn()),Oo(),To();let Ge=We;if(We=(em=(Zf=o.features)==null?void 0:Zf.showEventStreamToggle)!=null?em:!1,We&&!Ge){if(be||(ne=new ui(Z),be=new pi(me,ne),ye=ye!=null?ye:new fi,ne.open().then(()=>be==null?void 0:be.restore()).catch(()=>{}),U.setSSEEventCallback((ee,Ot)=>{var er;(er=o.onSSEEvent)==null||er.call(o,ee,Ot),ye==null||ye.processEvent(ee,Ot),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Ot)})})),!At&&qe){let ee=(rm=(tm=o.features)==null?void 0:tm.eventStream)==null?void 0:rm.classNames,Ot="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"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");At=C("button",Ot),At.style.width="28px",At.style.height="28px",At.style.color=Ao.actionIconColor,At.type="button",At.setAttribute("aria-label","Event Stream"),At.title="Event Stream";let er=Ee("activity","18px","currentColor",1.5);er&&At.appendChild(er);let Ct=Re.clearChatButtonWrapper,qt=Re.closeButtonWrapper,Hr=Ct||qt;Hr&&Hr.parentNode===qe?qe.insertBefore(At,Hr):qe.appendChild(At),At.addEventListener("click",()=>{ge?lo():_o()})}}else!We&&Ge&&(lo(),At&&(At.remove(),At=null),be==null||be.clear(),ne==null||ne.destroy(),be=null,ne=null,ye==null||ye.reset(),ye=null);if(((om=o.launcher)==null?void 0:om.enabled)===!1&&xr&&(xr.destroy(),xr=null),((nm=o.launcher)==null?void 0:nm.enabled)===!1&&yr&&(yr.remove(),yr=null),((am=o.launcher)==null?void 0:am.enabled)!==!1&&!xr&&!yr){let ee=n.find(Ot=>Ot.renderLauncher);if(ee!=null&&ee.renderLauncher){let Ot=ee.renderLauncher({config:o,defaultRenderer:()=>di(o,_a).element,onToggle:_a});Ot&&(yr=Ot,r.appendChild(yr))}yr||(xr=di(o,_a),r.appendChild(xr.element))}xr&&xr.update(o),Ie&&((sm=o.launcher)==null?void 0:sm.title)!==void 0&&(Ie.textContent=o.launcher.title),Je&&((im=o.launcher)==null?void 0:im.subtitle)!==void 0&&(Je.textContent=o.launcher.subtitle);let Te=(lm=o.layout)==null?void 0:lm.header;if((Te==null?void 0:Te.layout)!==v&&qe){let ee=Te?os(o,Te,{showClose:I(),onClose:()=>Gt(!1,"user")}):kn({config:o,showClose:I(),onClose:()=>Gt(!1,"user")});qe.replaceWith(ee.header),qe=ee.header,fe=ee.iconHolder,Ie=ee.headerTitle,Je=ee.headerSubtitle,O=ee.closeButton,v=Te==null?void 0:Te.layout}else if(Te&&(fe&&(fe.style.display=Te.showIcon===!1?"none":""),Ie&&(Ie.style.display=Te.showTitle===!1?"none":""),Je&&(Je.style.display=Te.showSubtitle===!1?"none":""),O&&(O.style.display=Te.showCloseButton===!1?"none":""),Re.clearChatButtonWrapper)){let ee=Te.showClearChat;if(ee!==void 0){Re.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ot}=Re;Ot&&!Ot.classList.contains("persona-absolute")&&(ee?Ot.classList.remove("persona-ml-auto"):Ot.classList.add("persona-ml-auto"))}}let Ze=((dm=o.layout)==null?void 0:dm.showHeader)!==!1;qe&&(qe.style.display=Ze?"":"none");let bt=((cm=o.layout)==null?void 0:cm.showFooter)!==!1;ze&&(ze.style.display=bt?"":"none"),Sr(),To(),M!==w?M?Gt(k,"auto"):(P=!0,Wn()):k!==x&&Gt(k,"auto"),x=k,w=M,Ms(),_u();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),Qe=JSON.stringify(o.messageActions)!==JSON.stringify(b),ot=JSON.stringify((pm=o.layout)==null?void 0:pm.messages)!==JSON.stringify(S),Ht=((um=o.loadingIndicator)==null?void 0:um.render)!==(F==null?void 0:F.render)||((fm=o.loadingIndicator)==null?void 0:fm.renderIdle)!==(F==null?void 0:F.renderIdle)||((mm=o.loadingIndicator)==null?void 0:mm.showBubble)!==(F==null?void 0:F.showBubble),D=o.iterationDisplay!==q,Ne=((hm=(gm=o.features)==null?void 0:gm.showReasoning)!=null?hm:!0)!==(G!=null?G:!0)||((ym=(xm=o.features)==null?void 0:xm.showToolCalls)!=null?ym:!0)!==(N!=null?N:!0)||JSON.stringify((bm=o.features)==null?void 0:bm.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((vm=o.features)==null?void 0:vm.reasoningDisplay)!==JSON.stringify(xe);(Pe||Qe||ot||Ht||D||Ne)&&U&&(us++,Zn(it,U.getMessages(),ve));let we=(Cm=o.launcher)!=null?Cm:{},Qt=(wm=we.headerIconHidden)!=null?wm:!1,Kt=(Sm=(Am=o.layout)==null?void 0:Am.header)==null?void 0:Sm.showIcon,ir=Qt||Kt===!1,Bt=we.headerIconName,ar=(Tm=we.headerIconSize)!=null?Tm:"48px";if(fe){let ee=K.querySelector(".persona-border-b-persona-divider"),Ot=ee==null?void 0:ee.querySelector(".persona-flex-col");if(ir)fe.style.display="none",ee&&Ot&&!ee.contains(Ot)&&ee.insertBefore(Ot,ee.firstChild);else{if(fe.style.display="",fe.style.height=ar,fe.style.width=ar,ee&&Ot&&(ee.contains(fe)?fe.nextSibling!==Ot&&(fe.remove(),ee.insertBefore(fe,Ot)):ee.insertBefore(fe,Ot)),Bt){let Ct=parseFloat(ar)||24,qt=Ee(Bt,Ct*.6,"#ffffff",2);qt?fe.replaceChildren(qt):fe.textContent=(Mm=we.agentIconText)!=null?Mm:"\u{1F4AC}"}else if(we.iconUrl){let Ct=fe.querySelector("img");if(Ct)Ct.src=we.iconUrl,Ct.style.height=ar,Ct.style.width=ar;else{let qt=document.createElement("img");qt.src=we.iconUrl,qt.alt="",qt.className="persona-rounded-xl persona-object-cover",qt.style.height=ar,qt.style.width=ar,fe.replaceChildren(qt)}}else{let Ct=fe.querySelector("svg"),qt=fe.querySelector("img");(Ct||qt)&&fe.replaceChildren(),fe.textContent=(km=we.agentIconText)!=null?km:"\u{1F4AC}"}let er=fe.querySelector("img");er&&(er.style.height=ar,er.style.width=ar)}}let Po=(Lm=(Em=o.layout)==null?void 0:Em.header)==null?void 0:Lm.showTitle,wr=(Rm=(Pm=o.layout)==null?void 0:Pm.header)==null?void 0:Rm.showSubtitle;if(Ie&&(Ie.style.display=Po===!1?"none":""),Je&&(Je.style.display=wr===!1?"none":""),O){((Hm=(Im=o.layout)==null?void 0:Im.header)==null?void 0:Hm.showCloseButton)===!1?O.style.display="none":O.style.display="";let Ot=(Wm=we.closeButtonSize)!=null?Wm:"32px",er=(Bm=we.closeButtonPlacement)!=null?Bm:"inline";O.style.height=Ot,O.style.width=Ot;let{closeButtonWrapper:Ct}=Re,qt=er==="top-right",Hr=Ct==null?void 0:Ct.classList.contains("persona-absolute");if(Ct&&qt!==Hr)if(Ct.remove(),qt)Ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",K.style.position="relative",K.appendChild(Ct);else{let St=(Om=(Dm=we.clearChat)==null?void 0:Dm.placement)!=null?Om:"inline",Wr=(Nm=(_m=we.clearChat)==null?void 0:_m.enabled)!=null?Nm:!0;Ct.className=Wr&&St==="inline"?"":"persona-ml-auto";let Mo=K.querySelector(".persona-border-b-persona-divider");Mo&&Mo.appendChild(Ct)}if(O.style.color=we.closeButtonColor||Ao.actionIconColor,we.closeButtonBackgroundColor?(O.style.backgroundColor=we.closeButtonBackgroundColor,O.classList.remove("hover:persona-bg-gray-100")):(O.style.backgroundColor="",O.classList.add("hover:persona-bg-gray-100")),we.closeButtonBorderWidth||we.closeButtonBorderColor){let St=we.closeButtonBorderWidth||"0px",Wr=we.closeButtonBorderColor||"transparent";O.style.border=`${St} solid ${Wr}`,O.classList.remove("persona-border-none")}else O.style.border="",O.classList.add("persona-border-none");we.closeButtonBorderRadius?(O.style.borderRadius=we.closeButtonBorderRadius,O.classList.remove("persona-rounded-full")):(O.style.borderRadius="",O.classList.add("persona-rounded-full")),we.closeButtonPaddingX?(O.style.paddingLeft=we.closeButtonPaddingX,O.style.paddingRight=we.closeButtonPaddingX):(O.style.paddingLeft="",O.style.paddingRight=""),we.closeButtonPaddingY?(O.style.paddingTop=we.closeButtonPaddingY,O.style.paddingBottom=we.closeButtonPaddingY):(O.style.paddingTop="",O.style.paddingBottom="");let no=(Fm=we.closeButtonIconName)!=null?Fm:"x",Jo=(Um=we.closeButtonIconText)!=null?Um:"\xD7";O.innerHTML="";let bo=Ee(no,"28px","currentColor",1);bo?O.appendChild(bo):O.textContent=Jo;let br=(qm=we.closeButtonTooltipText)!=null?qm:"Close chat",Io=(zm=we.closeButtonShowTooltip)!=null?zm:!0;if(O.setAttribute("aria-label",br),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),Io&&br)){let St=null,Wr=()=>{if(St||!O)return;let sa=O.ownerDocument,Ls=sa.body;if(!Ls)return;St=un(sa,"div","persona-clear-chat-tooltip"),St.textContent=br;let Ps=un(sa,"div");Ps.className="persona-clear-chat-tooltip-arrow",St.appendChild(Ps);let ia=O.getBoundingClientRect();St.style.position="fixed",St.style.zIndex=String(jn),St.style.left=`${ia.left+ia.width/2}px`,St.style.top=`${ia.top-8}px`,St.style.transform="translate(-50%, -100%)",Ls.appendChild(St)},Mo=()=>{St&&St.parentNode&&(St.parentNode.removeChild(St),St=null)};Ct.addEventListener("mouseenter",Wr),Ct.addEventListener("mouseleave",Mo),O.addEventListener("focus",Wr),O.addEventListener("blur",Mo),Ct._cleanupTooltip=()=>{Mo(),Ct&&(Ct.removeEventListener("mouseenter",Wr),Ct.removeEventListener("mouseleave",Mo)),O&&(O.removeEventListener("focus",Wr),O.removeEventListener("blur",Mo))}}}let{clearChatButton:st,clearChatButtonWrapper:Ut}=Re;if(st){let ee=($m=we.clearChat)!=null?$m:{},Ot=(Vm=ee.enabled)!=null?Vm:!0,er=(Gm=(jm=o.layout)==null?void 0:jm.header)==null?void 0:Gm.showClearChat,Ct=er!==void 0?er:Ot,qt=(Km=ee.placement)!=null?Km:"inline";if(Ut){Ut.style.display=Ct?"":"none";let{closeButtonWrapper:Hr}=Re;!H()&&Hr&&!Hr.classList.contains("persona-absolute")&&(Ct?Hr.classList.remove("persona-ml-auto"):Hr.classList.add("persona-ml-auto"));let no=qt==="top-right",Jo=Ut.classList.contains("persona-absolute");if(!H()&&no!==Jo&&Ct){if(Ut.remove(),no)Ut.className="persona-absolute persona-top-4 persona-z-50",Ut.style.right="48px",K.style.position="relative",K.appendChild(Ut);else{Ut.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ut.style.right="";let br=K.querySelector(".persona-border-b-persona-divider"),Io=Re.closeButtonWrapper;br&&Io&&Io.parentElement===br?br.insertBefore(Ut,Io):br&&br.appendChild(Ut)}let bo=Re.closeButtonWrapper;bo&&!bo.classList.contains("persona-absolute")&&(no?bo.classList.add("persona-ml-auto"):bo.classList.remove("persona-ml-auto"))}}if(Ct){if(!H()){let St=(Xm=ee.size)!=null?Xm:"32px";st.style.height=St,st.style.width=St}let Hr=(Qm=ee.iconName)!=null?Qm:"refresh-cw",no=(Ym=ee.iconColor)!=null?Ym:"";st.style.color=no||Ao.actionIconColor,st.innerHTML="";let Jo=H()?"14px":"20px",bo=Ee(Hr,Jo,"currentColor",2);if(bo&&st.appendChild(bo),ee.backgroundColor?(st.style.backgroundColor=ee.backgroundColor,st.classList.remove("hover:persona-bg-gray-100")):(st.style.backgroundColor="",st.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let St=ee.borderWidth||"0px",Wr=ee.borderColor||"transparent";st.style.border=`${St} solid ${Wr}`,st.classList.remove("persona-border-none")}else st.style.border="",st.classList.add("persona-border-none");ee.borderRadius?(st.style.borderRadius=ee.borderRadius,st.classList.remove("persona-rounded-full")):(st.style.borderRadius="",st.classList.add("persona-rounded-full")),ee.paddingX?(st.style.paddingLeft=ee.paddingX,st.style.paddingRight=ee.paddingX):(st.style.paddingLeft="",st.style.paddingRight=""),ee.paddingY?(st.style.paddingTop=ee.paddingY,st.style.paddingBottom=ee.paddingY):(st.style.paddingTop="",st.style.paddingBottom="");let br=(Jm=ee.tooltipText)!=null?Jm:"Clear chat",Io=(Zm=ee.showTooltip)!=null?Zm:!0;if(st.setAttribute("aria-label",br),Ut&&(Ut._cleanupTooltip&&(Ut._cleanupTooltip(),delete Ut._cleanupTooltip),Io&&br)){let St=null,Wr=()=>{if(St||!st)return;let sa=st.ownerDocument,Ls=sa.body;if(!Ls)return;St=un(sa,"div","persona-clear-chat-tooltip"),St.textContent=br;let Ps=un(sa,"div");Ps.className="persona-clear-chat-tooltip-arrow",St.appendChild(Ps);let ia=st.getBoundingClientRect();St.style.position="fixed",St.style.zIndex=String(jn),St.style.left=`${ia.left+ia.width/2}px`,St.style.top=`${ia.top-8}px`,St.style.transform="translate(-50%, -100%)",Ls.appendChild(St)},Mo=()=>{St&&St.parentNode&&(St.parentNode.removeChild(St),St=null)};Ut.addEventListener("mouseenter",Wr),Ut.addEventListener("mouseleave",Mo),st.addEventListener("focus",Wr),st.addEventListener("blur",Mo),Ut._cleanupTooltip=()=>{Mo(),Ut&&(Ut.removeEventListener("mouseenter",Wr),Ut.removeEventListener("mouseleave",Mo)),st&&(st.removeEventListener("focus",Wr),st.removeEventListener("blur",Mo))}}}}let kr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[gi],Vo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ea.message,Ea.messageAndClick];T=hi({parsers:kr,handlers:Vo,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),ve=my(o,T,ie),U.updateConfig(o),Zn(it,U.getMessages(),ve),nr(),ea(),Da(U.isStreaming());let Ro=((eg=o.voiceRecognition)==null?void 0:eg.enabled)===!0,ta=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ra=((rg=(tg=o.voiceRecognition)==null?void 0:tg.provider)==null?void 0:rg.type)==="runtype";if(Ro&&(ta||ra))if(!X||!wt){let ee=tb(o.voiceRecognition,o.sendButton);ee&&(X=ee.micButton,wt=ee.micButtonWrapper,Dt.insertBefore(wt,Ar),X.addEventListener("click",Hi),X.disabled=U.isStreaming())}else{let ee=(og=o.voiceRecognition)!=null?og:{},Ot=(ng=o.sendButton)!=null?ng:{},er=(ag=ee.iconName)!=null?ag:"mic",Ct=(sg=Ot.size)!=null?sg:"40px",qt=(ig=ee.iconSize)!=null?ig:Ct,Hr=parseFloat(qt)||24;X.style.width=qt,X.style.height=qt,X.style.minWidth=qt,X.style.minHeight=qt;let no=(dg=(lg=ee.iconColor)!=null?lg:Ot.textColor)!=null?dg:"currentColor";X.innerHTML="";let Jo=Ee(er,Hr,no,2);Jo?X.appendChild(Jo):X.textContent="\u{1F3A4}";let bo=(cg=ee.backgroundColor)!=null?cg:Ot.backgroundColor;bo?X.style.backgroundColor=bo:X.style.backgroundColor="",no?X.style.color=no:X.style.color="var(--persona-text, #111827)",ee.borderWidth?(X.style.borderWidth=ee.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),ee.borderColor?X.style.borderColor=ee.borderColor:X.style.borderColor="",ee.paddingX?(X.style.paddingLeft=ee.paddingX,X.style.paddingRight=ee.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),ee.paddingY?(X.style.paddingTop=ee.paddingY,X.style.paddingBottom=ee.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let br=wt==null?void 0:wt.querySelector(".persona-send-button-tooltip"),Io=(pg=ee.tooltipText)!=null?pg:"Start voice recognition";if(((ug=ee.showTooltip)!=null?ug:!1)&&Io)if(br)br.textContent=Io,br.style.display="";else{let Wr=document.createElement("div");Wr.className="persona-send-button-tooltip",Wr.textContent=Io,wt==null||wt.insertBefore(Wr,X)}else br&&(br.style.display="none");wt.style.display="",X.disabled=U.isStreaming()}else X&&wt&&(wt.style.display="none",((mg=(fg=o.voiceRecognition)==null?void 0:fg.provider)==null?void 0:mg.type)==="runtype"?U.isVoiceActive()&&U.toggleVoice():kt&&Ur());if(((gg=o.attachments)==null?void 0:gg.enabled)===!0)if(!Ce||!ct){let ee=(hg=o.attachments)!=null?hg:{},er=(yg=((xg=o.sendButton)!=null?xg:{}).size)!=null?yg:"40px";rt||(rt=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),rt.style.display="none",Rt.insertBefore(rt,te)),de||(de=document.createElement("input"),de.type="file",de.accept=((bg=ee.allowedTypes)!=null?bg:Tn).join(","),de.multiple=((vg=ee.maxFiles)!=null?vg:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),Rt.insertBefore(de,te)),Ce=C("div","persona-send-button-wrapper"),ct=C("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ct.type="button",ct.setAttribute("aria-label",(Cg=ee.buttonTooltipText)!=null?Cg:"Attach file");let Ct=(wg=ee.buttonIconName)!=null?wg:"paperclip",qt=er,Hr=parseFloat(qt)||40,no=Math.round(Hr*.6);ct.style.width=qt,ct.style.height=qt,ct.style.minWidth=qt,ct.style.minHeight=qt,ct.style.fontSize="18px",ct.style.lineHeight="1",ct.style.backgroundColor="transparent",ct.style.color="var(--persona-primary, #111827)",ct.style.border="none",ct.style.borderRadius="6px",ct.style.transition="background-color 0.15s ease",ct.addEventListener("mouseenter",()=>{ct.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ct.addEventListener("mouseleave",()=>{ct.style.backgroundColor="transparent"});let Jo=Ee(Ct,no,"currentColor",1.5);Jo?ct.appendChild(Jo):ct.textContent="\u{1F4CE}",ct.addEventListener("click",Io=>{Io.preventDefault(),de==null||de.click()}),Ce.appendChild(ct);let bo=(Ag=ee.buttonTooltipText)!=null?Ag:"Attach file",br=C("div","persona-send-button-tooltip");br.textContent=bo,Ce.appendChild(br),Mt.append(Ce),!je&&de&&rt&&(je=wa.fromConfig(ee),je.setPreviewsContainer(rt),de.addEventListener("change",async()=>{je&&(de!=null&&de.files)&&(await je.handleFileSelect(de.files),de.value="")})),K.querySelector(".persona-attachment-drop-overlay")||K.appendChild(gy(ee.dropOverlay))}else{Ce.style.display="";let ee=(Sg=o.attachments)!=null?Sg:{};de&&(de.accept=((Tg=ee.allowedTypes)!=null?Tg:Tn).join(","),de.multiple=((Mg=ee.maxFiles)!=null?Mg:4)>1),je&&je.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else Ce&&(Ce.style.display="none"),je&&je.clearAttachments(),(kg=K.querySelector(".persona-attachment-drop-overlay"))==null||kg.remove();let ur=(Eg=o.sendButton)!=null?Eg:{},oa=(Lg=ur.useIcon)!=null?Lg:!1,On=(Pg=ur.iconText)!=null?Pg:"\u2191",_n=ur.iconName,yn=(Rg=ur.tooltipText)!=null?Rg:"Send message",na=(Ig=ur.showTooltip)!=null?Ig:!1,Yo=(Hg=ur.size)!=null?Hg:"40px",pt=ur.backgroundColor,Ir=ur.textColor;if(oa){if(_e.style.width=Yo,_e.style.height=Yo,_e.style.minWidth=Yo,_e.style.minHeight=Yo,_e.style.fontSize="18px",_e.style.lineHeight="1",_e.innerHTML="",Ir?_e.style.color=Ir:_e.style.color="var(--persona-button-primary-fg, #ffffff)",_n){let ee=parseFloat(Yo)||24,Ot=(Ir==null?void 0:Ir.trim())||"currentColor",er=Ee(_n,ee,Ot,2);er?_e.appendChild(er):_e.textContent=On}else _e.textContent=On;_e.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",pt?(_e.style.backgroundColor=pt,_e.classList.remove("persona-bg-persona-primary")):(_e.style.backgroundColor="",_e.classList.add("persona-bg-persona-primary"))}else _e.textContent=(Bg=(Wg=o.copy)==null?void 0:Wg.sendButtonLabel)!=null?Bg:"Send",_e.style.width="",_e.style.height="",_e.style.minWidth="",_e.style.minHeight="",_e.style.fontSize="",_e.style.lineHeight="",_e.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",pt?(_e.style.backgroundColor=pt,_e.classList.remove("persona-bg-persona-accent")):_e.classList.add("persona-bg-persona-accent"),Ir?_e.style.color=Ir:_e.classList.add("persona-text-white");ur.borderWidth?(_e.style.borderWidth=ur.borderWidth,_e.style.borderStyle="solid"):(_e.style.borderWidth="",_e.style.borderStyle=""),ur.borderColor?_e.style.borderColor=ur.borderColor:_e.style.borderColor="",ur.paddingX?(_e.style.paddingLeft=ur.paddingX,_e.style.paddingRight=ur.paddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),ur.paddingY?(_e.style.paddingTop=ur.paddingY,_e.style.paddingBottom=ur.paddingY):(_e.style.paddingTop="",_e.style.paddingBottom="");let Zt=Ar==null?void 0:Ar.querySelector(".persona-send-button-tooltip");if(na&&yn)if(Zt)Zt.textContent=yn,Zt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=yn,Ar==null||Ar.insertBefore(ee,_e)}else Zt&&(Zt.style.display="none");let Yt=(Fg=(Dg=o.layout)==null?void 0:Dg.contentMaxWidth)!=null?Fg:H()?(Ng=(_g=(Og=o.launcher)==null?void 0:Og.composerBar)==null?void 0:_g.contentMaxWidth)!=null?Ng:"720px":void 0;Yt?(it.style.maxWidth=Yt,it.style.marginLeft="auto",it.style.marginRight="auto",it.style.width="100%",Rt&&(Rt.style.maxWidth=Yt,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Yt,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight="",it.style.width="",Rt&&(Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let Et=(Ug=o.statusIndicator)!=null?Ug:{},fr=(qg=Et.visible)!=null?qg:!0;if(dr.style.display=fr?"":"none",U){let ee=U.getStatus();Ye(dr,(er=>{var Ct,qt,Hr,no;return er==="idle"?(Ct=Et.idleText)!=null?Ct:ao.idle:er==="connecting"?(qt=Et.connectingText)!=null?qt:ao.connecting:er==="connected"?(Hr=Et.connectedText)!=null?Hr:ao.connected:er==="error"?(no=Et.errorText)!=null?no:ao.error:ao[er]})(ee),Et,ee)}dr.classList.remove("persona-text-left","persona-text-center","persona-text-right");let _t=Et.align==="left"?"persona-text-left":Et.align==="center"?"persona-text-center":"persona-text-right";dr.classList.add(_t)},open(){I()&&Gt(!0,"api")},close(){I()&&Gt(!1,"api")},toggle(){I()&&Gt(!P,"api")},clearChat(){Or=!1,U.clearMessages(),Cr.clear(),sn();try{localStorage.removeItem(cs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==cs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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={},T.syncFromMetadata(),be==null||be.clear(),ye==null||ye.reset(),Y==null||Y.update()},setMessage(c){return!te||U.isStreaming()?!1:(!P&&I()&&Gt(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(U.isStreaming())return!1;let g=(c==null?void 0:c.trim())||te.value.trim();return g?(!P&&I()&&Gt(!0,"system"),te.value="",te.style.height="auto",U.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return U.isStreaming()?!1:((b=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(U.isVoiceActive()||(!P&&I()&&Gt(!0,"system"),Lt.manuallyDeactivated=!1,So(),U.toggleVoice().then(()=>{Lt.active=U.isVoiceActive(),zo("user"),U.isVoiceActive()&&Ts()})),!0):kt?!0:jr()?(!P&&I()&&Gt(!0,"system"),Lt.manuallyDeactivated=!1,So(),pr("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?U.isVoiceActive()?(U.toggleVoice().then(()=>{Lt.active=!1,Lt.manuallyDeactivated=!0,So(),zo("user"),Bn()}),!0):!1:kt?(Lt.manuallyDeactivated=!0,So(),Ur("user"),!0):!1},injectMessage(c){return!P&&I()&&Gt(!0,"system"),U.injectMessage(c)},injectAssistantMessage(c){!P&&I()&&Gt(!0,"system");let g=U.injectAssistantMessage(c);return z&&(z=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)),g},injectUserMessage(c){return!P&&I()&&Gt(!0,"system"),U.injectUserMessage(c)},injectSystemMessage(c){return!P&&I()&&Gt(!0,"system"),U.injectSystemMessage(c)},injectMessageBatch(c){return!P&&I()&&Gt(!0,"system"),U.injectMessageBatch(c)},injectComponentDirective(c){return!P&&I()&&Gt(!0,"system"),U.injectComponentDirective(c)},injectTestMessage(c){!P&&I()&&Gt(!0,"system"),U.injectTestEvent(c)},async connectStream(c,g){return U.connectStream(c,g)},__pushEventStreamEvent(c){be&&(ye==null||ye.processEvent(c.type,c.payload),be.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||!be||_o()},hideEventStream(){ge&&lo()},isEventStreamVisible(){return ge},showArtifacts(){Go(o)&&(Or=!1,eo(),mt==null||mt.setMobileOpen(!0))},hideArtifacts(){Go(o)&&(Or=!0,eo())},upsertArtifact(c){return Go(o)?(Or=!1,U.upsertArtifact(c)):null},selectArtifact(c){Go(o)&&U.selectArtifact(c)},clearArtifacts(){Go(o)&&U.clearArtifacts()},getArtifacts(){var c;return(c=U==null?void 0:U.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=U==null?void 0:U.getSelectedArtifactId())!=null?c:null},focusInput(){return M&&!P&&!H()||!te?!1:(te.focus(),!0)},async resolveApproval(c,g,b){let W=U.getMessages().find(F=>{var q;return F.variant==="approval"&&((q=F.approval)==null?void 0:q.id)===c});if(!(W!=null&&W.approval))throw new Error(`Approval not found: ${c}`);if(W.approval.toolType==="webmcp"){U.resolveWebMcpApproval(W.id,g);return}return U.resolveApproval(W.approval,g,b)},getMessages(){return U.getMessages()},getStatus(){return U.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return a.on(c,g)},off(c,g){a.off(c,g)},isOpen(){return I()&&P},isVoiceActive(){return Lt.active},getState(){return{open:I()&&P,launcherEnabled:M,voiceActive:Lt.active,streaming:U.isStreaming()}},showCSATFeedback(c){!P&&I()&&Gt(!0,"system");let g=it.querySelector(".persona-feedback-container");g&&g.remove();let b=od({onSubmit:async(S,W)=>{var F;U.isClientTokenMode()&&await U.submitCSATFeedback(S,W),(F=c==null?void 0:c.onSubmit)==null||F.call(c,S,W)},onDismiss:c==null?void 0:c.onDismiss,...c});it.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!P&&I()&&Gt(!0,"system");let g=it.querySelector(".persona-feedback-container");g&&g.remove();let b=nd({onSubmit:async(S,W)=>{var F;U.isClientTokenMode()&&await U.submitNPSFeedback(S,W),(F=c==null?void 0:c.onSubmit)==null||F.call(c,S,W)},onDismiss:c==null?void 0:c.onDismiss,...c});it.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return U.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return U.submitNPSFeedback(c,g)},destroy(){Ke!=null&&(clearInterval(Ke),Ke=null),gt.forEach(c=>c()),De.remove(),nt==null||nt.remove(),xr==null||xr.destroy(),yr==null||yr.remove(),ut&&O.removeEventListener("click",ut)}};if((((_f=t==null?void 0:t.debugTools)!=null?_f:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Mr,getMessages:Mr.getMessages,getStatus:Mr.getStatus,getMetadata:Mr.getPersistentMetadata,updateMetadata:Mr.updatePersistentMetadata,clearHistory:()=>Mr.clearChat(),setVoiceActive:b=>b?Mr.startVoiceRecognition():Mr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,gt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=r.getAttribute("data-persona-instance")||r.id||"persona-"+Math.random().toString(36).slice(2,8),g=G=>{let N=G.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Mr.focusInput()};if(window.addEventListener("persona:focusInput",g),gt.push(()=>{window.removeEventListener("persona:focusInput",g)}),We){let G=Se=>{let xe=Se.detail;(!(xe!=null&&xe.instanceId)||xe.instanceId===c)&&Mr.showEventStream()},N=Se=>{let xe=Se.detail;(!(xe!=null&&xe.instanceId)||xe.instanceId===c)&&Mr.hideEventStream()};window.addEventListener("persona:showEventStream",G),window.addEventListener("persona:hideEventStream",N),gt.push(()=>{window.removeEventListener("persona:showEventStream",G),window.removeEventListener("persona:hideEventStream",N)})}let b=G=>{let N=G.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Mr.showArtifacts()},S=G=>{let N=G.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Mr.hideArtifacts()},W=G=>{let N=G.detail;N!=null&&N.instanceId&&N.instanceId!==c||N!=null&&N.artifact&&Mr.upsertArtifact(N.artifact)},F=G=>{let N=G.detail;N!=null&&N.instanceId&&N.instanceId!==c||typeof(N==null?void 0:N.id)=="string"&&Mr.selectArtifact(N.id)},q=G=>{let N=G.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&Mr.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",S),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",q),gt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",S),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",q)})}let $o=ZC(o.persistState);if($o&&I()){let c=ew($o.storage),g=`${$o.keyPrefix}widget-open`,b=`${$o.keyPrefix}widget-voice`,S=`${$o.keyPrefix}widget-voice-mode`;if(c){let W=((Nf=$o.persist)==null?void 0:Nf.openState)&&c.getItem(g)==="true",F=((Ff=$o.persist)==null?void 0:Ff.voiceState)&&c.getItem(b)==="true",q=((Uf=$o.persist)==null?void 0:Uf.voiceState)&&c.getItem(S)==="true";if(W&&setTimeout(()=>{Mr.open(),setTimeout(()=>{var G;if(F||q)Mr.startVoiceRecognition();else if((G=$o.persist)!=null&&G.focusInput){let N=r.querySelector("textarea");N&&N.focus()}},100)},0),(qf=$o.persist)!=null&&qf.openState&&(a.on("widget:opened",()=>{c.setItem(g,"true")}),a.on("widget:closed",()=>{c.setItem(g,"false")})),(zf=$o.persist)!=null&&zf.voiceState&&(a.on("voice:state",G=>{c.setItem(b,G.active?"true":"false")}),a.on("user:message",G=>{c.setItem(S,G.viaVoice?"true":"false")})),$o.clearOnChatClear){let G=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(S)},N=()=>G();window.addEventListener("persona:clear-chat",N),gt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return u&&I()&&setTimeout(()=>{Mr.open()},0),xn(),Mr};var tw=(r,e)=>{let t=r.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(t);return n?Math.max(0,e*parseFloat(n[1])/100):420},rw=(r,e)=>{if(e===!1){r.style.maxHeight="";return}r.style.maxHeight="100vh",r.style.maxHeight=e},ow=(r,e)=>{e===!1?(r.style.position="relative",r.style.top=""):(r.style.position="sticky",r.style.top="0")},nw=(r,e)=>{let t=r.parentElement;if(!t)return;let o=r.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!n||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},hy=(r,e)=>{var o,n;let t=(n=(o=e==null?void 0:e.launcher)==null?void 0:o.enabled)!=null?n:!0;r.className="persona-host",r.style.height=t?"":"100%",r.style.display=t?"":"flex",r.style.flexDirection=t?"":"column",r.style.flex=t?"":"1 1 auto",r.style.minHeight=t?"":"0"},bu=r=>{r.style.position="",r.style.top="",r.style.bottom="",r.style.left="",r.style.right="",r.style.zIndex="",r.style.transform="",r.style.pointerEvents=""},xy=r=>{r.style.inset="",r.style.width="",r.style.height="",r.style.maxWidth="",r.style.maxHeight="",r.style.minWidth="",bu(r)},hu=r=>{r.style.transition=""},xu=r=>{r.style.display="",r.style.flexDirection="",r.style.flex="",r.style.minHeight="",r.style.minWidth="",r.style.width="",r.style.height="",r.style.alignItems="",r.style.transition="",r.style.transform="",r.style.marginLeft=""},yu=r=>{r.style.width="",r.style.maxWidth="",r.style.minWidth="",r.style.flex="1 1 auto"},id=(r,e)=>{r.style.width="",r.style.minWidth="",r.style.maxWidth="",r.style.boxSizing="",e.style.alignItems=""},aw=(r,e,t,o,n)=>{n?t.parentElement!==e&&(r.replaceChildren(),e.replaceChildren(t,o),r.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),r.appendChild(t),r.appendChild(o))},sw=(r,e,t,o,n,a)=>{let s=a?e:r;n==="left"?s.firstElementChild!==o&&s.replaceChildren(o,t):s.lastElementChild!==o&&s.replaceChildren(t,o)},yy=(r,e,t,o,n,a,s)=>{var y,h,T,M,k,L;let i=Bo(a),d=i.reveal==="push";aw(r,e,t,o,d),sw(r,e,t,o,i.side,d),r.dataset.personaHostLayout="docked",r.dataset.personaDockSide=i.side,r.dataset.personaDockOpen=s?"true":"false",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.height="100%",r.style.minHeight="0",r.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let l=r.ownerDocument.defaultView,u=(h=(y=a==null?void 0:a.launcher)==null?void 0:y.mobileFullscreen)!=null?h:!0,f=(M=(T=a==null?void 0:a.launcher)==null?void 0:T.mobileBreakpoint)!=null?M:640,p=l!=null?l.innerWidth<=f:!1;if(u&&p&&s){r.dataset.personaDockMobileFullscreen="true",r.removeAttribute("data-persona-dock-reveal"),xu(e),hu(o),xy(o),yu(t),id(n,o),r.style.display="flex",r.style.flexDirection="column",r.style.alignItems="stretch",r.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((L=(k=a==null?void 0:a.launcher)==null?void 0:k.zIndex)!=null?L:so),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(r.removeAttribute("data-persona-dock-mobile-fullscreen"),xy(o),rw(o,i.maxHeight),i.reveal==="overlay"){r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="hidden",r.dataset.personaDockReveal="overlay",xu(e),hu(o),yu(t),id(n,o);let x=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=s?"translateX(0)":w;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=x,o.style.transform=v,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="hidden",r.dataset.personaDockReveal="push",hu(o),bu(o),id(n,o);let x=tw(i.width,r.clientWidth),w=Math.max(0,r.clientWidth),v=i.animate?"margin-left 180ms ease":"none",E=i.side==="right"?s?-x:0:s?0:-x;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${w+x}px`,e.style.transition=v,e.style.marginLeft=`${E}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${w}px`,t.style.maxWidth=`${w}px`,t.style.minWidth=`${w}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{r.style.display="flex",r.style.flexDirection="row",r.style.alignItems="stretch",r.style.overflow="",xu(e),bu(o),yu(t),id(n,o);let x=i.reveal==="emerge";x?r.dataset.personaDockReveal="emerge":r.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${w}`,o.style.width=w,o.style.maxWidth=w,o.style.minWidth=w,o.style.minHeight="0",ow(o,i.maxHeight),o.style.overflow=x||E?"hidden":"visible",o.style.transition=v,x&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},iw=(r,e)=>{let t=r.ownerDocument.createElement("div");return hy(t,e),r.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(o){hy(t,o)},destroy(){t.remove()}}},lw=(r,e)=>{var L,x,w,v;let{ownerDocument:t}=r,o=r.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=r.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=r.nextSibling,s=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),f=(x=(L=e==null?void 0:e.launcher)==null?void 0:L.enabled)==null||x?(v=(w=e==null?void 0:e.launcher)==null?void 0:w.autoExpand)!=null?v:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),o.insertBefore(s,r),d.appendChild(r);let p=null,m=()=>{p==null||p.disconnect(),p=null},y=()=>{m(),Bo(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(p=new ResizeObserver(()=>{yy(s,i,d,l,u,e,f)}),p.observe(s))},h=!1,T=()=>{yy(s,i,d,l,u,e,f),y(),f&&!h&&s.dataset.personaDockMobileFullscreen!=="true"&&(h=!0,nw(s,Bo(e)))},M=s.ownerDocument.defaultView,k=()=>{T()};return M==null||M.addEventListener("resize",k),Bo(e).reveal==="push"?(i.appendChild(d),i.appendChild(l),s.appendChild(i)):(s.appendChild(d),s.appendChild(l)),T(),{mode:"docked",host:u,shell:s,syncWidgetState(E){let H=E.launcherEnabled?E.open:!0;f!==H&&(f=H,T())},updateConfig(E){var H,I;e=E,((I=(H=e==null?void 0:e.launcher)==null?void 0:H.enabled)!=null?I:!0)===!1&&(f=!0),T()},destroy(){M==null||M.removeEventListener("resize",k),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(r,a):o.appendChild(r)),s.remove()}}},xi=(r,e)=>Lr(e)?lw(r,e):iw(r,e);var vu={},by=!1,dw=r=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof r=="string"){let e=document.querySelector(r);if(!e)throw new Error(`Chat widget target "${r}" was not found`);return e}return r},cw=()=>{try{if(typeof vu!="undefined"&&vu.url)return new URL("../widget.css",vu.url).href}catch{}return null},vy=(r,e)=>{let t=cw(),o=()=>{if(!(r instanceof ShadowRoot)||r.querySelector("link[data-persona]"))return;let n=e.head.querySelector("link[data-persona]");if(!n)return;let a=n.cloneNode(!0);r.insertBefore(a,r.firstChild)};if(r instanceof ShadowRoot)if(t){let n=e.createElement("link");n.rel="stylesheet",n.href=t,n.setAttribute("data-persona","true"),r.insertBefore(n,r.firstChild)}else o();else if(!e.head.querySelector("link[data-persona]")&&t){let a=e.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),e.head.appendChild(a)}},Cy=r=>{let e=dw(r.target),t=r.useShadowDom===!0,o=e.ownerDocument,n=r.config,a=xi(e,n),s,i=[],d=(T,M)=>{var w,v;let L=!((v=(w=M==null?void 0:M.launcher)==null?void 0:w.enabled)!=null?v:!0)||Lr(M),x=o.createElement("div");if(x.setAttribute("data-persona-root","true"),L&&(x.style.height="100%",x.style.display="flex",x.style.flexDirection="column",x.style.flex="1",x.style.minHeight="0"),t){let E=T.attachShadow({mode:"open"});E.appendChild(x),vy(E,o)}else T.appendChild(x),vy(T,o);return e.id&&x.setAttribute("data-persona-instance",e.id),x},l=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},f=()=>{let T=d(a.host,n);s=sd(T,n,{debugTools:r.debugTools}),u()},p=()=>{i.forEach(T=>T()),i=[],s.destroy()};f(),r.onChatReady?r.onChatReady():r.onReady&&(by||(by=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),r.onReady());let m=T=>{p(),a.destroy(),a=xi(e,T),n=T,f()},y={update(T){var v,E,H,I,P,z;let M={...n,...T,launcher:{...(v=n==null?void 0:n.launcher)!=null?v:{},...(E=T==null?void 0:T.launcher)!=null?E:{},dock:{...(I=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?I:{},...(z=(P=T==null?void 0:T.launcher)==null?void 0:P.dock)!=null?z:{}}}},k=Lr(n),L=Lr(M),x=Kn(n),w=Kn(M);if(k!==L||x!==w){m(M);return}n=M,a.updateConfig(n),s.update(T),l()},destroy(){p(),a.destroy(),r.windowKey&&typeof window!="undefined"&&delete window[r.windowKey]}},h=new Proxy(y,{get(T,M,k){if(M==="host")return a.host;if(M in T)return Reflect.get(T,M,k);let L=s[M];return typeof L=="function"?L.bind(s):L}});return r.windowKey&&typeof window!="undefined"&&(window[r.windowKey]=h),h};var My=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),pw=new Set(["button","a","input","select","textarea","details","summary"]),uw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Cu=/\b(product|card|item|listing|result)\b/i,Au=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,fw=3e3,mw=100;function ky(r){let e=typeof r.className=="string"?r.className:"";if(Cu.test(e)||r.id&&Cu.test(r.id))return!0;for(let t=0;t<r.attributes.length;t++){let o=r.attributes[t];if(o.name.startsWith("data-")&&Cu.test(o.value))return!0}return!1}function Ey(r){var e;return Au.test(((e=r.textContent)!=null?e:"").trim())}function Ly(r){var t;let e=r.querySelectorAll("a[href]");for(let o=0;o<e.length;o++){let n=(t=e[o].getAttribute("href"))!=null?t:"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function gw(r){return!!r.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function wy(r){let e=r.match(Au);return e?e[0]:null}function Ay(r){var o,n,a;let e=(o=r.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:r.querySelector("a[href]");if(e&&((n=e.textContent)!=null&&n.trim())){let s=e.getAttribute("href");return{title:e.textContent.trim(),href:s&&s!=="#"?s:null}}let t=r.querySelector("h1, h2, h3, h4, h5, h6");return(a=t==null?void 0:t.textContent)!=null&&a.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function hw(r){let e=[],t=o=>{let n=o.trim();n&&!e.includes(n)&&e.push(n)};return r.querySelectorAll("button").forEach(o=>{var n;return t((n=o.textContent)!=null?n:"")}),r.querySelectorAll('[role="button"]').forEach(o=>{var n;return t((n=o.textContent)!=null?n:"")}),r.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;t((n=o.value)!=null?n:"")}),e.slice(0,6)}var xw="commerce-card",yw="result-card";function Sy(r){return!ky(r)||!Ey(r)||!Ly(r)&&!gw(r)?0:5200}function Ty(r){var o;return!ky(r)||Ey(r)||!Ly(r)||((o=r.textContent)!=null?o:"").trim().length<20||!(!!r.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!r.querySelector(".snippet, .description, p"))?0:2800}var Su=[{id:xw,scoreElement(r){return Sy(r)},shouldSuppressDescendant(r,e,t){if(e===r||!r.contains(e))return!1;if(t.interactivity==="static"){let o=t.text.trim();return!!(o.length===0||Au.test(o)&&o.length<32)}return!0},formatSummary(r,e){var d,l,u;if(Sy(r)===0)return null;let{title:t,href:o}=Ay(r),n=(u=(l=wy(((d=r.textContent)!=null?d:"").trim()))!=null?l:wy(e.text))!=null?u:"",a=hw(r);return[o&&t?`[${t}](${o})${n?` \u2014 ${n}`:""}`:t?`${t}${n?` \u2014 ${n}`:""}`:n||e.text.trim().slice(0,120),`selector: ${e.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
156
|
-
`)}},{id:
|
|
157
|
-
`)}}];function
|
|
110
|
+
`}if(!v&&!l){let Vt="max-height: -moz-available !important; max-height: stretch !important;",qt=f?"":"padding-top: 1.25em !important;",ft=f?"":`z-index: ${(gr=(rt=o.launcher)==null?void 0:rt.zIndex)!=null?gr:Lr} !important;`;_e.style.cssText+=Vt+qt+ft}Qe()};xe(),Wn(e,o),wl(e,o),Sl(e,o);let dt=[];dt.push(()=>{document.removeEventListener("keydown",gn)});let tr=null,fr=null;dt.push(()=>{tr==null||tr(),tr=null,fr==null||fr(),fr=null}),Gr&&dt.push(()=>{Gr==null||Gr.disconnect(),Gr=null}),dt.push(()=>{Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Ie&&dt.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),G==null||G.destroy(),G=null,ge==null||ge.destroy(),ge=null,J=null});let Io=null,es=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=el(()=>{Wn(e,o)}))};es(),dt.push(()=>{Io&&(Io(),Io=null)});let Xo=(Qu=o.features)==null?void 0:Qu.streamAnimation;if(Xo!=null&&Xo.type&&Xo.type!=="none"){let l=Ds(Xo.type,Xo.plugins);l&&(up(l,e),dt.push(()=>wh(e)))}let qn=Nh(Ge),Wo=null,_,ha=l=>{var v,R;if(!_)return;let f=l!=null?l:_.getMessages(),h=((R=(v=o.features)==null?void 0:v.suggestReplies)==null?void 0:R.enabled)!==!1?Ai(f):null;h?qn.render(h,_,ke,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(F=>F.role==="user")?qn.render([],_,ke,f):qn.render(o.suggestionChips,_,ke,f,o.suggestionChipsConfig)},Ho=!1,Bo=fh(),Qo=new Map,Do=new Map,bo=new Map,xa=0,Qs=Ia()!==null,Yr=ol(),Zr=0,vo=null,Co=!1,Vn=!1,Jo=0,Mr=null,Fo=null,ya=!1,$n=!1,ba=null,Js=4,va=24,Ys=80,Ca=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ts=(Yu=(Ju=o.voiceRecognition)==null?void 0:Ju.autoResume)!=null?Yu:!1,po=l=>{a.emit("voice:state",{active:mt.active,source:l,timestamp:Date.now()})},Vr=()=>{m(l=>({...l,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},Zs=()=>{var v,R;if(((v=o.voiceRecognition)==null?void 0:v.enabled)===!1)return;let l=Ip(c.voiceState),f=!!l.active,h=Number((R=l.timestamp)!=null?R:0);mt.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Pv&&setTimeout(()=>{var F,$;mt.active||(mt.manuallyDeactivated=!1,(($=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:$.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("restore"),_.isVoiceActive()&&Ta()}):di("restore"))},1e3)},ei=()=>_?ox(_.getMessages()).filter(l=>!l.__skipPersist):[];function wa(l){if(!(i!=null&&i.save))return;let h={messages:l?ox(l):_?ei():[],metadata:c,artifacts:Kr.artifacts,selectedArtifactId:Kr.selectedId};try{let v=i.save(h);v instanceof Promise&&v.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",v)}}let Yo=null,rs=()=>_e.querySelector("#persona-scroll-container")||Me,yn=()=>{Yo!==null&&(cancelAnimationFrame(Yo),Yo=null),Co=!1},os=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!1,yn()},ns=()=>{Jo>0?(Rr.textContent=String(Jo),Rr.style.display="",lt.setAttribute("aria-label",`${sr()||"Jump to latest"} (${Jo} new)`)):(Rr.textContent="",Rr.style.display="none",lt.setAttribute("aria-label",sr()||"Jump to latest"))},as=()=>{Jo!==0&&(Jo=0,ns())},ss=()=>ot()==="follow"?!Yr.isFollowing():!da(Me,va),$r=()=>{if(!Ft()||ce){lt.parentNode&<.remove(),lt.style.display="none";return}lt.parentNode!==pe&&pe.appendChild(lt),Ur();let f=sn(Me)>0&&ss();f||as(),lt.style.display=f?"":"none"},Sa=()=>{Yr.pause()&&(os(),$r())},No=()=>{Yr.resume(),as(),$r()},Oo=(l=!1)=>{ot()==="follow"&&Yr.isFollowing()&&(!l&&!Ho||(vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!0,vo=requestAnimationFrame(()=>{vo=null,Vn=!1,Yr.isFollowing()&&ti(rs(),l?220:140)})))},is=(l,f,h,v=()=>!0)=>{let R=l.scrollTop,F=f(),$=F-R;yn();let O=performance.now();Co=!0;let D=se=>1-Math.pow(1-se,3),ae=se=>{if(!v()){yn();return}let Q=f();Q!==F&&(F=Q,$=F-R);let ye=se-O,He=Math.min(ye/h,1),Se=D(He),nt=R+$*Se;l.scrollTop=nt,Zr=l.scrollTop,He<1?Yo=requestAnimationFrame(ae):(l.scrollTop=F,Zr=l.scrollTop,Yo=null,Co=!1)};Yo=requestAnimationFrame(ae)},ti=(l,f=500)=>{let h=sn(l)-l.scrollTop;if(Math.abs(h)<1){Zr=l.scrollTop;return}if(Math.abs(h)>=Ys){yn(),Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1;return}is(l,()=>sn(l),f,()=>Yr.isFollowing())},ls=()=>{let l=rs();Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1,$r()},ds=l=>{ir.style.height=`${Math.max(0,Math.round(l))}px`,Mr&&(Mr.spacerHeight=Math.max(0,l))},zn=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),yn(),Mr=null,ir.style.height="0px"},ri=l=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{var ae;Fo=null;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${f}"]`);if(!h)return;let v=0,R=h;for(;R&&R!==Me;)v+=R.offsetTop,R=R.offsetParent;let F=(ae=Mr==null?void 0:Mr.spacerHeight)!=null?ae:0,$=Me.scrollHeight-F,{targetScrollTop:O,spacerHeight:D}=yh({anchorOffsetTop:v,topOffset:Dt(),viewportHeight:Me.clientHeight,contentHeight:$});Mr={initialSpacerHeight:D,contentHeightAtAnchor:$,spacerHeight:D},ds(D),is(Me,()=>O,220)})},oi=()=>{if(ot()==="follow"){if(!Yr.isFollowing()||da(Me,1))return;Oo(!Ho);return}if(Mr&&Mr.initialSpacerHeight>0){let l=Me.scrollHeight-Mr.spacerHeight,f=bh({initialSpacerHeight:Mr.initialSpacerHeight,contentHeightAtAnchor:Mr.contentHeightAtAnchor,currentContentHeight:l});f!==Mr.spacerHeight&&ds(f)}$r()},ni=l=>{let f=ot();f==="follow"?(No(),Oo(!0)):f==="anchor-top"&&ri(l)},ai=l=>{let f=new Map;l.forEach(h=>{let v=Ca.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!v&&h.role==="assistant"&&(a.emit("assistant:message",h),!$n&&ot()!=="anchor-top"&&ss()&&(Jo+=1,ns(),$r())),h.role==="assistant"&&(v!=null&&v.streaming)&&h.streaming===!1&&a.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(v?h.approval.status!=="pending"&&a.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):a.emit("approval:requested",{approval:h.approval,message:h}))}),Ca.clear(),f.forEach((h,v)=>{Ca.set(v,h)})},si=(l,f,h)=>{var st,Le,Ee,ze,Qe,xt;let v=document.createElement("div"),F=(()=>{var Re;let B=n.find(Pe=>Pe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Re=o.loadingIndicator)!=null&&Re.render)return o.loadingIndicator.render})(),$=(B,Re)=>Re==null?!1:typeof Re=="string"?(B.textContent=Re,!0):(B.appendChild(Re),!0),O=new Set,D=new Set,ae=n.some(B=>B.renderAskUserQuestion),se=[],Q=[],ye=o.enableComponentStreaming!==!1,He=n.some(B=>B.renderApproval)&&o.approval!==!1,Se=[];if(f.forEach(B=>{var Ye,Rt,cr,go,to,jn,Gn,ka,La,Xt,Kn,Mn,Tn,en,Xn,wo;O.add(B.id);let Re=ae&&rn(B),Pe=He&&B.variant==="approval"&&!!B.approval,fe=!Re&&B.role==="assistant"&&!B.variant&&ye&&El(B);if(!Pe&&bo.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),bo.delete(B.id)}if(!fe&&Do.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Do.delete(B.id)}let Ut=rn(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Rt=B.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=uh(B,xa)+Ut,Kt=Re||Pe||fe?null:mh(Bo,B.id,Ot);if(Kt){v.appendChild(Kt.cloneNode(!0)),rn(B)&&((cr=B.toolCall)!=null&&cr.id)&&((go=B.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((to=B.agentMetadata)!=null&&to.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}let bt=null,zt=n.find(rt=>!!(B.variant==="reasoning"&&rt.renderReasoning||B.variant==="tool"&&rt.renderToolCall||!B.variant&&rt.renderMessage)),eo=(jn=o.layout)==null?void 0:jn.messages;if(rn(B)&&((Gn=B.agentMetadata)==null?void 0:Gn.askUserQuestionAnswered)===!0){Qo.delete(B.id);let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(As(B)&&((La=(ka=o.features)==null?void 0:ka.suggestReplies)==null?void 0:La.enabled)!==!1)return;if(rn(B)&&((Kn=(Xt=o.features)==null?void 0:Xt.askUserQuestion)==null?void 0:Kn.enabled)!==!1){let rt=n.find(gr=>typeof gr.renderAskUserQuestion=="function");if(rt&&Mt.current){let gr=Qo.get(B.id),Vt=gr!==Ot,qt=null;if(Vt){let{payload:St,complete:Tr}=on(B),Br=B.id,Uo=()=>{var vr;return(vr=Mt.current)==null?void 0:vr.getMessages().find(Dr=>Dr.id===Br)};qt=rt.renderAskUserQuestion({message:B,payload:St,complete:Tr,resolve:vr=>{var Fr;let Dr=Uo();Dr&&((Fr=Mt.current)==null||Fr.resolveAskUserQuestion(Dr,vr))},dismiss:()=>{var Dr,Fr,Qn;let vr=Uo();(Dr=vr==null?void 0:vr.agentMetadata)!=null&&Dr.awaitingLocalTool&&((Fr=Mt.current)==null||Fr.markAskUserQuestionResolved(vr),(Qn=Mt.current)==null||Qn.resolveAskUserQuestion(vr,"(dismissed)"))},config:o})}let ft=gr!=null;if(Vt&&qt===null&&!ft){((Mn=B.agentMetadata)==null?void 0:Mn.awaitingLocalTool)===!0&&!((Tn=B.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-ask-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),v.appendChild(Qt),se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}else{((en=B.agentMetadata)==null?void 0:en.awaitingLocalTool)===!0&&!((Xn=B.agentMetadata)!=null&&Xn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}}else if(Pe){let rt=n.find(ft=>typeof ft.renderApproval=="function"),Vt=bo.get(B.id)!==Ot,qt=null;if(Vt&&(rt!=null&&rt.renderApproval)){let ft=B.id,Qt=(St,Tr)=>{var Uo,vr,Dr;let Br=(Uo=Mt.current)==null?void 0:Uo.getMessages().find(Fr=>Fr.id===ft);Br!=null&&Br.approval&&(Br.approval.toolType==="webmcp"?(vr=Mt.current)==null||vr.resolveWebMcpApproval(Br.id,St):(Dr=Mt.current)==null||Dr.resolveApproval(Br.approval,St,Tr))};qt=rt.renderApproval({message:B,defaultRenderer:()=>vl(B,o),config:o,approve:St=>Qt("approved",St),deny:St=>Qt("denied",St)})}if(Vt&&qt===null){let ft=l.querySelector(`#wrapper-${B.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),bo.delete(B.id),bt=vl(B,o)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${B.id}`,ft.setAttribute("data-wrapper-id",B.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),v.appendChild(ft),Se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}}else if(zt)if(B.variant==="reasoning"&&B.reasoning&&zt.renderReasoning){if(!Ke)return;bt=zt.renderReasoning({message:B,defaultRenderer:()=>Ap(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&zt.renderToolCall){if(!Ce)return;bt=zt.renderToolCall({message:B,defaultRenderer:()=>Mp(B,o),config:o})}else zt.renderMessage&&(bt=zt.renderMessage({message:B,defaultRenderer:()=>{let rt=Ga(B,h,eo,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&Lp(rt,B,o,_),rt},config:o}));if(!bt&&fe){let rt=kl(B);if(rt){let gr=Do.get(B.id),Vt=gr!==Ot,qt=o.wrapComponentDirectiveInBubble!==!1,ft=null;if(Vt){let Qt=Tl(rt,{config:o,message:B,transform:h});if(Qt)if(qt){let St=document.createElement("div");if(St.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(" "),St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),St.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}}if(ft||gr!=null){let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-component-directive-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),qt||Qt.classList.add("persona-w-full"),v.appendChild(Qt),Q.push({messageId:B.id,fingerprint:Ot,bubble:ft});return}}}if(!bt)if(B.variant==="reasoning"&&B.reasoning){if(!Ke)return;bt=Ap(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Ce)return;bt=Mp(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;bt=vl(B,o)}else{let rt=(wo=o.layout)==null?void 0:wo.messages;rt!=null&&rt.renderUserMessage&&B.role==="user"?bt=rt.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):rt!=null&&rt.renderAssistantMessage&&B.role==="assistant"?bt=rt.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):bt=Ga(B,h,rt,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&bt&&Lp(bt,B,o,_)}let or=document.createElement("div");or.className="persona-flex",or.id=`wrapper-${B.id}`,or.setAttribute("data-wrapper-id",B.id),B.role==="user"&&or.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&or.classList.add("persona-w-full"),or.appendChild(bt),gh(Bo,B.id,Ot,or),v.appendChild(or)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Pe=Re.getAttribute("data-persona-ask-sheet-for");Pe&&!D.has(Pe)&&Ln(Y.composerOverlay,Pe)}),(Le=(st=o.features)==null?void 0:st.toolCallDisplay)!=null&&Le.grouped){let B=[],Re=[];f.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ce){Re.push(Pe);return}Re.length>1&&B.push(Re),Re=[]}),Re.length>1&&B.push(Re),B.forEach((Pe,fe)=>{var Ye,Rt;let Ut=Pe.map(cr=>Array.from(v.children).find(go=>go instanceof HTMLElement&&go.getAttribute("data-wrapper-id")===cr.id)).filter(cr=>!!cr);if(Ut.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${fe}-${Pe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${fe}-${Pe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let bt=document.createElement("div");bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Pe.length} tools`,eo=(Rt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Rt.call(Ye,{messages:Pe,toolCalls:Pe.map(cr=>cr.toolCall).filter(cr=>!!cr),defaultSummary:zt,config:o});$(bt,eo)||(bt.textContent=zt);let or=document.createElement("div");or.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(bt,or),Ot.appendChild(Kt),Ut[0].before(Ot),Ut.forEach((cr,go)=>{let to=document.createElement("div");to.className="persona-tool-group-item persona-relative",to.setAttribute("data-persona-tool-group-item","true"),go<Ut.length-1&&to.setAttribute("data-persona-tool-group-connector","true"),to.appendChild(cr),or.appendChild(to)})})}hh(Bo,O);let nt=f.some(B=>B.role==="assistant"&&B.streaming),$e=f[f.length-1],ut=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ho&&f.some(B=>B.role==="user")&&!nt&&!ut){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},Re=n.find(fe=>fe.renderLoadingIndicator),Pe=null;if(Re!=null&&Re.renderLoadingIndicator&&(Pe=Re.renderLoadingIndicator(B)),Pe===null&&((Ee=o.loadingIndicator)!=null&&Ee.render)&&(Pe=o.loadingIndicator.render(B)),Pe===null&&(Pe=ua()),Pe){let fe=document.createElement("div"),Ut=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;fe.className=Ut?["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(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Pe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(fe),v.appendChild(Ot)}}if(!Ho&&f.length>0){let B=f[f.length-1],Re={config:o,lastMessage:B,messageCount:f.length},Pe=n.find(Ut=>Ut.renderIdleIndicator),fe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(fe=Pe.renderIdleIndicator(Re)),fe===null&&((Qe=o.loadingIndicator)!=null&&Qe.renderIdle)&&(fe=o.loadingIndicator.renderIdle(Re)),fe){let Ut=document.createElement("div"),Ot=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Ut.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(" "),Ut.setAttribute("data-idle-indicator","true"),Ut.appendChild(fe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ut),v.appendChild(Kt)}}if(tl(l,v),se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Qo.set(B,Re))}if(Qo.size>0)for(let B of Qo.keys())O.has(B)||Qo.delete(B);if(Q.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Q){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Do.set(B,Re))}if(Do.size>0)for(let B of Do.keys())O.has(B)||Do.delete(B);if(Se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),bo.set(B,Re))}if(bo.size>0)for(let B of bo.keys())O.has(B)||bo.delete(B)},bn=(l,f,h)=>{si(l,f,h),fn()},vn=null,ii=()=>{var h;if(vn)return;let l=v=>{let R=v.composedPath();R.includes(_e)||Ze&&R.includes(Ze)||I(!1,"user")};vn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},cs=()=>{var f;if(!vn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",vn,!0),vn=null};dt.push(()=>cs());let Cn=null,li=()=>{var h;if(Cn)return;let l=v=>{v.key==="Escape"&&(v.isComposing||I(!1,"user"))};Cn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},ps=()=>{var f;if(!Cn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Cn,!0),Cn=null};dt.push(()=>ps());let wn=!1,us=new Set,Aa=()=>{var f,h,v,R;let l=(v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:v.streamAnimation;return l||((R=o.features)==null?void 0:R.streamAnimation)},Ve=()=>{var ut,st,Le,Ee;if(!H())return;let l=Y.peekBanner,f=Y.peekTextNode;if(!l||!f)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=_==null?void 0:_.getMessages())!=null?ut:[],v;for(let ze=h.length-1;ze>=0;ze--){let Qe=h[ze];if(Qe.role==="assistant"&&Qe.content){v=Qe;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let R=v.content,F=!!v.streaming,$=Aa(),O=sl($),D=O.type!=="none"?Ds(O.type,$==null?void 0:$.plugins):null,ae=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,v))===!0,se=D!==null&&(F||ae);se&&D&&!us.has(D.name)&&(up(D,e),us.add(D.name));let Q=se&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Le=f.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==Q&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),Q&&ye!==Q&&(f.classList.add(Q),f.dataset.personaPeekStreamClass=Q),se?(f.style.setProperty("--persona-stream-step",`${O.speed}ms`),f.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let He=se?il(R,O.buffer,D,v,F):R;if(se&&O.placeholder==="skeleton"&&F&&(!He||!He.trim())){let ze=document.createElement("div"),Qe=Ns();Qe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Qe),tl(f,ze)}else{let ze=Math.max(0,He.length-100),Qe=He.length>100?He.slice(-100):He,xt=qo(Qe);if(!se||!D){let B=He.length>100?`\u2026${Qe}`:Qe;f.textContent!==B&&(f.textContent=B)}else{let B=xt;(D.wrap==="char"||D.wrap==="word")&&(B=Fs(xt,D.wrap,`peek-${v.id}`,{skipTags:D.skipTags,startIndex:ze}));let Re=document.createElement("div");if(Re.innerHTML=B,D.useCaret&&Qe.length>0){let Pe=ll(),fe=Re.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ut=fe[fe.length-1];Ut!=null&&Ut.parentNode?Ut.parentNode.insertBefore(Pe,Ut.nextSibling):Re.appendChild(Pe)}tl(f,Re),(Ee=D.onAfterRender)==null||Ee.call(D,{container:f,bubble:l,messageId:v.id,message:v,speed:O.speed,duration:O.duration})}}let $e=Ho||wn;l.classList.toggle("persona-pill-peek--visible",$e)};if(H()){let l=Y.peekBanner;if(l){let v=R=>{R.preventDefault(),R.stopPropagation(),I(!0,"user")};l.addEventListener("pointerdown",v),dt.push(()=>{l.removeEventListener("pointerdown",v)})}let f=()=>{wn||(wn=!0,Ve())},h=()=>{wn&&(wn=!1,Ve())};be.addEventListener("pointerenter",f),be.addEventListener("pointerleave",h),dt.push(()=>{be.removeEventListener("pointerenter",f),be.removeEventListener("pointerleave",h)}),Ze&&(Ze.addEventListener("pointerenter",f),Ze.addEventListener("pointerleave",h),dt.push(()=>{Ze.removeEventListener("pointerenter",f),Ze.removeEventListener("pointerleave",h)}))}let L=l=>{var ye,He,Se,nt,$e,ut,st,Le;let f=(He=(ye=o.launcher)==null?void 0:ye.composerBar)!=null?He:{},h=(Se=f.expandedSize)!=null?Se:"anchored",v=(nt=f.bottomOffset)!=null?nt:"16px",R=f.collapsedMaxWidth,F=($e=f.expandedMaxWidth)!=null?$e:"880px",$=(ut=f.expandedTopOffset)!=null?ut:"5vh",O=(st=f.modalMaxWidth)!=null?st:"880px",D=(Le=f.modalMaxHeight)!=null?Le:"min(90vh, 800px)",ae="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Q=_e.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",Ze){let Ee=Ze.style;Ee.bottom=v,Ee.width=R!=null?R:""}if(l&&h!=="fullscreen"){if(h==="modal"){Q.top="50%",Q.left="50%",Q.transform="translate(-50%, -50%)",Q.bottom="auto",Q.right="auto",Q.width=O,Q.maxWidth=ae,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${v} + ${se})`,Q.top=$,Q.width=F,Q.maxWidth=ae}},U=()=>{var D,ae,se,Q,ye,He,Se,nt;if(!W())return;if(H()){let ut=(se=((ae=(D=o.launcher)==null?void 0:D.composerBar)!=null?ae:{}).expandedSize)!=null?se:"anchored",st=k?"expanded":"collapsed";_e.dataset.state=st,_e.dataset.expandedSize=ut,Ze&&(Ze.dataset.state=st,Ze.dataset.expandedSize=ut),_e.style.removeProperty("display"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),L(k),pe.style.display=k?"flex":"none",xe(),k?(ii(),li()):(cs(),ps()),Ve();return}let l=pr(o),f=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(He=(ye=o.launcher)==null?void 0:ye.mobileBreakpoint)!=null?He:640,v=(nt=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?nt:!0,R=f.innerWidth<=h,F=v&&R&&E,$=no(o).reveal;k?(_e.style.removeProperty("display"),_e.style.display=l?"flex":"",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),rr?rr.element.style.display="none":mr&&(mr.style.display="none")):(l?l&&($==="overlay"||$==="push")&&!F?(_e.style.removeProperty("display"),_e.style.display="flex",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.setProperty("display","none","important"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.display="",_e.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),rr?rr.element.style.display=l?"none":"":mr&&(mr.style.display=l?"none":""))},I=(l,f="user")=>{var F,$;if(!W()||k===l)return;let h=k;k=l,U();let v=(()=>{var Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt;let O=(nt=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?nt:!1,D=($e=e.ownerDocument.defaultView)!=null?$e:window,ae=(st=(ut=o.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,se=(Ee=(Le=o.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Ee:640,Q=D.innerWidth<=se,ye=pr(o)&&ae&&Q,He=H()&&((xt=(Qe=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Qe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return O||ae&&Q&&E||ye||He})();if(k&&v){if(!tr){let O=e.getRootNode(),D=O instanceof ShadowRoot?O.host:e.closest(".persona-host");D&&(tr=fp(D,($=(F=o.launcher)==null?void 0:F.zIndex)!=null?$:Lr))}fr||(fr=mp(e.ownerDocument))}else k||(tr==null||tr(),tr=null,fr==null||fr(),fr=null);k&&(fs(),ot()==="follow"?Oo(!0):ls());let R={open:k,source:f,timestamp:Date.now()};k&&!h?a.emit("widget:opened",R):!k&&h&&a.emit("widget:closed",R),a.emit("widget:state",{open:k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()})},X=l=>{Pr(l?"stop":"send"),z&&(z.disabled=l),qn.buttons.forEach(f=>{f.disabled=l}),Ne.dataset.personaComposerStreaming=l?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},re=()=>{mt.active||ke&&ke.focus()};a.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>re(),200)});let K=()=>{var h,v,R,F,$,O,D,ae,se,Q,ye;Eo.textContent=(v=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?v:"Hello \u{1F44B}",V.textContent=(F=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",ke.placeholder=(O=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?O:"How can I help...";let l=Me.querySelector("[data-persona-intro-card]");if(l){let He=((D=o.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=He?"":"none",He?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((se=(ae=o.sendButton)==null?void 0:ae.useIcon)!=null&&se)&&!(_!=null&&_.isStreaming())&&(je.textContent=(ye=(Q=o.copy)==null?void 0:Q.sendButtonLabel)!=null?ye:"Send"),ke.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ke.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(f=>({...f,sessionId:l}))}});let Ae=null,Oe=()=>{Ae==null&&(Ae=setInterval(()=>{let l=Je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ae),Ae=null;return}let f=Date.now();l.forEach(h=>{let v=Number(h.getAttribute("data-tool-elapsed"));v&&(h.textContent=Ti(f-v))})},100))};_=new Ua(o,{onMessagesChanged(l){var v;bn(Je,l,me),Oe(),ha(l),Oo(!Ho),ai(l);let f=[...l].reverse().find(R=>R.role==="user");l.length===0&&zn(),!ya||$n?(ya=!0,ba=(v=f==null?void 0:f.id)!=null?v:null):f&&f.id!==ba&&(ba=f.id,ni(f.id));let h=mt.lastUserMessageId;f&&f.id!==h&&(mt.lastUserMessageId=f.id,a.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),wa(l),Ve()},onStatusChanged(l){var v;let f=(v=o.statusIndicator)!=null?v:{};Lt(ur,(R=>{var F,$,O,D;return R==="idle"?(F=f.idleText)!=null?F:kr.idle:R==="connecting"?($=f.connectingText)!=null?$:kr.connecting:R==="connected"?(O=f.connectedText)!=null?O:kr.connected:R==="error"?(D=f.errorText)!=null?D:kr.error:kr[R]})(l),f,l)},onStreamingChanged(l){Ho=l,X(l),_&&bn(Je,_.getMessages(),me),l||Oo(!0),Ve()},onVoiceStatusChanged(l){var f,h;if(a.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Zo(),Ta();break;case"processing":Zo(),$x();break;case"speaking":Zo(),zx();break;default:l==="idle"&&_.isBargeInActive()?(Zo(),Ta(),z==null||z.setAttribute("aria-label","End voice session")):(mt.active=!1,Zo(),po("system"),Vr());break}},onArtifactsState(l){Kr=l,Jr(),wa()}}),Mt.current=_;let at=null;if(_.onReadAloudChange((l,f)=>{var R;pn=l,un=f,fn();let h=l!=null?l:at;l&&(at=l);let v=h&&(R=_.getMessages().find(F=>F.id===h))!=null?R:null;a.emit("message:read-aloud",{messageId:h,message:v,state:f,timestamp:Date.now()}),f==="idle"&&(at=null)}),ya=!0,((ef=(Zu=o.voiceRecognition)==null?void 0:Zu.provider)==null?void 0:ef.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ge||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,l,f),ue==null||ue.processEvent(l,f),ge==null||ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})}),d&&d.then(l=>{var f,h,v;if(l){if(l.metadata&&(c=Ip(l.metadata),T.syncFromMetadata()),(f=l.messages)!=null&&f.length){$n=!0;try{_.hydrateMessages(l.messages)}finally{$n=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(v=l.selectedArtifactId)!=null?v:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let tt=()=>{var f,h,v;!H()||k||!((v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||v)||I(!0,"auto")},Bt=l=>{var R;if(l.preventDefault(),_.isStreaming()){_.cancel(),ue==null||ue.reset(),G==null||G.update();return}let f=ke.value.trim(),h=(R=yt==null?void 0:yt.hasAttachments())!=null?R:!1;if(!f&&!h)return;tt();let v;h&&(v=[],v.push(...yt.getContentParts()),f&&v.push(ks(f))),ke.value="",ke.style.height="auto",Tt(),_.sendMessage(f,{contentParts:v}),h&&yt.clearAttachments()},$t=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},lr={...rl},wt=!1,Tt=()=>{lr={...rl}},br=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var f;return(f=l.content)!=null?f:""}).filter(l=>l.length>0),Hr=l=>{if(!ke)return;wt=!0,ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),wt=!1;let f=ke.value.length;ke.setSelectionRange(f,f)},Sr=()=>{wt||Tt()},Zt=l=>{if(ke){if($t()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=ke.selectionStart===0&&ke.selectionEnd===0,h=ph({direction:l.key==="ArrowUp"?"up":"down",history:br(),currentValue:ke.value,atStart:f,state:lr});if(lr=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Hr(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Tt(),l.preventDefault(),je.click()}}},uo=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(pe)&&(_.cancel(),ue==null||ue.reset(),G==null||G.update(),Tt(),l.preventDefault(),l.stopImmediatePropagation())},Xp=async l=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!yt)return;let f=Iv(l.clipboardData);f.length!==0&&(l.preventDefault(),await yt.handleFiles(f))},fo=null,_o=!1,Ma=null,pt=null,Qp=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,di=(l="user")=>{var F,$,O,D,ae,se,Q;if(_o||_.isStreaming())return;let f=Qp();if(!f)return;fo=new f;let v=($=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?$:2e3;fo.continuous=!0,fo.interimResults=!0,fo.lang="en-US";let R=ke.value;fo.onresult=ye=>{let He="",Se="";for(let $e=0;$e<ye.results.length;$e++){let ut=ye.results[$e],st=ut[0].transcript;ut.isFinal?He+=st+" ":Se=st}let nt=R+He+Se;ke.value=nt,Ma&&clearTimeout(Ma),(He||Se)&&(Ma=window.setTimeout(()=>{let $e=ke.value.trim();$e&&fo&&_o&&(Sn(),ke.value="",ke.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},v))},fo.onerror=ye=>{ye.error!=="no-speech"&&Sn()},fo.onend=()=>{if(_o){let ye=ke.value.trim();ye&&ye!==R.trim()&&(ke.value="",ke.style.height="auto",_.sendMessage(ye,{viaVoice:!0})),Sn()}};try{if(fo.start(),_o=!0,mt.active=!0,l!=="system"&&(mt.manuallyDeactivated=!1),po(l),Vr(),z){let ye=(O=o.voiceRecognition)!=null?O:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(se=ye.iconSize)!=null?se:(ae=o.sendButton)==null?void 0:ae.size)!=null?Q:"40")||24};let He=ye.recordingBackgroundColor,Se=ye.recordingIconColor,nt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=He!=null?He:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let $e=z.querySelector("svg");$e&&$e.setAttribute("stroke",Se)}nt&&(z.style.borderColor=nt),z.setAttribute("aria-label","Stop voice recognition")}}catch{Sn("system")}},Sn=(l="user")=>{if(_o){if(_o=!1,Ma&&(clearTimeout(Ma),Ma=null),fo){try{fo.stop()}catch{}fo=null}if(mt.active=!1,po(l),Vr(),z){if(z.classList.remove("persona-voice-recording"),pt){z.style.backgroundColor=pt.backgroundColor,z.style.color=pt.color,z.style.borderColor=pt.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",pt.color||"currentColor"),pt=null}z.setAttribute("aria-label","Start voice recognition")}}},Vx=(l,f)=>{var st,Le,Ee,ze,Qe,xt,B,Re,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),v=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",R=((Le=l==null?void 0:l.provider)==null?void 0:Le.type)==="custom";if(!(h||v||R))return null;let $=S("div","persona-send-button-wrapper"),O=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let D=(Ee=l==null?void 0:l.iconName)!=null?Ee:"mic",ae=(ze=f==null?void 0:f.size)!=null?ze:"40px",se=(Qe=l==null?void 0:l.iconSize)!=null?Qe:ae,Q=parseFloat(se)||24,ye=(xt=l==null?void 0:l.backgroundColor)!=null?xt:f==null?void 0:f.backgroundColor,He=(B=l==null?void 0:l.iconColor)!=null?B:f==null?void 0:f.textColor;O.style.width=se,O.style.height=se,O.style.minWidth=se,O.style.minHeight=se,O.style.fontSize="18px",O.style.lineHeight="1",He?O.style.color=He:O.style.color="var(--persona-text, #111827)";let nt=ve(D,Q,He||"currentColor",1.5);nt?O.appendChild(nt):O.textContent="\u{1F3A4}",ye?O.style.backgroundColor=ye:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),$.appendChild(O);let $e=(Re=l==null?void 0:l.tooltipText)!=null?Re:"Start voice recognition";if(((Pe=l==null?void 0:l.showTooltip)!=null?Pe:!1)&&$e){let fe=S("div","persona-send-button-tooltip");fe.textContent=$e,$.appendChild(fe)}return{micButton:O,micButtonWrapper:$}},Bl=()=>{var f,h,v,R,F;if(!z||pt)return;let l=(f=o.voiceRecognition)!=null?f:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((F=(R=l.iconSize)!=null?R:(v=o.sendButton)==null?void 0:v.size)!=null?F:"40")||24}},Dl=(l,f)=>{var F,$,O,D,ae;if(!z)return;let h=z.querySelector("svg");h&&h.remove();let v=(ae=pt==null?void 0:pt.iconSize)!=null?ae:parseFloat((D=(O=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?O:($=o.sendButton)==null?void 0:$.size)!=null?D:"40")||24,R=ve(l,v,f,1.5);R&&z.appendChild(R)},ci=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ta=()=>{var R;if(!z)return;Bl();let l=(R=o.voiceRecognition)!=null?R:{},f=l.recordingBackgroundColor,h=l.recordingIconColor,v=l.recordingBorderColor;if(ci(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let F=z.querySelector("svg");F&&F.setAttribute("stroke",h)}v&&(z.style.borderColor=v),z.setAttribute("aria-label","Stop voice recognition")},$x=()=>{var O,D,ae,se,Q,ye,He,Se;if(!z)return;Bl();let l=(O=o.voiceRecognition)!=null?O:{},f=_.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",v=(se=(ae=l.processingIconColor)!=null?ae:pt==null?void 0:pt.color)!=null?se:"",R=(ye=(Q=l.processingBackgroundColor)!=null?Q:pt==null?void 0:pt.backgroundColor)!=null?ye:"",F=(Se=(He=l.processingBorderColor)!=null?He:pt==null?void 0:pt.borderColor)!=null?Se:"";ci(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=R,z.style.borderColor=F;let $=v||"currentColor";z.style.color=$,Dl(h,$),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},zx=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee;if(!z)return;Bl();let l=(ae=o.voiceRecognition)!=null?ae:{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",v=(se=l.speakingIconName)!=null?se:h,R=(Se=l.speakingIconColor)!=null?Se:f==="barge-in"?(ye=(Q=l.recordingIconColor)!=null?Q:pt==null?void 0:pt.color)!=null?ye:"":(He=pt==null?void 0:pt.color)!=null?He:"",F=(ut=l.speakingBackgroundColor)!=null?ut:f==="barge-in"?(nt=l.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":($e=pt==null?void 0:pt.backgroundColor)!=null?$e:"",$=(Ee=l.speakingBorderColor)!=null?Ee:f==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Le=pt==null?void 0:pt.borderColor)!=null?Le:"";ci(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=F,z.style.borderColor=$;let O=R||"currentColor";z.style.color=O,Dl(v,O);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")},Zo=()=>{var l,f,h;z&&(ci(),pt&&(z.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",z.style.color=(f=pt.color)!=null?f:"",z.style.borderColor=(h=pt.borderColor)!=null?h:"",Dl(pt.iconName,pt.color||"currentColor"),pt=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},pi=()=>{var l,f;if(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"){let h=_.getVoiceStatus(),v=_.getVoiceInterruptionMode();if(v==="none"&&(h==="processing"||h==="speaking"))return;if(v==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()});return}_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),mt.manuallyDeactivated=!_.isVoiceActive(),Vr(),po("user"),_.isVoiceActive()?Ta():Zo()});return}if(_o){let h=ke.value.trim();mt.manuallyDeactivated=!0,Vr(),Sn("user"),h&&(ke.value="",ke.style.height="auto",_.sendMessage(h))}else mt.manuallyDeactivated=!1,Vr(),di("user")};jr=pi,z&&(z.addEventListener("click",pi),dt.push(()=>{var l,f;((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Zo()):Sn("system"),z&&z.removeEventListener("click",pi)}));let jx=a.on("assistant:complete",()=>{ts&&(mt.active||mt.manuallyDeactivated||ts==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var l,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("auto"),_.isVoiceActive()&&Ta()}):di("auto"))},600))});dt.push(jx);let Gx=a.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(Gx);let Jp=()=>{I(!k,"user")},rr=null,mr=null;if(E&&!H()){let{instance:l,element:f}=bp({config:o,plugins:n,onToggle:Jp});rr=l,l||(mr=f)}rr?e.appendChild(rr.element):mr&&e.appendChild(mr),U(),ha(),K(),X(_.isStreaming()),ot()==="follow"?Oo(!0):ls(),Zs(),P&&(!E||H()?setTimeout(()=>re(),0):k&&setTimeout(()=>re(),200));let fs=()=>{var D,ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt,B,Re,Pe,fe,Ut,Ot;if(H()){Ur(),U();return}let l=pr(o),f=(ae=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?ae:!1,h=l||f||((Q=(se=o.launcher)==null?void 0:se.fullHeight)!=null?Q:!1),v=(ye=e.ownerDocument.defaultView)!=null?ye:window,R=(Se=(He=o.launcher)==null?void 0:He.mobileFullscreen)!=null?Se:!0,F=($e=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?$e:640,$=v.innerWidth<=F,O=R&&$&&E;try{if(O){xe(),Wn(e,o);return}if(A&&(A=!1,xe(),Wn(e,o)),!E&&!l){be.style.height="",be.style.width="";return}if(!f&&!l){let Kt=(st=(ut=o==null?void 0:o.launcher)==null?void 0:ut.width)!=null?st:o==null?void 0:o.launcherWidth,bt=Kt!=null?Kt:oo;be.style.width=bt,be.style.maxWidth=bt}if(Ro(),!h){let Kt=v.innerHeight,bt=64,zt=(Ee=(Le=o.launcher)==null?void 0:Le.heightOffset)!=null?Ee:0,eo=Math.max(200,Kt-bt),or=Math.min(640,eo),Ye=Math.max(200,or-zt);be.style.height=`${Ye}px`}}finally{if(Ur(),U(),k&&E){let bt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((xt=(Qe=o.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?xt:640),zt=(Re=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Re:!1,eo=(fe=(Pe=o.launcher)==null?void 0:Pe.mobileFullscreen)!=null?fe:!0,or=pr(o)&&eo&&bt,Ye=zt||eo&&bt&&E||or;if(Ye&&!fr){let Rt=e.getRootNode(),cr=Rt instanceof ShadowRoot?Rt.host:e.closest(".persona-host");cr&&!tr&&(tr=fp(cr,(Ot=(Ut=o.launcher)==null?void 0:Ut.zIndex)!=null?Ot:Lr)),fr=mp(e.ownerDocument)}else Ye||(tr==null||tr(),tr=null,fr==null||fr(),fr=null)}}};fs();let Yp=(tf=e.ownerDocument.defaultView)!=null?tf:window;if(Yp.addEventListener("resize",fs),dt.push(()=>Yp.removeEventListener("resize",fs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ur()});l.observe(Ne),dt.push(()=>l.disconnect())}Zr=Me.scrollTop;let Zp=sn(Me),Kx=()=>{let l=Me.getRootNode(),f=typeof l.getSelection=="function"?l.getSelection():null;return f!=null?f:Me.ownerDocument.getSelection()},Fl=()=>xh(Kx(),Me),eu=()=>{let l=Me.scrollTop,f=sn(Me),h=f<Zp;if(Zp=f,ot()!=="follow"){Zr=l,$r();return}let{action:v,nextLastScrollTop:R}=nl({following:Yr.isFollowing(),currentScrollTop:l,lastScrollTop:Zr,nearBottom:da(Me,va),userScrollThreshold:Js,isAutoScrolling:Co||Vn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Zr=R,v==="resume"){Fl()||No();return}v==="pause"&&Sa()};if(Me.addEventListener("scroll",eu,{passive:!0}),dt.push(()=>Me.removeEventListener("scroll",eu)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{oi()});l.observe(Je),l.observe(Me),dt.push(()=>l.disconnect())}let tu=()=>{ot()==="follow"&&Yr.isFollowing()&&Fl()&&Sa()},ru=Me.ownerDocument;ru.addEventListener("selectionchange",tu),dt.push(()=>{ru.removeEventListener("selectionchange",tu)});let ou=l=>{if(ot()!=="follow")return;let f=al({following:Yr.isFollowing(),deltaY:l.deltaY,nearBottom:da(Me,va),resumeWhenNearBottom:!0});f==="pause"?Sa():f==="resume"&&!Fl()&&No()};Me.addEventListener("wheel",ou,{passive:!0}),dt.push(()=>Me.removeEventListener("wheel",ou)),lt.addEventListener("click",()=>{zn(),Me.scrollTop=Me.scrollHeight,Zr=Me.scrollTop,No(),Oo(!0),$r()}),dt.push(()=>lt.remove()),dt.push(()=>{os(),zn()});let nu=()=>{j&&(Wo&&(j.removeEventListener("click",Wo),Wo=null),W()?(j.style.display="",Wo=()=>{I(!1,"user")},j.addEventListener("click",Wo)):j.style.display="none")};nu(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Bo.clear(),No(),Ln(Y.composerOverlay);try{localStorage.removeItem(Ya),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ya}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ya)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(v=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",v)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()})})(),Wt&&Wt.addEventListener("submit",Bt),ke==null||ke.addEventListener("keydown",Zt),ke==null||ke.addEventListener("input",Sr),ke==null||ke.addEventListener("paste",Xp);let au=(rf=e.ownerDocument)!=null?rf:document;au.addEventListener("keydown",uo,!0);let su="persona-attachment-drop-active",ms=0,Nl=()=>{ms=0,pe.classList.remove(su)},Ea=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&yt!==null},iu=l=>{!Rl(l.dataTransfer)||!Ea()||(ms++,ms===1&&pe.classList.add(su))},lu=l=>{!Rl(l.dataTransfer)||!Ea()||(ms--,ms<=0&&Nl())},du=l=>{!Rl(l.dataTransfer)||!Ea()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},cu=l=>{var h;if(!Rl(l.dataTransfer)||!Ea())return;l.preventDefault(),l.stopPropagation(),Nl();let f=Array.from((h=l.dataTransfer.files)!=null?h:[]);f.length!==0&&yt.handleFiles(f)},An=!0;pe.addEventListener("dragenter",iu,An),pe.addEventListener("dragleave",lu,An),e.addEventListener("dragover",du,An),e.addEventListener("drop",cu,An);let ui=e.ownerDocument,pu=l=>{Ea()&&l.preventDefault()},uu=l=>{Ea()&&l.preventDefault()};ui.addEventListener("dragover",pu),ui.addEventListener("drop",uu),dt.push(()=>{Wt&&Wt.removeEventListener("submit",Bt),ke==null||ke.removeEventListener("keydown",Zt),ke==null||ke.removeEventListener("input",Sr),ke==null||ke.removeEventListener("paste",Xp),au.removeEventListener("keydown",uo,!0)}),dt.push(()=>{pe.removeEventListener("dragenter",iu,An),pe.removeEventListener("dragleave",lu,An),e.removeEventListener("dragover",du,An),e.removeEventListener("drop",cu,An),ui.removeEventListener("dragover",pu),ui.removeEventListener("drop",uu),Nl()}),dt.push(()=>{_.cancel()}),rr?dt.push(()=>{rr==null||rr.destroy()}):mr&&dt.push(()=>{mr==null||mr.remove()});let dr={update(l){var Tr,Br,Uo,vr,Dr,Fr,Qn,gs,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,Cf,wf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf,If,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,$f,zf,jf,Gf,Kf,Xf,Qf,Jf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,Cm,wm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,$m,zm,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,og,ng,ag,sg,ig,lg;let f=o.toolCall,h=o.messageActions,v=(Tr=o.layout)==null?void 0:Tr.messages,R=o.colorScheme,F=o.loadingIndicator,$=o.iterationDisplay,O=(Br=o.features)==null?void 0:Br.showReasoning,D=(Uo=o.features)==null?void 0:Uo.showToolCalls,ae=(vr=o.features)==null?void 0:vr.toolCallDisplay,se=(Dr=o.features)==null?void 0:Dr.reasoningDisplay;o={...o,...l},xe(),Wn(e,o),wl(e,o),Sl(e,o),Jr(),o.colorScheme!==R&&es();let Q=zs.getForInstance(o.plugins);n.length=0,n.push(...Q),E=(Qn=(Fr=o.launcher)==null?void 0:Fr.enabled)!=null?Qn:!0,M=(cf=(gs=o.launcher)==null?void 0:gs.autoExpand)!=null?cf:!1,Ke=(uf=(pf=o.features)==null?void 0:pf.showReasoning)!=null?uf:!0,Ce=(mf=(ff=o.features)==null?void 0:ff.showToolCalls)!=null?mf:!0,Ue=(hf=(gf=o.features)==null?void 0:gf.scrollToBottom)!=null?hf:{};let ye=ot();Te=(yf=(xf=o.features)==null?void 0:xf.scrollBehavior)!=null?yf:{},ye!==ot()&&(zn(),No()),ko(),$r();let He=Ie;if(Ie=(vf=(bf=o.features)==null?void 0:bf.showEventStreamToggle)!=null?vf:!1,Ie&&!He){if(ge||(J=new Vs(de),ge=new qs(le,J),ue=ue!=null?ue:new $s,J.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),_.setSSEEventCallback((te,Et)=>{var jt;(jt=o.onSSEEvent)==null||jt.call(o,te,Et),ue==null||ue.processEvent(te,Et),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!ht&&qe){let te=(wf=(Cf=o.features)==null?void 0:Cf.eventStream)==null?void 0:wf.classNames,Et="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"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");ht=S("button",Et),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let jt=ve("activity","18px","currentColor",1.5);jt&&ht.appendChild(jt);let it=Y.clearChatButtonWrapper,It=Y.closeButtonWrapper,hr=it||It;hr&&hr.parentNode===qe?qe.insertBefore(ht,hr):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}}else!Ie&&He&&(yo(),ht&&(ht.remove(),ht=null),ge==null||ge.clear(),J==null||J.destroy(),ge=null,J=null,ue==null||ue.reset(),ue=null);if(((Sf=o.launcher)==null?void 0:Sf.enabled)===!1&&rr&&(rr.destroy(),rr=null),((Af=o.launcher)==null?void 0:Af.enabled)===!1&&mr&&(mr.remove(),mr=null),((Mf=o.launcher)==null?void 0:Mf.enabled)!==!1&&!rr&&!mr){let{instance:te,element:Et}=bp({config:o,plugins:n,onToggle:Jp});rr=te,te||(mr=Et),e.appendChild(Et)}rr&&rr.update(o),Xe&&((Tf=o.launcher)==null?void 0:Tf.title)!==void 0&&(Xe.textContent=o.launcher.title),et&&((Ef=o.launcher)==null?void 0:Ef.subtitle)!==void 0&&(et.textContent=o.launcher.subtitle);let Se=(kf=o.layout)==null?void 0:kf.header;if((Se==null?void 0:Se.layout)!==b&&qe){let te=Se?za(o,Se,{showClose:W(),onClose:()=>I(!1,"user")}):ln({config:o,showClose:W(),onClose:()=>I(!1,"user")});gt.replaceHeader(te),qe=gt.header.element,he=gt.header.iconHolder,Xe=gt.header.headerTitle,et=gt.header.headerSubtitle,j=gt.header.closeButton,b=Se==null?void 0:Se.layout}else if(Se&&(he&&(he.style.display=Se.showIcon===!1?"none":""),Xe&&(Xe.style.display=Se.showTitle===!1?"none":""),et&&(et.style.display=Se.showSubtitle===!1?"none":""),j&&(j.style.display=Se.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let te=Se.showClearChat;if(te!==void 0){Y.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Et}=Y;Et&&!Et.classList.contains("persona-absolute")&&(te?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let $e=((Lf=o.layout)==null?void 0:Lf.showHeader)!==!1;qe&&(qe.style.display=$e?"":"none");let ut=((Pf=o.layout)==null?void 0:Pf.showFooter)!==!1;Ne&&(Ne.style.display=ut?"":"none"),Ur(),$r(),E!==w?E?I(M,"auto"):(k=!0,U()):M!==y&&I(M,"auto"),y=M,w=E,fs(),nu();let Ee=JSON.stringify(l.toolCall)!==JSON.stringify(f),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Qe=JSON.stringify((Rf=o.layout)==null?void 0:Rf.messages)!==JSON.stringify(v),xt=((If=o.loadingIndicator)==null?void 0:If.render)!==(F==null?void 0:F.render)||((Wf=o.loadingIndicator)==null?void 0:Wf.renderIdle)!==(F==null?void 0:F.renderIdle)||((Hf=o.loadingIndicator)==null?void 0:Hf.showBubble)!==(F==null?void 0:F.showBubble),B=o.iterationDisplay!==$,Re=((Df=(Bf=o.features)==null?void 0:Bf.showReasoning)!=null?Df:!0)!==(O!=null?O:!0)||((Nf=(Ff=o.features)==null?void 0:Ff.showToolCalls)!=null?Nf:!0)!==(D!=null?D:!0)||JSON.stringify((Of=o.features)==null?void 0:Of.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((_f=o.features)==null?void 0:_f.reasoningDisplay)!==JSON.stringify(se);(Ee||ze||Qe||xt||B||Re)&&_&&(xa++,bn(Je,_.getMessages(),me));let fe=(Uf=o.launcher)!=null?Uf:{},Ut=(qf=fe.headerIconHidden)!=null?qf:!1,Ot=($f=(Vf=o.layout)==null?void 0:Vf.header)==null?void 0:$f.showIcon,Kt=Ut||Ot===!1,bt=fe.headerIconName,zt=(zf=fe.headerIconSize)!=null?zf:"48px";if(he){let te=pe.querySelector(".persona-border-b-persona-divider"),Et=te==null?void 0:te.querySelector(".persona-flex-col");if(Kt)he.style.display="none",te&&Et&&!te.contains(Et)&&te.insertBefore(Et,te.firstChild);else{if(he.style.display="",he.style.height=zt,he.style.width=zt,te&&Et&&(te.contains(he)?he.nextSibling!==Et&&(he.remove(),te.insertBefore(he,Et)):te.insertBefore(he,Et)),bt){let it=parseFloat(zt)||24,It=ve(bt,it*.6,"currentColor",1);It?he.replaceChildren(It):he.textContent=(jf=fe.agentIconText)!=null?jf:"\u{1F4AC}"}else if(fe.iconUrl){let it=he.querySelector("img");if(it)it.src=fe.iconUrl,it.style.height=zt,it.style.width=zt;else{let It=document.createElement("img");It.src=fe.iconUrl,It.alt="",It.className="persona-rounded-xl persona-object-cover",It.style.height=zt,It.style.width=zt,he.replaceChildren(It)}}else{let it=he.querySelector("svg"),It=he.querySelector("img");(it||It)&&he.replaceChildren(),he.textContent=(Gf=fe.agentIconText)!=null?Gf:"\u{1F4AC}"}let jt=he.querySelector("img");jt&&(jt.style.height=zt,jt.style.width=zt)}}let eo=(Xf=(Kf=o.layout)==null?void 0:Kf.header)==null?void 0:Xf.showTitle,or=(Jf=(Qf=o.layout)==null?void 0:Qf.header)==null?void 0:Jf.showSubtitle;if(Xe&&(Xe.style.display=eo===!1?"none":""),et&&(et.style.display=or===!1?"none":""),j){((Zf=(Yf=o.layout)==null?void 0:Yf.header)==null?void 0:Zf.showCloseButton)===!1?j.style.display="none":j.style.display="";let Et=(em=fe.closeButtonSize)!=null?em:"32px",jt=(tm=fe.closeButtonPlacement)!=null?tm:"inline";j.style.height=Et,j.style.width=Et;let{closeButtonWrapper:it}=Y,It=jt==="top-right",hr=it==null?void 0:it.classList.contains("persona-absolute");if(it&&It!==hr)if(it.remove(),It)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(it);else{let ct=(om=(rm=fe.clearChat)==null?void 0:rm.placement)!=null?om:"inline",xr=(am=(nm=fe.clearChat)==null?void 0:nm.enabled)!=null?am:!0;it.className=xr&&ct==="inline"?"":"persona-ml-auto";let zr=pe.querySelector(".persona-border-b-persona-divider");zr&&zr.appendChild(it)}if(j.style.color=fe.closeButtonColor||_r.actionIconColor,fe.closeButtonBackgroundColor?(j.style.backgroundColor=fe.closeButtonBackgroundColor,j.classList.remove("hover:persona-bg-gray-100")):(j.style.backgroundColor="",j.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let ct=fe.closeButtonBorderWidth||"0px",xr=fe.closeButtonBorderColor||"transparent";j.style.border=`${ct} solid ${xr}`,j.classList.remove("persona-border-none")}else j.style.border="",j.classList.add("persona-border-none");fe.closeButtonBorderRadius?(j.style.borderRadius=fe.closeButtonBorderRadius,j.classList.remove("persona-rounded-full")):(j.style.borderRadius="",j.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(j.style.paddingLeft=fe.closeButtonPaddingX,j.style.paddingRight=fe.closeButtonPaddingX):(j.style.paddingLeft="",j.style.paddingRight=""),fe.closeButtonPaddingY?(j.style.paddingTop=fe.closeButtonPaddingY,j.style.paddingBottom=fe.closeButtonPaddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Er=(sm=fe.closeButtonIconName)!=null?sm:"x",So=(im=fe.closeButtonIconText)!=null?im:"\xD7";j.innerHTML="";let Nr=ve(Er,"28px","currentColor",1);Nr?j.appendChild(Nr):j.textContent=So;let er=(lm=fe.closeButtonTooltipText)!=null?lm:"Close chat",ro=(dm=fe.closeButtonShowTooltip)!=null?dm:!0;if(j.setAttribute("aria-label",er),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!j)return;let Jn=j.ownerDocument,hs=Jn.body;if(!hs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let xs=Vo(Jn,"div");xs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(xs);let Yn=j.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",hs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};it.addEventListener("mouseenter",xr),it.addEventListener("mouseleave",zr),j.addEventListener("focus",xr),j.addEventListener("blur",zr),it._cleanupTooltip=()=>{zr(),it&&(it.removeEventListener("mouseenter",xr),it.removeEventListener("mouseleave",zr)),j&&(j.removeEventListener("focus",xr),j.removeEventListener("blur",zr))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Rt}=Y;if(Ye){let te=(cm=fe.clearChat)!=null?cm:{},Et=(pm=te.enabled)!=null?pm:!0,jt=(fm=(um=o.layout)==null?void 0:um.header)==null?void 0:fm.showClearChat,it=jt!==void 0?jt:Et,It=(mm=te.placement)!=null?mm:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:hr}=Y;!H()&&hr&&!hr.classList.contains("persona-absolute")&&(it?hr.classList.remove("persona-ml-auto"):hr.classList.add("persona-ml-auto"));let Er=It==="top-right",So=Rt.classList.contains("persona-absolute");if(!H()&&Er!==So&&it){if(Rt.remove(),Er)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",pe.style.position="relative",pe.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let er=pe.querySelector(".persona-border-b-persona-divider"),ro=Y.closeButtonWrapper;er&&ro&&ro.parentElement===er?er.insertBefore(Rt,ro):er&&er.appendChild(Rt)}let Nr=Y.closeButtonWrapper;Nr&&!Nr.classList.contains("persona-absolute")&&(Er?Nr.classList.add("persona-ml-auto"):Nr.classList.remove("persona-ml-auto"))}}if(it){if(!H()){let ct=(gm=te.size)!=null?gm:"32px";Ye.style.height=ct,Ye.style.width=ct}let hr=(hm=te.iconName)!=null?hm:"refresh-cw",Er=(xm=te.iconColor)!=null?xm:"";Ye.style.color=Er||_r.actionIconColor,Ye.innerHTML="";let So=H()?"14px":"20px",Nr=ve(hr,So,"currentColor",2);if(Nr&&Ye.appendChild(Nr),te.backgroundColor?(Ye.style.backgroundColor=te.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let ct=te.borderWidth||"0px",xr=te.borderColor||"transparent";Ye.style.border=`${ct} solid ${xr}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");te.borderRadius?(Ye.style.borderRadius=te.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),te.paddingX?(Ye.style.paddingLeft=te.paddingX,Ye.style.paddingRight=te.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),te.paddingY?(Ye.style.paddingTop=te.paddingY,Ye.style.paddingBottom=te.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let er=(ym=te.tooltipText)!=null?ym:"Clear chat",ro=(bm=te.showTooltip)!=null?bm:!0;if(Ye.setAttribute("aria-label",er),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!Ye)return;let Jn=Ye.ownerDocument,hs=Jn.body;if(!hs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let xs=Vo(Jn,"div");xs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(xs);let Yn=Ye.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",hs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};Rt.addEventListener("mouseenter",xr),Rt.addEventListener("mouseleave",zr),Ye.addEventListener("focus",xr),Ye.addEventListener("blur",zr),Rt._cleanupTooltip=()=>{zr(),Rt&&(Rt.removeEventListener("mouseenter",xr),Rt.removeEventListener("mouseleave",zr)),Ye&&(Ye.removeEventListener("focus",xr),Ye.removeEventListener("blur",zr))}}}}let cr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[js],go=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick];T=Gs({parsers:cr,handlers:go,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),me=nx(o,T,Z),_.updateConfig(o),bn(Je,_.getMessages(),me),ha(),K(),X(_.isStreaming());let to=((vm=o.voiceRecognition)==null?void 0:vm.enabled)===!0,jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Gn=((wm=(Cm=o.voiceRecognition)==null?void 0:Cm.provider)==null?void 0:wm.type)==="runtype";if(to&&(jn||Gn))if(!z||!Ht){let te=Vx(o.voiceRecognition,o.sendButton);te&&(z=te.micButton,Ht=te.micButtonWrapper,Jt.insertBefore(Ht,Cr),z.addEventListener("click",pi),z.disabled=_.isStreaming())}else{let te=(Sm=o.voiceRecognition)!=null?Sm:{},Et=(Am=o.sendButton)!=null?Am:{},jt=(Mm=te.iconName)!=null?Mm:"mic",it=(Tm=Et.size)!=null?Tm:"40px",It=(Em=te.iconSize)!=null?Em:it,hr=parseFloat(It)||24;z.style.width=It,z.style.height=It,z.style.minWidth=It,z.style.minHeight=It;let Er=(Lm=(km=te.iconColor)!=null?km:Et.textColor)!=null?Lm:"currentColor";z.innerHTML="";let So=ve(jt,hr,Er,2);So?z.appendChild(So):z.textContent="\u{1F3A4}";let Nr=(Pm=te.backgroundColor)!=null?Pm:Et.backgroundColor;Nr?z.style.backgroundColor=Nr:z.style.backgroundColor="",Er?z.style.color=Er:z.style.color="var(--persona-text, #111827)",te.borderWidth?(z.style.borderWidth=te.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),te.borderColor?z.style.borderColor=te.borderColor:z.style.borderColor="",te.paddingX?(z.style.paddingLeft=te.paddingX,z.style.paddingRight=te.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),te.paddingY?(z.style.paddingTop=te.paddingY,z.style.paddingBottom=te.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let er=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),ro=(Rm=te.tooltipText)!=null?Rm:"Start voice recognition";if(((Im=te.showTooltip)!=null?Im:!1)&&ro)if(er)er.textContent=ro,er.style.display="";else{let xr=document.createElement("div");xr.className="persona-send-button-tooltip",xr.textContent=ro,Ht==null||Ht.insertBefore(xr,z)}else er&&(er.style.display="none");Ht.style.display="",z.disabled=_.isStreaming()}else z&&Ht&&(Ht.style.display="none",((Hm=(Wm=o.voiceRecognition)==null?void 0:Wm.provider)==null?void 0:Hm.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():_o&&Sn());if(((Bm=o.attachments)==null?void 0:Bm.enabled)===!0)if(!we||!oe){let te=(Dm=o.attachments)!=null?Dm:{},jt=(Nm=((Fm=o.sendButton)!=null?Fm:{}).size)!=null?Nm:"40px";At||(At=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),At.style.display="none",Wt.insertBefore(At,ke)),De||(De=document.createElement("input"),De.type="file",De.accept=((Om=te.allowedTypes)!=null?Om:an).join(","),De.multiple=((_m=te.maxFiles)!=null?_m:4)>1,De.style.display="none",De.setAttribute("aria-label","Attach files"),Wt.insertBefore(De,ke)),we=S("div","persona-send-button-wrapper"),oe=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),oe.type="button",oe.setAttribute("aria-label",(Um=te.buttonTooltipText)!=null?Um:"Attach file");let it=(qm=te.buttonIconName)!=null?qm:"paperclip",It=jt,hr=parseFloat(It)||40,Er=Math.round(hr*.6);oe.style.width=It,oe.style.height=It,oe.style.minWidth=It,oe.style.minHeight=It,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.style.backgroundColor="transparent",oe.style.color="var(--persona-primary, #111827)",oe.style.border="none",oe.style.borderRadius="6px",oe.style.transition="background-color 0.15s ease",oe.addEventListener("mouseenter",()=>{oe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),oe.addEventListener("mouseleave",()=>{oe.style.backgroundColor="transparent"});let So=ve(it,Er,"currentColor",1.5);So?oe.appendChild(So):oe.textContent="\u{1F4CE}",oe.addEventListener("click",ro=>{ro.preventDefault(),De==null||De.click()}),we.appendChild(oe);let Nr=(Vm=te.buttonTooltipText)!=null?Vm:"Attach file",er=S("div","persona-send-button-tooltip");er.textContent=Nr,we.appendChild(er),Gt.append(we),!yt&&De&&At&&(yt=la.fromConfig(te),yt.setPreviewsContainer(At),De.addEventListener("change",async()=>{yt&&(De!=null&&De.files)&&(await yt.handleFileSelect(De.files),De.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(ax(te.dropOverlay))}else{we.style.display="";let te=($m=o.attachments)!=null?$m:{};De&&(De.accept=((zm=te.allowedTypes)!=null?zm:an).join(","),De.multiple=((jm=te.maxFiles)!=null?jm:4)>1),yt&&yt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else we&&(we.style.display="none"),yt&&yt.clearAttachments(),(Gm=pe.querySelector(".persona-attachment-drop-overlay"))==null||Gm.remove();let Xt=(Km=o.sendButton)!=null?Km:{},Kn=(Xm=Xt.useIcon)!=null?Xm:!1,Mn=(Qm=Xt.iconText)!=null?Qm:"\u2191",Tn=Xt.iconName,en=(Jm=Xt.tooltipText)!=null?Jm:"Send message",Xn=(Ym=Xt.showTooltip)!=null?Ym:!1,wo=(Zm=Xt.size)!=null?Zm:"40px",rt=Xt.backgroundColor,gr=Xt.textColor;if(Kn){if(je.style.width=wo,je.style.height=wo,je.style.minWidth=wo,je.style.minHeight=wo,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",gr?je.style.color=gr:je.style.color="var(--persona-button-primary-fg, #ffffff)",Tn){let te=parseFloat(wo)||24,Et=(gr==null?void 0:gr.trim())||"currentColor",jt=ve(Tn,te,Et,2);jt?je.appendChild(jt):je.textContent=Mn}else je.textContent=Mn;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(tg=(eg=o.copy)==null?void 0:eg.sendButtonLabel)!=null?tg:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.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",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),gr?je.style.color=gr:je.classList.add("persona-text-white");Xt.borderWidth?(je.style.borderWidth=Xt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Xt.borderColor?je.style.borderColor=Xt.borderColor:je.style.borderColor="",Xt.paddingX?(je.style.paddingLeft=Xt.paddingX,je.style.paddingRight=Xt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Xt.paddingY?(je.style.paddingTop=Xt.paddingY,je.style.paddingBottom=Xt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Vt=Cr==null?void 0:Cr.querySelector(".persona-send-button-tooltip");if(Xn&&en)if(Vt)Vt.textContent=en,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=en,Cr==null||Cr.insertBefore(te,je)}else Vt&&(Vt.style.display="none");let qt=(sg=(rg=o.layout)==null?void 0:rg.contentMaxWidth)!=null?sg:H()?(ag=(ng=(og=o.launcher)==null?void 0:og.composerBar)==null?void 0:ng.contentMaxWidth)!=null?ag:"720px":void 0;qt?(Je.style.maxWidth=qt,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%",Wt&&(Wt.style.maxWidth=qt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Ge&&(Ge.style.maxWidth=qt,Ge.style.marginLeft="auto",Ge.style.marginRight="auto")):(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight="",Je.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Ge&&(Ge.style.maxWidth="",Ge.style.marginLeft="",Ge.style.marginRight=""));let ft=(ig=o.statusIndicator)!=null?ig:{},Qt=(lg=ft.visible)!=null?lg:!0;if(ur.style.display=Qt?"":"none",_){let te=_.getStatus();Lt(ur,(jt=>{var it,It,hr,Er;return jt==="idle"?(it=ft.idleText)!=null?it:kr.idle:jt==="connecting"?(It=ft.connectingText)!=null?It:kr.connecting:jt==="connected"?(hr=ft.connectedText)!=null?hr:kr.connected:jt==="error"?(Er=ft.errorText)!=null?Er:kr.error:kr[jt]})(te),ft,te)}ur.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";ur.classList.add(St)},open(){W()&&I(!0,"api")},close(){W()&&I(!1,"api")},toggle(){W()&&I(!k,"api")},clearChat(){Ir=!1,_.clearMessages(),Bo.clear(),No();try{localStorage.removeItem(Ya),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ya}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ya)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()},setMessage(l){return!ke||_.isStreaming()?!1:(!k&&W()&&I(!0,"system"),ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=(l==null?void 0:l.trim())||ke.value.trim();return f?(!k&&W()&&I(!0,"system"),ke.value="",ke.style.height="auto",_.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return _.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!k&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("user"),_.isVoiceActive()&&Ta()})),!0):_o?!0:Qp()?(!k&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),di("user"),!0):!1},stopVoiceRecognition(){var l,f;return((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()}),!0):!1:_o?(mt.manuallyDeactivated=!0,Vr(),Sn("user"),!0):!1},injectMessage(l){return!k&&W()&&I(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&W()&&I(!0,"system");let f=_.injectAssistantMessage(l);return N&&(N=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!k&&W()&&I(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&W()&&I(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&W()&&I(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&W()&&I(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&W()&&I(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){ge&&(ue==null||ue.processEvent(l.type,l.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ie||!ge||zo()},hideEventStream(){ce&&yo()},isEventStreamVisible(){return ce},showArtifacts(){xo(o)&&(Ir=!1,Jr(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){xo(o)&&(Ir=!0,Jr())},upsertArtifact(l){return xo(o)?(Ir=!1,_.upsertArtifact(l)):null},selectArtifact(l){xo(o)&&_.selectArtifact(l)},clearArtifacts(){xo(o)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return E&&!k&&!H()||!ke?!1:(ke.focus(),!0)},async resolveApproval(l,f,h){let R=_.getMessages().find(F=>{var $;return F.variant==="approval"&&(($=F.approval)==null?void 0:$.id)===l});if(!(R!=null&&R.approval))throw new Error(`Approval not found: ${l}`);if(R.approval.toolType==="webmcp"){_.resolveWebMcpApproval(R.id,f);return}return _.resolveApproval(R.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){m(l)},on(l,f){return a.on(l,f)},off(l,f){a.off(l,f)},isOpen(){return W()&&k},isVoiceActive(){return mt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:W()&&k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=Ll({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitCSATFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=Pl({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitNPSFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return _.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return _.submitNPSFeedback(l,f)},destroy(){Ae!=null&&(clearInterval(Ae),Ae=null),dt.forEach(l=>l()),_e.remove(),Ze==null||Ze.remove(),rr==null||rr.destroy(),mr==null||mr.remove(),Wo&&j.removeEventListener("click",Wo)}};if((((of=r==null?void 0:r.debugTools)!=null?of:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,f={controller:dr,getMessages:dr.getMessages,getStatus:dr.getStatus,getMetadata:dr.getPersistentMetadata,updateMetadata:dr.updatePersistentMetadata,clearHistory:()=>dr.clearChat(),setVoiceActive:h=>h?dr.startVoiceRecognition():dr.stopVoiceRecognition()};window.AgentWidgetBrowser=f,dt.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.focusInput()};if(window.addEventListener("persona:focusInput",f),dt.push(()=>{window.removeEventListener("persona:focusInput",f)}),Ie){let O=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.showEventStream()},D=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",D),dt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",D)})}let h=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.showArtifacts()},v=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.hideArtifacts()},R=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&dr.upsertArtifact(D.artifact)},F=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&dr.selectArtifact(D.id)},$=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",$),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",$)})}let mo=Wv(o.persistState);if(mo&&W()){let l=Hv(mo.storage),f=`${mo.keyPrefix}widget-open`,h=`${mo.keyPrefix}widget-voice`,v=`${mo.keyPrefix}widget-voice-mode`;if(l){let R=((nf=mo.persist)==null?void 0:nf.openState)&&l.getItem(f)==="true",F=((af=mo.persist)==null?void 0:af.voiceState)&&l.getItem(h)==="true",$=((sf=mo.persist)==null?void 0:sf.voiceState)&&l.getItem(v)==="true";if(R&&setTimeout(()=>{dr.open(),setTimeout(()=>{var O;if(F||$)dr.startVoiceRecognition();else if((O=mo.persist)!=null&&O.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(lf=mo.persist)!=null&&lf.openState&&(a.on("widget:opened",()=>{l.setItem(f,"true")}),a.on("widget:closed",()=>{l.setItem(f,"false")})),(df=mo.persist)!=null&&df.voiceState&&(a.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),a.on("user:message",O=>{l.setItem(v,O.viaVoice?"true":"false")})),mo.clearOnChatClear){let O=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(v)},D=()=>O();window.addEventListener("persona:clear-chat",D),dt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return u&&W()&&setTimeout(()=>{dr.open()},0),Ve(),Qs||mi().then(()=>{_&&(xa++,Bo.clear(),bn(Je,_.getMessages(),me))}).catch(()=>{}),dr};var Bv=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},Dv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Fv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nv=(e,t)=>{let r=e.parentElement;if(!r)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!n||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},sx=(e,t)=>{var o,n;let r=(n=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?n:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},Dp=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=""},ix=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Dp(e)},Wp=e=>{e.style.transition=""},Hp=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="",e.style.marginLeft=""},Bp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Wl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ov=(e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))},_v=(e,t,r,o,n,a)=>{let s=a?t:e;n==="left"?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)},lx=(e,t,r,o,n,a,s)=>{var x,C,T,E,M,P;let i=no(a),c=i.reveal==="push";Ov(e,t,r,o,c),_v(e,t,r,o,i.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"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",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let d=e.ownerDocument.defaultView,u=(C=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,g=(E=(T=a==null?void 0:a.launcher)==null?void 0:T.mobileBreakpoint)!=null?E:640,p=d!=null?d.innerWidth<=g:!1;if(u&&p&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hp(t),Wp(o),ix(o),Bp(r),Wl(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((P=(M=a==null?void 0:a.launcher)==null?void 0:M.zIndex)!=null?P:Lr),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(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.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),ix(o),Dv(o,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Hp(t),Wp(o),Bp(r),Wl(n,o);let y=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",b=s?"translateX(0)":w;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=b,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",Wp(o),Dp(o),Wl(n,o);let y=Bv(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),b=i.animate?"margin-left 180ms ease":"none",A=i.side==="right"?s?-y:0:s?0:-y;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+y}px`,t.style.transition=b,t.style.marginLeft=`${A}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Hp(t),Dp(o),Bp(r),Wl(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",b=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",A=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${w}`,o.style.width=w,o.style.maxWidth=w,o.style.minWidth=w,o.style.minHeight="0",Fv(o,i.maxHeight),o.style.overflow=y||A?"hidden":"visible",o.style.transition=b,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},Uv=(e,t)=>{let r=e.ownerDocument.createElement("div");return sx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){sx(r,o)},destroy(){r.remove()}}},qv=(e,t)=>{var P,y,w,b;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),d=r.createElement("aside"),u=r.createElement("div"),g=(y=(P=t==null?void 0:t.launcher)==null?void 0:P.enabled)==null||y?(b=(w=t==null?void 0:t.launcher)==null?void 0:w.autoExpand)!=null?b:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",d.appendChild(u),o.insertBefore(s,e),c.appendChild(e);let p=null,m=()=>{p==null||p.disconnect(),p=null},x=()=>{m(),no(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(p=new ResizeObserver(()=>{lx(s,i,c,d,u,t,g)}),p.observe(s))},C=!1,T=()=>{lx(s,i,c,d,u,t,g),x(),g&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,Nv(s,no(t)))},E=s.ownerDocument.defaultView,M=()=>{T()};return E==null||E.addEventListener("resize",M),no(t).reveal==="push"?(i.appendChild(c),i.appendChild(d),s.appendChild(i)):(s.appendChild(c),s.appendChild(d)),T(),{mode:"docked",host:u,shell:s,syncWidgetState(A){let H=A.launcherEnabled?A.open:!0;g!==H&&(g=H,T())},updateConfig(A){var H,W;t=A,((W=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)!=null?W:!0)===!1&&(g=!0),T()},destroy(){E==null||E.removeEventListener("resize",M),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Ks=(e,t)=>pr(t)?qv(e,t):Uv(e,t);var Fp={},dx=!1,Vv=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},$v=()=>{try{if(typeof Fp!="undefined"&&Fp.url)return new URL("../widget.css",Fp.url).href}catch{}return null},cx=(e,t)=>{let r=$v(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let a=n.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(r){let n=t.createElement("link");n.rel="stylesheet",n.href=r,n.setAttribute("data-persona","true"),e.insertBefore(n,e.firstChild)}else o();else if(!t.head.querySelector("link[data-persona]")&&r){let a=t.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-persona","true"),t.head.appendChild(a)}},px=e=>{let t=Vv(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Ks(t,n),s,i=[],c=(T,E)=>{var w,b;let P=!((b=(w=E==null?void 0:E.launcher)==null?void 0:w.enabled)!=null?b:!0)||pr(E),y=o.createElement("div");if(y.setAttribute("data-persona-root","true"),P&&(y.style.height="100%",y.style.display="flex",y.style.flexDirection="column",y.style.flex="1",y.style.minHeight="0"),r){let A=T.attachShadow({mode:"open"});A.appendChild(y),cx(A,o)}else T.appendChild(y),cx(T,o);return t.id&&y.setAttribute("data-persona-instance",t.id),y},d=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},g=()=>{let T=c(a.host,n);s=Il(T,n,{debugTools:e.debugTools}),u()},p=()=>{i.forEach(T=>T()),i=[],s.destroy()};g(),e.onChatReady?e.onChatReady():e.onReady&&(dx||(dx=!0,console.warn("[Persona] `onReady` is deprecated: use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=T=>{p(),a.destroy(),a=Ks(t,T),n=T,g()},x={update(T){var b,A,H,W,k,N;let E={...n,...T,launcher:{...(b=n==null?void 0:n.launcher)!=null?b:{},...(A=T==null?void 0:T.launcher)!=null?A:{},dock:{...(W=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?W:{},...(N=(k=T==null?void 0:T.launcher)==null?void 0:k.dock)!=null?N:{}}}},M=pr(n),P=pr(E),y=Dn(n),w=Dn(E);if(M!==P||y!==w){m(E);return}n=E,a.updateConfig(n),s.update(T),d()},destroy(){p(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(x,{get(T,E,M){if(E==="host")return a.host;if(E in T)return Reflect.get(T,E,M);let P=s[E];return typeof P=="function"?P.bind(s):P}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var hx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),zv=new Set(["button","a","input","select","textarea","details","summary"]),jv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Np=/\b(product|card|item|listing|result)\b/i,_p=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Gv=3e3,Kv=100;function xx(e){let t=typeof e.className=="string"?e.className:"";if(Np.test(t)||e.id&&Np.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Np.test(o.value))return!0}return!1}function yx(e){var t;return _p.test(((t=e.textContent)!=null?t:"").trim())}function bx(e){var r;let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=(r=t[o].getAttribute("href"))!=null?r:"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function Xv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ux(e){let t=e.match(_p);return t?t[0]:null}function fx(e){var o,n,a;let t=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(t&&((n=t.textContent)!=null&&n.trim())){let s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function Qv(e){let t=[],r=o=>{let n=o.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;r((n=o.value)!=null?n:"")}),t.slice(0,6)}var Jv="commerce-card",Yv="result-card";function mx(e){return!xx(e)||!yx(e)||!bx(e)&&!Xv(e)?0:5200}function gx(e){var o;return!xx(e)||yx(e)||!bx(e)||((o=e.textContent)!=null?o:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Up=[{id:Jv,scoreElement(e){return mx(e)},shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if(r.interactivity==="static"){let o=r.text.trim();return!!(o.length===0||_p.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,d,u;if(mx(e)===0)return null;let{title:r,href:o}=fx(e),n=(u=(d=ux(((c=e.textContent)!=null?c:"").trim()))!=null?d:ux(t.text))!=null?u:"",a=Qv(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
111
|
+
`)}},{id:Yv,scoreElement(e){return gx(e)},formatSummary(e,t){if(gx(e)===0)return null;let{title:r,href:o}=fx(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
112
|
+
`)}}];function Zv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function e0(e){var u,g,p,m,x,C,T,E,M,P,y,w,b;let t=(u=e.options)!=null?u:{},r=(p=(g=t.maxElements)!=null?g:e.maxElements)!=null?p:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(T=(C=t.maxTextLength)!=null?C:e.maxTextLength)!=null?T:200,a=(M=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?M:!0,s=(P=t.root)!=null?P:e.root,i=(y=t.mode)!=null?y:"structured",c=(w=t.maxCandidates)!=null?w:Math.max(500,r*10),d=(b=e.rules)!=null?b:Up;return i==="simple"&&e.rules&&e.rules.length>0?(Zv(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}function Op(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var t0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function r0(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":t==="button"||r==="button"||zv.has(t)||r&&jv.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function vx(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 o0(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let c=e.getAttribute("role");c&&(t.role=c);for(let d=0;d<e.attributes.length;d++){let u=e.attributes[d];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function qp(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Op(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of t0){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${Op(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let r=Array.from(e.classList).filter(n=>n&&!n.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(s=>Op(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}let a=e.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let c=`${n}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let o=e.parentElement;if(o){let a=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function n0(e){return e==="static"?Kv:Gv}function Cx(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:qp(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:r0(e),attributes:o0(e)}}function a0(e,t,r,o){let n=n0(t.interactivity),a=null;for(let s of r){let i=s.scoreElement(e,t,o);i>0&&(n+=i,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function s0(e,t){var r;for(let o of e)if(t.el!==o.el&&(r=o.formattingRule)!=null&&r.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function i0(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,u=d.tagName.toLowerCase();if(hx.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!vx(d)){i=s.nextNode();continue}let g=Cx(d,e.maxTextLength),p=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(T=>T==="role");if(!p&&!m){i=s.nextNode();continue}if(o.has(g.selector)){i=s.nextNode();continue}o.add(g.selector);let{score:x,formattingRule:C}=a0(d,g,e.rules,r);n.push({el:d,domIndex:a,enriched:g,score:x,formattingRule:C}),a+=1}i=s.nextNode()}n.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex});let c=[];for(let d of n){if(c.length>=e.maxElements)break;s0(c,d)||c.push(d)}return c.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:g===1&&u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex}),c.map(d=>{var p;let u;if((p=d.formattingRule)!=null&&p.formatSummary){let m=d.formattingRule.formatSummary(d.el,d.enriched,r);m&&(u=m)}let g={...d.enriched};return u&&(g.formattedSummary=u),g})}function l0(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,d=c.tagName.toLowerCase();if(hx.has(d)){a=n.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!vx(c)){a=n.nextNode();continue}let u=Cx(c,e.maxTextLength),g=u.text.length>0,p=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!g&&!p){a=n.nextNode();continue}o.has(u.selector)||(o.add(u.selector),r.push(u))}a=n.nextNode()}let s=[],i=[];for(let c of r)c.interactivity!=="static"?s.push(c):i.push(c);return[...s,...i].slice(0,e.maxElements)}function wx(e={}){var o;let t=e0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?l0(t,r):i0(t,r):[]}var Hl=100;function Sx(e,t={}){var a;if(e.length===0)return"No page elements found.";let r=(a=t.mode)!=null?a:"structured",o=[];if(r==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
|
|
158
113
|
${s.map(i=>`- ${i.split(`
|
|
159
114
|
`).join(`
|
|
160
115
|
`)}`).join(`
|
|
161
|
-
`)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of r
|
|
116
|
+
`)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of e)r==="structured"&&s.formattedSummary||n[s.interactivity].push(s);if(n.clickable.length>0){let s=n.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Hl)}" (clickable)`);o.push(`Interactive elements:
|
|
162
117
|
${s.join(`
|
|
163
|
-
`)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
118
|
+
`)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Hl)}" (navigable)`);o.push(`Navigation links:
|
|
164
119
|
${s.join(`
|
|
165
|
-
`)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
120
|
+
`)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Hl)}" (input)`);o.push(`Form inputs:
|
|
166
121
|
${s.join(`
|
|
167
|
-
`)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
122
|
+
`)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Hl)}"`);o.push(`Content:
|
|
168
123
|
${s.join(`
|
|
169
124
|
`)}`)}return o.join(`
|
|
170
125
|
|
|
171
|
-
`)}
|
|
126
|
+
`)}function Ax(){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 Mx(){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 Tx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var o;let r={...t.palette};return(o=e.colors)!=null&&o.primary&&(r.colors={...r.colors,primary:{50:$o(e.colors.primary,.95),100:$o(e.colors.primary,.9),200:$o(e.colors.primary,.8),300:$o(e.colors.primary,.7),400:$o(e.colors.primary,.6),500:e.colors.primary,600:$o(e.colors.primary,.8),700:$o(e.colors.primary,.7),800:$o(e.colors.primary,.6),900:$o(e.colors.primary,.5),950:$o(e.colors.primary,.45)}}),{...t,palette:r}}}}function Ex(){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 kx(){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 $o(e,t){let r=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),n=parseInt(e.slice(5,7),16),a=Math.round(r+(255-r)*(1-t)),s=Math.round(o+(255-o)*(1-t)),i=Math.round(n+(255-n)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Lx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var d0={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"}}},Px={components:{panel:{borderRadius:"0",shadow:"none"}}},Vp={id:"shop",label:"Shopping Assistant",config:{theme:d0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:oo},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?"]}},$p={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Px}},zp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Px}},jp={shop:Vp,minimal:$p,fullscreen:zp};function Rx(e){return jp[e]}var c0=`
|
|
172
127
|
@keyframes persona-stream-wipe {
|
|
173
128
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
174
129
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -204,7 +159,7 @@ ${s.join(`
|
|
|
204
159
|
mask-image: none !important;
|
|
205
160
|
}
|
|
206
161
|
}
|
|
207
|
-
`.trim(),
|
|
162
|
+
`.trim(),p0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:c0};ca(p0);var u0=`
|
|
208
163
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
209
164
|
animation: persona-stream-glyph-cycle-fade
|
|
210
165
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -222,12 +177,9 @@ ${s.join(`
|
|
|
222
177
|
opacity: 1 !important;
|
|
223
178
|
}
|
|
224
179
|
}
|
|
225
|
-
`.trim(),
|
|
180
|
+
`.trim(),Xs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",f0=10,m0=120,Gp=120,g0=.4,h0=50,x0=e=>{var o;if(!e)return Gp;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Gp},Ox=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=x0(t);return m0*r/Gp},Kp=e=>{let t=Xs[Math.floor(Math.random()*Xs.length)];return e&&t===e&&(t=Xs[(Xs.indexOf(t)+1)%Xs.length]),t},y0=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let r=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let n of Array.from(r)){if(n===e){o=!0;continue}o&&Math.random()<g0&&(n.textContent=Kp())}},Ix=new WeakMap,Wx=25,Hx=.5,b0=6,Bx=.25,Dx=new WeakMap,Fx=new WeakMap,v0=(e,t)=>{var n;if(!e)return Wx*Hx;let r=Dx.get(e);Dx.set(e,t);let o=(n=Fx.get(e))!=null?n:Wx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Bx)+a*Bx,Fx.set(e,o))}return Math.max(b0,o*Hx)},Za=new Map,C0=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},w0=e=>{var t;e&&Za.set(e,((t=Za.get(e))!=null?t:0)+1)},S0=e=>{var r;if(!e)return;let t=(r=Za.get(e))!=null?r:0;t<=1?Za.delete(e):Za.set(e,t-1)},_x=e=>{var d;if(e.dataset.glyphCycleScheduled==="true")return;let t=(d=e.textContent)!=null?d:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Kp();let r=C0(e);r&&(e.dataset.glyphCycleMessageId=r),w0(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=v0(o,n),s=Ox(e),i=f0*s,c=n+i;if(o){let u=Ix.get(o);u!==void 0&&(c=Math.max(c,u)),Ix.set(o,c+a)}A0(e,t,c)},A0=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=Ox(e),n=(s=e.textContent)!=null?s:void 0,a=()=>{var c;if(!e.isConnected)return;if(Date.now()>=r){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,S0((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Kp(n);e.textContent=i,n=i,y0(e),setTimeout(a,o)};setTimeout(a,o)},Nx=e=>{var r;let t=(r=e.querySelectorAll)==null?void 0:r.call(e,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let o of Array.from(t))_x(o)},M0=e=>e.nodeType===1,T0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:u0,bufferContent(e){if(e.length<h0)return"";let t=0,r=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(r=o),o+=1}return r<0?"":e.slice(0,r)},isAnimating(e){var t;return((t=Za.get(e.id))!=null?t:0)>0},onAttach(e){Nx(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))M0(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?_x(n):Nx(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ca(T0);var Ux,qx,nr=typeof document!="undefined"&&(qx=(Ux=document.currentScript)==null?void 0:Ux.src)!=null?qx:null;bg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});pg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});mi().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});th(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});return ty(E0);})();
|
|
226
181
|
/*! Bundled license information:
|
|
227
182
|
|
|
228
|
-
dompurify/dist/purify.es.mjs:
|
|
229
|
-
(*! @license DOMPurify 3.4.10 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.10/LICENSE *)
|
|
230
|
-
|
|
231
183
|
lucide/dist/esm/icons/activity.mjs:
|
|
232
184
|
lucide/dist/esm/icons/arrow-down.mjs:
|
|
233
185
|
lucide/dist/esm/icons/arrow-left.mjs:
|