@runtypelabs/persona 3.23.0 → 3.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
- "use strict";var Wf=Object.create;var Ga=Object.defineProperty;var Bf=Object.getOwnPropertyDescriptor;var Hf=Object.getOwnPropertyNames;var Df=Object.getPrototypeOf,Ff=Object.prototype.hasOwnProperty;var Of=(e,t)=>{for(var n in t)Ga(e,n,{get:t[n],enumerable:!0})},Cu=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Hf(t))!Ff.call(e,r)&&r!==n&&Ga(e,r,{get:()=>t[r],enumerable:!(o=Bf(t,r))||o.enumerable});return e};var Su=(e,t,n)=>(n=e!=null?Wf(Df(e)):{},Cu(t||!e||!e.__esModule?Ga(n,"default",{value:e,enumerable:!0}):n,e)),Nf=e=>Cu(Ga({},"__esModule",{value:!0}),e);var Ry={};Of(Ry,{ADVANCED_TOKENS_SECTION:()=>Tl,ALL_ROLES:()=>or,ALL_TABS:()=>si,BRAND_PALETTE_SECTION:()=>wl,BUILT_IN_PRESETS:()=>kl,COLORS_SECTIONS:()=>Vu,COLOR_FAMILIES:()=>oi,COMPONENTS_SECTIONS:()=>bl,COMPONENT_COLOR_SECTIONS:()=>hl,COMPONENT_SHAPE_SECTIONS:()=>gl,CONFIGURE_SECTIONS:()=>vl,CONFIGURE_SUB_GROUPS:()=>Ks,CONTRAST_PAIRS:()=>cs,CSS_NAMED_COLORS:()=>Ca,DEVICE_DIMENSIONS:()=>Br,HOME_SUGGESTION_CHIPS:()=>gc,INTERFACE_ROLES_SECTION:()=>Sl,MOCK_BROWSER_CONTENT:()=>bc,MOCK_WORKSPACE_CONTENT:()=>yc,PALETTE_SECTION:()=>Nu,PREVIEW_STORAGE_ADAPTER:()=>fc,RADIUS_PRESETS:()=>ds,ROLE_ASSISTANT_MESSAGES:()=>Ns,ROLE_BORDERS:()=>zs,ROLE_FAMILIES:()=>Hs,ROLE_FAMILY_LABELS:()=>Du,ROLE_HEADER:()=>Fs,ROLE_INPUT:()=>$s,ROLE_INTENSITIES:()=>xo,ROLE_LINKS_FOCUS:()=>Us,ROLE_PRIMARY_ACTIONS:()=>_s,ROLE_SCROLL_TO_BOTTOM:()=>Vs,ROLE_SURFACES:()=>Ds,ROLE_USER_MESSAGES:()=>Os,SEMANTIC_COLORS_SECTION:()=>_u,SHADE_KEYS:()=>Tr,SHELL_STYLE_ID:()=>ya,STATUS_COLORS_SECTION:()=>Al,STATUS_PALETTE_SECTION:()=>Cl,STYLE_SECTIONS:()=>kr,STYLE_SECTIONS_V2:()=>$u,THEME_EDITOR_PRESETS:()=>Qr,THEME_SECTION:()=>xl,ThemeEditorState:()=>Qa,ZOOM_MAX:()=>Qi,ZOOM_MIN:()=>Xi,appendPreviewTranscriptEntry:()=>yf,applySceneConfig:()=>nl,applyShellTheme:()=>Zi,buildPreviewConfig:()=>cr,buildPreviewConfigWithMessages:()=>xf,buildShellCss:()=>Ji,buildSrcdoc:()=>el,buildSummary:()=>dr,buildTranscriptStreamFrames:()=>vf,coerceColor:()=>Hr,coerceFamily:()=>Sa,coerceIntensity:()=>Aa,coerceRadius:()=>Ea,coerceRoundnessStyle:()=>ka,coerceScheme:()=>Ta,convertFromPx:()=>Wu,convertToPx:()=>Pu,createPreviewMessages:()=>xc,createPreviewTranscriptEntry:()=>tl,createThemeEditorTools:()=>Ac,createThemePreview:()=>Cf,detectRoleAssignment:()=>ri,escapeHtml:()=>va,findSection:()=>zu,formatCssValue:()=>Za,generateColorScale:()=>ni,getPreviewTranscriptPresetLabel:()=>bf,getShellPalette:()=>hc,getThemeEditorPreset:()=>ai,hexToHsl:()=>ul,hslToHex:()=>ml,isValidHex:()=>ei,normalizeColorValue:()=>Xr,paletteColorPath:()=>Bu,parseCssValue:()=>Ja,presetStreamsText:()=>vc,quickContrastWarnings:()=>Dr,resolveRoleAssignment:()=>qs,resolveThemeColorPath:()=>fl,rgbToHex:()=>ti,runContrastChecks:()=>us,scopeSection:()=>qu,tokenRefDisplayName:()=>Hu,toolResult:()=>Io,wcagContrastRatio:()=>Bs});module.exports=Nf(Ry);var Au=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Au(s)&&Au(r)?n[o]=Ws(s,r):n[o]=r}return n}var lo="min(440px, calc(100vw - 24px))",Ya="440px",Et={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:lo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Tu(e,t){if(!(!e&&!t))return e?t?Ws(e,t):e:t}function ku(e){var t,n,o,r,s,a,i,d,l,u,p,g,m,w,x,L,W,B,D,V,H;return e?{...Et,...e,theme:Tu(Et.theme,e.theme),darkTheme:Tu(Et.darkTheme,e.darkTheme),launcher:{...Et.launcher,...e.launcher,dock:{...(t=Et.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Et.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Et.copy,...e.copy},sendButton:{...Et.sendButton,...e.sendButton},statusIndicator:{...Et.statusIndicator,...e.statusIndicator},voiceRecognition:{...Et.voiceRecognition,...e.voiceRecognition},features:(()=>{var Ce,Be,ve,ee,Me,Q,Te,he;let v=(Ce=Et.features)==null?void 0:Ce.artifacts,C=(Be=e.features)==null?void 0:Be.artifacts,M=(ve=Et.features)==null?void 0:ve.scrollToBottom,A=(ee=e.features)==null?void 0:ee.scrollToBottom,E=(Me=Et.features)==null?void 0:Me.streamAnimation,F=(Q=e.features)==null?void 0:Q.streamAnimation,U=(Te=Et.features)==null?void 0:Te.askUserQuestion,j=(he=e.features)==null?void 0:he.askUserQuestion,fe=v===void 0&&C===void 0?void 0:{...v,...C,layout:{...v==null?void 0:v.layout,...C==null?void 0:C.layout}},se=M===void 0&&A===void 0?void 0:{...M,...A},ye=E===void 0&&F===void 0?void 0:{...E,...F},le=U===void 0&&j===void 0?void 0:{...U,...j,styles:{...U==null?void 0:U.styles,...j==null?void 0:j.styles}};return{...Et.features,...e.features,...se!==void 0?{scrollToBottom:se}:{},...fe!==void 0?{artifacts:fe}:{},...ye!==void 0?{streamAnimation:ye}:{},...le!==void 0?{askUserQuestion:le}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Et.suggestionChips,suggestionChipsConfig:{...Et.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Et.layout,...e.layout,header:{...(a=Et.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Et.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Et.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(g=e.layout)==null?void 0:g.messages)==null?void 0:m.avatar},timestamp:{...(x=(w=Et.layout)==null?void 0:w.messages)==null?void 0:x.timestamp,...(W=(L=e.layout)==null?void 0:L.messages)==null?void 0:W.timestamp}},slots:{...(B=Et.layout)==null?void 0:B.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{...Et.markdown,...e.markdown,options:{...(V=Et.markdown)==null?void 0:V.options,...(H=e.markdown)==null?void 0:H.options}},messageActions:{...Et.messageActions,...e.messageActions}}:Et}var _f={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"}},Vf={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"}},$f={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:lo,maxWidth:Ya,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Gr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gr(e,o):o}function Eu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Gr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Uf(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Mu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Mu(s,r):n[o]=r}return n}function zf(e,t){return t?Mu(e,t):e}function on(e,t={}){var r,s,a,i,d,l,u,p,g,m,w,x,L;let n={palette:_f,semantic:Vf,components:$f},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(g=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(w=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(L=e==null?void 0:e.semantic)==null?void 0:L.typography}},components:zf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let W=Uf(o);if(!W.valid)throw new Error(`Theme validation failed: ${W.errors.map(B=>B.message).join(", ")}`)}if(t.plugins)for(let W of t.plugins)o=W.transform(o);return o}function Lu(e){var x,L,W,B,D,V,H,v,C,M,A,E,F,U,j,fe,se,ye,le,Ce,Be,ve,ee,Me,Q,Te,he,ce,me,Ke,K,re,Pe,nt,ge,de,Ve,Ie,pe,X,$e,St,J,Oe,In,Ot,cn,Fn,Zn,N,ae,De,Qe,Ne,_e,rt,At,_t,Kt,G,gt,ot,Ut,ie,xe,Ct,Vt,Zt,xn,Mt,Tt,bt,vt,zt,et,On,eo,wn,Nn,mt,So,_n,pr,Rn,Fr,Uo,Ro,xt,Vn,$n,Cn,Pt,to,no,Un,zo,Po,qo,zn,Bt,Sn,oo,jo,Wo,Ko,Ao,qn,uo,ht,Gt,Yt,jn,Go,ro,mo,Kn;let t=Eu(e),n={};for(let[k,Gn]of Object.entries(t)){let fo=k.replace(/\./g,"-");n[`--persona-${fo}`]=Gn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(L=n["--persona-semantic-colors-secondary"])!=null?L:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(W=n["--persona-semantic-colors-accent"])!=null?W:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(B=n["--persona-semantic-colors-surface"])!=null?B:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(D=n["--persona-semantic-colors-background"])!=null?D:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(V=n["--persona-semantic-colors-container"])!=null?V:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(H=n["--persona-semantic-colors-text"])!=null?H:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(C=n["--persona-semantic-colors-text-inverse"])!=null?C:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(M=n["--persona-semantic-colors-border"])!=null?M:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(A=n["--persona-semantic-colors-divider"])!=null?A:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(E=n["--persona-components-voice-recording-indicator"])!=null?E:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(F=n["--persona-components-voice-recording-background"])!=null?F:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(U=n["--persona-components-voice-processing-icon"])!=null?U:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(j=n["--persona-components-voice-speaking-icon"])!=null?j:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(fe=n["--persona-components-approval-requested-background"])!=null?fe:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(se=n["--persona-components-approval-requested-border"])!=null?se:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ye=n["--persona-components-approval-requested-text"])!=null?ye:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(le=n["--persona-components-approval-approve-background"])!=null?le:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Ce=n["--persona-components-approval-deny-background"])!=null?Ce:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Be=n["--persona-components-attachment-image-background"])!=null?Be:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ve=n["--persona-components-attachment-image-border"])!=null?ve:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ee=n["--persona-semantic-typography-fontFamily"])!=null?ee:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Me=n["--persona-semantic-typography-fontSize"])!=null?Me:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Q=n["--persona-semantic-typography-fontWeight"])!=null?Q:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Te=n["--persona-semantic-typography-lineHeight"])!=null?Te:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(he=n["--persona-palette-radius-sm"])!=null?he:"0.125rem",n["--persona-radius-md"]=(ce=n["--persona-palette-radius-md"])!=null?ce:"0.375rem",n["--persona-radius-lg"]=(me=n["--persona-palette-radius-lg"])!=null?me:"0.5rem",n["--persona-radius-xl"]=(Ke=n["--persona-palette-radius-xl"])!=null?Ke:"0.75rem",n["--persona-radius-full"]=(K=n["--persona-palette-radius-full"])!=null?K:"9999px",n["--persona-launcher-radius"]=(Pe=(re=n["--persona-components-launcher-borderRadius"])!=null?re:n["--persona-palette-radius-full"])!=null?Pe:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(ge=n["--persona-components-launcher-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-launcher-border"]=(de=n["--persona-components-launcher-border"])!=null?de:n["--persona-border"],n["--persona-button-primary-bg"]=(Ve=n["--persona-components-button-primary-background"])!=null?Ve:n["--persona-primary"],n["--persona-button-primary-fg"]=(Ie=n["--persona-components-button-primary-foreground"])!=null?Ie:n["--persona-text-inverse"],n["--persona-button-radius"]=(X=(pe=n["--persona-components-button-primary-borderRadius"])!=null?pe:n["--persona-palette-radius-full"])!=null?X:"9999px",n["--persona-panel-radius"]=(St=($e=n["--persona-components-panel-borderRadius"])!=null?$e:n["--persona-radius-xl"])!=null?St:"0.75rem",n["--persona-panel-border"]=(J=n["--persona-components-panel-border"])!=null?J:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(In=(Oe=n["--persona-components-panel-shadow"])!=null?Oe:n["--persona-palette-shadows-xl"])!=null?In:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(cn=(Ot=n["--persona-components-input-borderRadius"])!=null?Ot:n["--persona-radius-lg"])!=null?cn:"0.5rem",n["--persona-message-user-radius"]=(Zn=(Fn=n["--persona-components-message-user-borderRadius"])!=null?Fn:n["--persona-radius-lg"])!=null?Zn:"0.5rem",n["--persona-message-assistant-radius"]=(ae=(N=n["--persona-components-message-assistant-borderRadius"])!=null?N:n["--persona-radius-lg"])!=null?ae:"0.5rem",n["--persona-header-bg"]=(De=n["--persona-components-header-background"])!=null?De:n["--persona-surface"],n["--persona-header-border"]=(Qe=n["--persona-components-header-border"])!=null?Qe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ne=n["--persona-components-header-iconBackground"])!=null?Ne:n["--persona-primary"],n["--persona-header-icon-fg"]=(_e=n["--persona-components-header-iconForeground"])!=null?_e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(rt=n["--persona-components-header-titleForeground"])!=null?rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(At=n["--persona-components-header-subtitleForeground"])!=null?At:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(_t=n["--persona-components-header-actionIconForeground"])!=null?_t:n["--persona-muted"];let o=(Kt=e.components)==null?void 0:Kt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(G=e.components)==null?void 0:G.introCard;n["--persona-intro-card-bg"]=(gt=n["--persona-components-introCard-background"])!=null?gt:n["--persona-surface"],n["--persona-intro-card-radius"]=(ot=n["--persona-components-introCard-borderRadius"])!=null?ot:"1rem",n["--persona-intro-card-padding"]=(Ut=n["--persona-components-introCard-padding"])!=null?Ut:"1.5rem",n["--persona-intro-card-shadow"]=(xe=(ie=r==null?void 0:r.shadow)!=null?ie:n["--persona-components-introCard-shadow"])!=null?xe:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ct=n["--persona-components-input-background"])!=null?Ct:n["--persona-surface"],n["--persona-input-placeholder"]=(Vt=n["--persona-components-input-placeholder"])!=null?Vt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Zt=n["--persona-components-message-user-background"])!=null?Zt:n["--persona-accent"],n["--persona-message-user-text"]=(xn=n["--persona-components-message-user-text"])!=null?xn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Mt=n["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Tt=n["--persona-components-message-assistant-background"])!=null?Tt:n["--persona-surface"],n["--persona-message-assistant-text"]=(bt=n["--persona-components-message-assistant-text"])!=null?bt:n["--persona-text"],n["--persona-message-assistant-border"]=(vt=n["--persona-components-message-assistant-border"])!=null?vt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(On=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?On:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(wn=(eo=n["--persona-components-scrollToBottom-foreground"])!=null?eo:n["--persona-button-primary-fg"])!=null?wn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Nn=n["--persona-components-scrollToBottom-border"])!=null?Nn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(mt=n["--persona-components-scrollToBottom-size"])!=null?mt:"40px",n["--persona-scroll-to-bottom-radius"]=(pr=(_n=(So=n["--persona-components-scrollToBottom-borderRadius"])!=null?So:n["--persona-button-radius"])!=null?_n:n["--persona-radius-full"])!=null?pr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Fr=(Rn=n["--persona-components-scrollToBottom-shadow"])!=null?Rn:n["--persona-palette-shadows-sm"])!=null?Fr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Uo=n["--persona-components-scrollToBottom-padding"])!=null?Uo:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Ro=n["--persona-components-scrollToBottom-gap"])!=null?Ro:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Vn=(xt=n["--persona-components-scrollToBottom-fontSize"])!=null?xt:n["--persona-palette-typography-fontSize-sm"])!=null?Vn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($n=n["--persona-components-scrollToBottom-iconSize"])!=null?$n:"14px",n["--persona-tool-bubble-shadow"]=(Cn=n["--persona-components-toolBubble-shadow"])!=null?Cn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Pt=n["--persona-components-reasoningBubble-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(to=n["--persona-components-composer-shadow"])!=null?to:"none",n["--persona-md-inline-code-bg"]=(no=n["--persona-components-markdown-inlineCode-background"])!=null?no:n["--persona-container"],n["--persona-md-inline-code-color"]=(Un=n["--persona-components-markdown-inlineCode-foreground"])!=null?Un:n["--persona-text"],n["--persona-md-link-color"]=(Po=(zo=n["--persona-components-markdown-link-foreground"])!=null?zo:n["--persona-accent"])!=null?Po:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(qo=n["--persona-components-markdown-codeBlock-background"])!=null?qo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(zn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?zn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Bt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Bt:"inherit",n["--persona-md-table-header-bg"]=(Sn=n["--persona-components-markdown-table-headerBackground"])!=null?Sn:n["--persona-container"],n["--persona-md-table-border-color"]=(oo=n["--persona-components-markdown-table-borderColor"])!=null?oo:n["--persona-border"],n["--persona-md-hr-color"]=(jo=n["--persona-components-markdown-hr-color"])!=null?jo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Wo=n["--persona-components-markdown-blockquote-borderColor"])!=null?Wo:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Ko=n["--persona-components-markdown-blockquote-background"])!=null?Ko:"transparent",n["--persona-md-blockquote-text-color"]=(Ao=n["--persona-components-markdown-blockquote-textColor"])!=null?Ao:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(qn=n["--persona-components-collapsibleWidget-container"])!=null?qn:n["--persona-surface"],n["--cw-surface"]=(uo=n["--persona-components-collapsibleWidget-surface"])!=null?uo:n["--persona-surface"],n["--cw-border"]=(ht=n["--persona-components-collapsibleWidget-border"])!=null?ht:n["--persona-border"],n["--persona-message-border"]=(Gt=n["--persona-components-message-border"])!=null?Gt:n["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let g=u==null?void 0:u.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let w=u==null?void 0:u.artifact;if(w!=null&&w.toolbar){let k=w.toolbar;k.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=k.iconHoverColor),k.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=k.iconHoverBackground),k.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=k.iconPadding),k.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=k.iconBorderRadius),k.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=k.iconBorder),k.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=k.toggleGroupGap),k.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=k.toggleBorderRadius),k.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=k.copyBackground),k.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=k.copyBorder),k.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=k.copyColor),k.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=k.copyBorderRadius),k.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=k.copyPadding),k.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=k.copyMenuBackground,n["--persona-dropdown-bg"]=(Yt=n["--persona-dropdown-bg"])!=null?Yt:k.copyMenuBackground),k.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=k.copyMenuBorder,n["--persona-dropdown-border"]=(jn=n["--persona-dropdown-border"])!=null?jn:k.copyMenuBorder),k.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=k.copyMenuShadow,n["--persona-dropdown-shadow"]=(Go=n["--persona-dropdown-shadow"])!=null?Go:k.copyMenuShadow),k.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=k.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ro=n["--persona-dropdown-radius"])!=null?ro:k.copyMenuBorderRadius),k.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=k.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(mo=n["--persona-dropdown-item-hover-bg"])!=null?mo:k.copyMenuItemHoverBackground),k.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=k.iconBackground),k.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=k.toolbarBorder)}if(w!=null&&w.tab){let k=w.tab;k.background&&(n["--persona-artifact-tab-bg"]=k.background),k.activeBackground&&(n["--persona-artifact-tab-active-bg"]=k.activeBackground),k.activeBorder&&(n["--persona-artifact-tab-active-border"]=k.activeBorder),k.borderRadius&&(n["--persona-artifact-tab-radius"]=k.borderRadius),k.textColor&&(n["--persona-artifact-tab-color"]=k.textColor),k.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=k.hoverBackground),k.listBackground&&(n["--persona-artifact-tab-list-bg"]=k.listBackground),k.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=k.listBorderColor),k.listPadding&&(n["--persona-artifact-tab-list-padding"]=k.listPadding)}if(w!=null&&w.pane){let k=w.pane;if(k.toolbarBackground){let Gn=(Kn=Gr(e,k.toolbarBackground))!=null?Kn:k.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Gn}}return n}var qf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Iu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},dl=()=>{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"},jf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":dl()},Kf=e=>jf(e),Gf=e=>on(e),Yf=e=>{var n;let t=on(void 0,{validate:!1});return on({...e,palette:{...t.palette,colors:{...qf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Xa=e=>{let t=Kf(e),n=Iu(e==null?void 0:e.theme),o=Iu(e==null?void 0:e.darkTheme);return t==="dark"?Yf(Ws(n!=null?n:{},o!=null?o:{})):Gf(n)},Xf=e=>Lu(e),Yr=(e,t)=>{var s;let n=Xa(t),o=Xf(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},Ru=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(dl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(dl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function pl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Ar(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:Ar((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var Qa=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...Et,...n}:n!=null?n:Et,this.theme=on(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?pl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?pl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):pl(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=Ar(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:on();this.config={...this.config,darkTheme:Ar(s,r,n)}}else this.config=Ar(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=Ar(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:on();this.config={...this.config,darkTheme:Ar(l,d,i)},o=!0}else this.config=Ar(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=on((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=on(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Et},this.theme=on(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=on(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Ja(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function Za(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Pu(e,t){return t==="rem"?e*16:e}function Wu(e,t){return t==="rem"?e/16:e}function Xr(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function ei(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function ti(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),u=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(u)?Math.max(0,Math.min(255,Math.round(l?u/100*255:u))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Bs(e,t){let n=s=>{var l;let a=Xr(s),i=a.startsWith("rgb")?(l=ti(a))!=null?l:"#000000":a,d=[1,3,5].map(u=>{let p=parseInt(i.slice(u,u+2),16)/255;return p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ul(e){var g;let t=Xr(e),n=t.startsWith("rgb")?(g=ti(t))!=null?g:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,u=d>.5?l/(2-a-i):l/(a+i),p;switch(a){case o:p=((r-s)/l+(r<s?6:0))/6;break;case r:p=((s-o)/l+2)/6;break;default:p=((o-r)/l+4)/6;break}return{h:p*360,s:u,l:d}}function ml(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let u=p=>{let g=Math.round((p+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${u(i)}${u(d)}${u(l)}`}function ni(e){let{h:t,s:n,l:o}=ul(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=ml(t,l,d)}return a}var Tr=["50","100","200","300","400","500","600","700","800","900","950"],oi=["primary","secondary","accent","gray","success","warning","error","info"];function Bu(e,t){return`palette.colors.${e}.${t}`}function fl(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?fl(e,`theme.${o}`,n+1):"#cbd5e1"}function Hu(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var xo=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Hs=["primary","secondary","accent","gray"],Du={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ds={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:xo,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Fs={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:xo,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Os={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:xo,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Ns={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:xo,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},_s={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:xo,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},Vs={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:xo,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},$s={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:xo,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},Us={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:xo,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},zs={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:xo,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},or=[Ds,Fs,Os,Ns,_s,Vs,$s,Us,zs];function qs(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Qf(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Qf(e,t,n,o){let r=t==="solid";if(o==="role-header")return Jf(e,r,n);if(o==="role-input")return Zf(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function Jf(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function Zf(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var eg=/^palette\.colors\.(\w+)\.(\d+)$/;function ri(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(eg);if(!r)return null;let s=r[1],a=Hs.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=qs(a,l,t);if(t.targets.every(g=>{var w;return String((w=e(g.path))!=null?w:"")===u[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var tg={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},ng={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},og={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},rg={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},sg={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},ag={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},ig={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},lg={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},kr=[ng,og,sg,rg,tg,ag,ig,lg];function Fu(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:oi.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var Ou={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Nu=Fu(),_u=Ou,Vu=[Fu(),Ou],cg={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:lo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ya},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},dg={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},pg={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},ug={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},mg={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},fg={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},gg={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},hg={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},bg={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},yg={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},gl=[cg,dg,pg,ug,mg],hl=[fg,gg,hg,bg,yg],bl=[...gl,...hl],yl=1024*1024,vg=["What can you help me with?","Tell me about your features","How does this work?"],js={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","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"]};function xg(e){return Number(e)*yl}function wg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/yl)):String(t):"10"}function Cg(e){var t;return(t=js[String(e)])!=null?t:js.images}function Sg(e){let t=Array.isArray(e)?e:js.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(js)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var Ag={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},Tg={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:vg}]},kg={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},Eg={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},Mg={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},Lg={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},Ig={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:lo},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},Rg={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},Pg={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},Wg={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},Bg={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},Hg={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},Dg={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},Fg={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},Og={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*yl,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:wg,parseValue:xg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:js.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Sg,parseValue:Cg}]},Ng={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},_g={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},Vg={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},$g={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},Ug={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Ks=[{label:"Content",sections:[Ag,Tg]},{label:"Layout",sections:[kg,Eg,Mg,Lg]},{label:"Widget",sections:[Ig,Rg,Pg,Wg,Bg,Hg]},{label:"Features",sections:[Dg,Fg,Og,Ng,_g]},{label:"Developer",collapsedByDefault:!0,sections:[Vg,$g,Ug]}],vl=Ks.flatMap(e=>e.sections),xl={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},wl={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},Cl={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},Sl={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:Ds},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Fs},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Os},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ns},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:_s},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Vs},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:$s},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Us},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:zs}]},Al={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},Tl={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},$u=[xl,wl,Cl,Sl,Al,Tl],si=[{id:"style",label:"Style",sections:kr},{id:"design-system",label:"Design System",sections:bl},{id:"configure",label:"Configure",sections:vl}];function Uu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function zg(e,t,n){return{...e,id:`${n}-${e.id}`,path:Uu(e.path,t)}}function zu(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function qu(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>zg(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[Uu(d,t),l]))}))}}var kl=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},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"},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"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Qr=[...kl];function ai(e){return Qr.find(t=>t.id===e)}var ju=require("marked"),qg=e=>{if(e)return e},El=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new ju.Marked({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=qg(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},ii=e=>e?El({markedOptions:e.options,renderer:e.renderer}):El(),Jy=El();var Gs=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Ku=Su(require("dompurify"),1),jg={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"]},Kg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Gg=()=>{let e=(0,Ku.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Kg.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,jg)},li=e=>e===!1?null:typeof e=="function"?e:Gg();var Ml="webmcp:",ci={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},di=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ci.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Qg(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return wo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let m=typeof document!="undefined"&&!!document.modelContext;return wo(m?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Yg(t),a;try{a=await r.getTools()}catch(m){let w=m instanceof Error?m.message:String(m);return wo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(m=>m.name===s);if(!i)return wo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return wo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return wo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return wo("User declined the tool call.");if(o!=null&&o.aborted)return wo("Aborted by cancel()");let l=new AbortController,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),g=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",g,{once:!0}));try{let m=await r.executeTool(i,th(n),{signal:l.signal});return Jg(m)}catch(m){if(u)return wo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return wo("Aborted by cancel()");let w=m instanceof Error?m.message:String(m);return wo(w)}finally{clearTimeout(p),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ci.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ci.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Zg;try{return await n(t)}catch(r){return ci.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Xg(t,o))}},Yg=e=>e.startsWith(Ml)?e.slice(Ml.length):e,Ll=e=>e.startsWith(Ml),Xg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Qg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Jg=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:nh(t)}]}},wo=e=>({isError:!0,content:[{type:"text",text:e}]}),Zg=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=eh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var Bg=Object.create;var Ga=Object.defineProperty;var Hg=Object.getOwnPropertyDescriptor;var Dg=Object.getOwnPropertyNames;var Fg=Object.getPrototypeOf,Og=Object.prototype.hasOwnProperty;var Ng=(e,t)=>{for(var n in t)Ga(e,n,{get:t[n],enumerable:!0})},Cu=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Dg(t))!Og.call(e,r)&&r!==n&&Ga(e,r,{get:()=>t[r],enumerable:!(o=Hg(t,r))||o.enumerable});return e};var Su=(e,t,n)=>(n=e!=null?Bg(Fg(e)):{},Cu(t||!e||!e.__esModule?Ga(n,"default",{value:e,enumerable:!0}):n,e)),_g=e=>Cu(Ga({},"__esModule",{value:!0}),e);var By={};Ng(By,{ADVANCED_TOKENS_SECTION:()=>Tl,ALL_ROLES:()=>or,ALL_TABS:()=>si,BRAND_PALETTE_SECTION:()=>wl,BUILT_IN_PRESETS:()=>kl,COLORS_SECTIONS:()=>Vu,COLOR_FAMILIES:()=>oi,COMPONENTS_SECTIONS:()=>bl,COMPONENT_COLOR_SECTIONS:()=>hl,COMPONENT_SHAPE_SECTIONS:()=>fl,CONFIGURE_SECTIONS:()=>vl,CONFIGURE_SUB_GROUPS:()=>Ks,CONTRAST_PAIRS:()=>cs,CSS_NAMED_COLORS:()=>Ca,DEVICE_DIMENSIONS:()=>Br,HOME_SUGGESTION_CHIPS:()=>fc,INTERFACE_ROLES_SECTION:()=>Sl,MOCK_BROWSER_CONTENT:()=>bc,MOCK_WORKSPACE_CONTENT:()=>yc,PALETTE_SECTION:()=>Nu,PREVIEW_STORAGE_ADAPTER:()=>gc,RADIUS_PRESETS:()=>ds,ROLE_ASSISTANT_MESSAGES:()=>Ns,ROLE_BORDERS:()=>zs,ROLE_FAMILIES:()=>Hs,ROLE_FAMILY_LABELS:()=>Du,ROLE_HEADER:()=>Fs,ROLE_INPUT:()=>$s,ROLE_INTENSITIES:()=>xo,ROLE_LINKS_FOCUS:()=>Us,ROLE_PRIMARY_ACTIONS:()=>_s,ROLE_SCROLL_TO_BOTTOM:()=>Vs,ROLE_SURFACES:()=>Ds,ROLE_USER_MESSAGES:()=>Os,SEMANTIC_COLORS_SECTION:()=>_u,SHADE_KEYS:()=>Tr,SHELL_STYLE_ID:()=>ya,STATUS_COLORS_SECTION:()=>Al,STATUS_PALETTE_SECTION:()=>Cl,STYLE_SECTIONS:()=>kr,STYLE_SECTIONS_V2:()=>$u,THEME_EDITOR_PRESETS:()=>Qr,THEME_SECTION:()=>xl,ThemeEditorState:()=>Qa,ZOOM_MAX:()=>Qi,ZOOM_MIN:()=>Xi,appendPreviewTranscriptEntry:()=>vg,applySceneConfig:()=>nl,applyShellTheme:()=>Zi,buildPreviewConfig:()=>cr,buildPreviewConfigWithMessages:()=>wg,buildShellCss:()=>Ji,buildSrcdoc:()=>el,buildSummary:()=>dr,buildTranscriptStreamFrames:()=>xg,coerceColor:()=>Hr,coerceFamily:()=>Sa,coerceIntensity:()=>Aa,coerceRadius:()=>Ea,coerceRoundnessStyle:()=>ka,coerceScheme:()=>Ta,convertFromPx:()=>Wu,convertToPx:()=>Pu,createPreviewMessages:()=>xc,createPreviewTranscriptEntry:()=>tl,createThemeEditorTools:()=>Ac,createThemePreview:()=>Sg,detectRoleAssignment:()=>ri,escapeHtml:()=>va,findSection:()=>zu,formatCssValue:()=>Za,generateColorScale:()=>ni,getPreviewTranscriptPresetLabel:()=>yg,getShellPalette:()=>hc,getThemeEditorPreset:()=>ai,hexToHsl:()=>ul,hslToHex:()=>ml,isValidHex:()=>ei,normalizeColorValue:()=>Xr,paletteColorPath:()=>Bu,parseCssValue:()=>Ja,presetStreamsText:()=>vc,quickContrastWarnings:()=>Dr,resolveRoleAssignment:()=>qs,resolveThemeColorPath:()=>gl,rgbToHex:()=>ti,runContrastChecks:()=>us,scopeSection:()=>qu,tokenRefDisplayName:()=>Hu,toolResult:()=>Io,wcagContrastRatio:()=>Bs});module.exports=_g(By);var Au=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Au(s)&&Au(r)?n[o]=Ws(s,r):n[o]=r}return n}var lo="min(440px, calc(100vw - 24px))",Ya="440px",Et={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:lo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Tu(e,t){if(!(!e&&!t))return e?t?Ws(e,t):e:t}function ku(e){var t,n,o,r,s,a,i,d,l,u,p,f,g,x,C,L,B,I,D,F,H;return e?{...Et,...e,theme:Tu(Et.theme,e.theme),darkTheme:Tu(Et.darkTheme,e.darkTheme),launcher:{...Et.launcher,...e.launcher,dock:{...(t=Et.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Et.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Et.copy,...e.copy},sendButton:{...Et.sendButton,...e.sendButton},statusIndicator:{...Et.statusIndicator,...e.statusIndicator},voiceRecognition:{...Et.voiceRecognition,...e.voiceRecognition},features:(()=>{var Ce,Be,ve,ee,Me,Q,Te,he;let v=(Ce=Et.features)==null?void 0:Ce.artifacts,w=(Be=e.features)==null?void 0:Be.artifacts,M=(ve=Et.features)==null?void 0:ve.scrollToBottom,A=(ee=e.features)==null?void 0:ee.scrollToBottom,E=(Me=Et.features)==null?void 0:Me.streamAnimation,O=(Q=e.features)==null?void 0:Q.streamAnimation,U=(Te=Et.features)==null?void 0:Te.askUserQuestion,j=(he=e.features)==null?void 0:he.askUserQuestion,ge=v===void 0&&w===void 0?void 0:{...v,...w,layout:{...v==null?void 0:v.layout,...w==null?void 0:w.layout}},se=M===void 0&&A===void 0?void 0:{...M,...A},ye=E===void 0&&O===void 0?void 0:{...E,...O},le=U===void 0&&j===void 0?void 0:{...U,...j,styles:{...U==null?void 0:U.styles,...j==null?void 0:j.styles}};return{...Et.features,...e.features,...se!==void 0?{scrollToBottom:se}:{},...ge!==void 0?{artifacts:ge}:{},...ye!==void 0?{streamAnimation:ye}:{},...le!==void 0?{askUserQuestion:le}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Et.suggestionChips,suggestionChipsConfig:{...Et.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Et.layout,...e.layout,header:{...(a=Et.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Et.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Et.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(C=(x=Et.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(B=(L=e.layout)==null?void 0:L.messages)==null?void 0:B.timestamp}},slots:{...(I=Et.layout)==null?void 0:I.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{...Et.markdown,...e.markdown,options:{...(F=Et.markdown)==null?void 0:F.options,...(H=e.markdown)==null?void 0:H.options}},messageActions:{...Et.messageActions,...e.messageActions}}:Et}var Vg={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"}},$g={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"}},Ug={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:lo,maxWidth:Ya,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Gr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gr(e,o):o}function Eu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Gr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function zg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Mu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Mu(s,r):n[o]=r}return n}function qg(e,t){return t?Mu(e,t):e}function on(e,t={}){var r,s,a,i,d,l,u,p,f,g,x,C,L;let n={palette:Vg,semantic:$g,components:Ug},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...n.semantic.typography,...(L=e==null?void 0:e.semantic)==null?void 0:L.typography}},components:qg(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let B=zg(o);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let B of t.plugins)o=B.transform(o);return o}function Lu(e){var C,L,B,I,D,F,H,v,w,M,A,E,O,U,j,ge,se,ye,le,Ce,Be,ve,ee,Me,Q,Te,he,ce,me,Ke,K,re,Pe,nt,fe,de,Ve,Ie,pe,X,$e,St,J,Oe,In,Ot,cn,Fn,Zn,_,ae,De,Qe,Ne,_e,rt,At,_t,Kt,G,ft,ot,Ut,ie,xe,Ct,Vt,Zt,xn,Mt,Tt,bt,vt,zt,et,On,eo,wn,Nn,mt,So,_n,pr,Rn,Fr,Uo,Ro,xt,Vn,$n,Cn,Pt,to,no,Un,zo,Po,qo,zn,Bt,Sn,oo,jo,Wo,Ko,Ao,qn,uo,ht,Gt,Yt,jn,Go,ro,mo,Kn;let t=Eu(e),n={};for(let[k,Gn]of Object.entries(t)){let go=k.replace(/\./g,"-");n[`--persona-${go}`]=Gn.value}n["--persona-primary"]=(C=n["--persona-semantic-colors-primary"])!=null?C:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(L=n["--persona-semantic-colors-secondary"])!=null?L:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(B=n["--persona-semantic-colors-accent"])!=null?B:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(D=n["--persona-semantic-colors-background"])!=null?D:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(F=n["--persona-semantic-colors-container"])!=null?F:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(H=n["--persona-semantic-colors-text"])!=null?H:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(w=n["--persona-semantic-colors-text-inverse"])!=null?w:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(M=n["--persona-semantic-colors-border"])!=null?M:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(A=n["--persona-semantic-colors-divider"])!=null?A:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(E=n["--persona-components-voice-recording-indicator"])!=null?E:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(U=n["--persona-components-voice-processing-icon"])!=null?U:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(j=n["--persona-components-voice-speaking-icon"])!=null?j:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ge=n["--persona-components-approval-requested-background"])!=null?ge:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(se=n["--persona-components-approval-requested-border"])!=null?se:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ye=n["--persona-components-approval-requested-text"])!=null?ye:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(le=n["--persona-components-approval-approve-background"])!=null?le:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Ce=n["--persona-components-approval-deny-background"])!=null?Ce:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Be=n["--persona-components-attachment-image-background"])!=null?Be:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ve=n["--persona-components-attachment-image-border"])!=null?ve:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ee=n["--persona-semantic-typography-fontFamily"])!=null?ee:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Me=n["--persona-semantic-typography-fontSize"])!=null?Me:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Q=n["--persona-semantic-typography-fontWeight"])!=null?Q:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Te=n["--persona-semantic-typography-lineHeight"])!=null?Te:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(he=n["--persona-palette-radius-sm"])!=null?he:"0.125rem",n["--persona-radius-md"]=(ce=n["--persona-palette-radius-md"])!=null?ce:"0.375rem",n["--persona-radius-lg"]=(me=n["--persona-palette-radius-lg"])!=null?me:"0.5rem",n["--persona-radius-xl"]=(Ke=n["--persona-palette-radius-xl"])!=null?Ke:"0.75rem",n["--persona-radius-full"]=(K=n["--persona-palette-radius-full"])!=null?K:"9999px",n["--persona-launcher-radius"]=(Pe=(re=n["--persona-components-launcher-borderRadius"])!=null?re:n["--persona-palette-radius-full"])!=null?Pe:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(fe=n["--persona-components-launcher-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-launcher-border"]=(de=n["--persona-components-launcher-border"])!=null?de:n["--persona-border"],n["--persona-button-primary-bg"]=(Ve=n["--persona-components-button-primary-background"])!=null?Ve:n["--persona-primary"],n["--persona-button-primary-fg"]=(Ie=n["--persona-components-button-primary-foreground"])!=null?Ie:n["--persona-text-inverse"],n["--persona-button-radius"]=(X=(pe=n["--persona-components-button-primary-borderRadius"])!=null?pe:n["--persona-palette-radius-full"])!=null?X:"9999px",n["--persona-panel-radius"]=(St=($e=n["--persona-components-panel-borderRadius"])!=null?$e:n["--persona-radius-xl"])!=null?St:"0.75rem",n["--persona-panel-border"]=(J=n["--persona-components-panel-border"])!=null?J:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(In=(Oe=n["--persona-components-panel-shadow"])!=null?Oe:n["--persona-palette-shadows-xl"])!=null?In:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(cn=(Ot=n["--persona-components-input-borderRadius"])!=null?Ot:n["--persona-radius-lg"])!=null?cn:"0.5rem",n["--persona-message-user-radius"]=(Zn=(Fn=n["--persona-components-message-user-borderRadius"])!=null?Fn:n["--persona-radius-lg"])!=null?Zn:"0.5rem",n["--persona-message-assistant-radius"]=(ae=(_=n["--persona-components-message-assistant-borderRadius"])!=null?_:n["--persona-radius-lg"])!=null?ae:"0.5rem",n["--persona-header-bg"]=(De=n["--persona-components-header-background"])!=null?De:n["--persona-surface"],n["--persona-header-border"]=(Qe=n["--persona-components-header-border"])!=null?Qe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ne=n["--persona-components-header-iconBackground"])!=null?Ne:n["--persona-primary"],n["--persona-header-icon-fg"]=(_e=n["--persona-components-header-iconForeground"])!=null?_e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(rt=n["--persona-components-header-titleForeground"])!=null?rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(At=n["--persona-components-header-subtitleForeground"])!=null?At:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(_t=n["--persona-components-header-actionIconForeground"])!=null?_t:n["--persona-muted"];let o=(Kt=e.components)==null?void 0:Kt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(G=e.components)==null?void 0:G.introCard;n["--persona-intro-card-bg"]=(ft=n["--persona-components-introCard-background"])!=null?ft:n["--persona-surface"],n["--persona-intro-card-radius"]=(ot=n["--persona-components-introCard-borderRadius"])!=null?ot:"1rem",n["--persona-intro-card-padding"]=(Ut=n["--persona-components-introCard-padding"])!=null?Ut:"1.5rem",n["--persona-intro-card-shadow"]=(xe=(ie=r==null?void 0:r.shadow)!=null?ie:n["--persona-components-introCard-shadow"])!=null?xe:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ct=n["--persona-components-input-background"])!=null?Ct:n["--persona-surface"],n["--persona-input-placeholder"]=(Vt=n["--persona-components-input-placeholder"])!=null?Vt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Zt=n["--persona-components-message-user-background"])!=null?Zt:n["--persona-accent"],n["--persona-message-user-text"]=(xn=n["--persona-components-message-user-text"])!=null?xn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Mt=n["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Tt=n["--persona-components-message-assistant-background"])!=null?Tt:n["--persona-surface"],n["--persona-message-assistant-text"]=(bt=n["--persona-components-message-assistant-text"])!=null?bt:n["--persona-text"],n["--persona-message-assistant-border"]=(vt=n["--persona-components-message-assistant-border"])!=null?vt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(On=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?On:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(wn=(eo=n["--persona-components-scrollToBottom-foreground"])!=null?eo:n["--persona-button-primary-fg"])!=null?wn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Nn=n["--persona-components-scrollToBottom-border"])!=null?Nn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(mt=n["--persona-components-scrollToBottom-size"])!=null?mt:"40px",n["--persona-scroll-to-bottom-radius"]=(pr=(_n=(So=n["--persona-components-scrollToBottom-borderRadius"])!=null?So:n["--persona-button-radius"])!=null?_n:n["--persona-radius-full"])!=null?pr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Fr=(Rn=n["--persona-components-scrollToBottom-shadow"])!=null?Rn:n["--persona-palette-shadows-sm"])!=null?Fr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Uo=n["--persona-components-scrollToBottom-padding"])!=null?Uo:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Ro=n["--persona-components-scrollToBottom-gap"])!=null?Ro:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Vn=(xt=n["--persona-components-scrollToBottom-fontSize"])!=null?xt:n["--persona-palette-typography-fontSize-sm"])!=null?Vn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($n=n["--persona-components-scrollToBottom-iconSize"])!=null?$n:"14px",n["--persona-tool-bubble-shadow"]=(Cn=n["--persona-components-toolBubble-shadow"])!=null?Cn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Pt=n["--persona-components-reasoningBubble-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(to=n["--persona-components-composer-shadow"])!=null?to:"none",n["--persona-md-inline-code-bg"]=(no=n["--persona-components-markdown-inlineCode-background"])!=null?no:n["--persona-container"],n["--persona-md-inline-code-color"]=(Un=n["--persona-components-markdown-inlineCode-foreground"])!=null?Un:n["--persona-text"],n["--persona-md-link-color"]=(Po=(zo=n["--persona-components-markdown-link-foreground"])!=null?zo:n["--persona-accent"])!=null?Po:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(qo=n["--persona-components-markdown-codeBlock-background"])!=null?qo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(zn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?zn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Bt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Bt:"inherit",n["--persona-md-table-header-bg"]=(Sn=n["--persona-components-markdown-table-headerBackground"])!=null?Sn:n["--persona-container"],n["--persona-md-table-border-color"]=(oo=n["--persona-components-markdown-table-borderColor"])!=null?oo:n["--persona-border"],n["--persona-md-hr-color"]=(jo=n["--persona-components-markdown-hr-color"])!=null?jo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Wo=n["--persona-components-markdown-blockquote-borderColor"])!=null?Wo:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Ko=n["--persona-components-markdown-blockquote-background"])!=null?Ko:"transparent",n["--persona-md-blockquote-text-color"]=(Ao=n["--persona-components-markdown-blockquote-textColor"])!=null?Ao:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(qn=n["--persona-components-collapsibleWidget-container"])!=null?qn:n["--persona-surface"],n["--cw-surface"]=(uo=n["--persona-components-collapsibleWidget-surface"])!=null?uo:n["--persona-surface"],n["--cw-border"]=(ht=n["--persona-components-collapsibleWidget-border"])!=null?ht:n["--persona-border"],n["--persona-message-border"]=(Gt=n["--persona-components-message-border"])!=null?Gt:n["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=u==null?void 0:u.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let k=x.toolbar;k.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=k.iconHoverColor),k.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=k.iconHoverBackground),k.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=k.iconPadding),k.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=k.iconBorderRadius),k.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=k.iconBorder),k.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=k.toggleGroupGap),k.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=k.toggleBorderRadius),k.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=k.copyBackground),k.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=k.copyBorder),k.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=k.copyColor),k.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=k.copyBorderRadius),k.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=k.copyPadding),k.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=k.copyMenuBackground,n["--persona-dropdown-bg"]=(Yt=n["--persona-dropdown-bg"])!=null?Yt:k.copyMenuBackground),k.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=k.copyMenuBorder,n["--persona-dropdown-border"]=(jn=n["--persona-dropdown-border"])!=null?jn:k.copyMenuBorder),k.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=k.copyMenuShadow,n["--persona-dropdown-shadow"]=(Go=n["--persona-dropdown-shadow"])!=null?Go:k.copyMenuShadow),k.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=k.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ro=n["--persona-dropdown-radius"])!=null?ro:k.copyMenuBorderRadius),k.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=k.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(mo=n["--persona-dropdown-item-hover-bg"])!=null?mo:k.copyMenuItemHoverBackground),k.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=k.iconBackground),k.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=k.toolbarBorder)}if(x!=null&&x.tab){let k=x.tab;k.background&&(n["--persona-artifact-tab-bg"]=k.background),k.activeBackground&&(n["--persona-artifact-tab-active-bg"]=k.activeBackground),k.activeBorder&&(n["--persona-artifact-tab-active-border"]=k.activeBorder),k.borderRadius&&(n["--persona-artifact-tab-radius"]=k.borderRadius),k.textColor&&(n["--persona-artifact-tab-color"]=k.textColor),k.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=k.hoverBackground),k.listBackground&&(n["--persona-artifact-tab-list-bg"]=k.listBackground),k.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=k.listBorderColor),k.listPadding&&(n["--persona-artifact-tab-list-padding"]=k.listPadding)}if(x!=null&&x.pane){let k=x.pane;if(k.toolbarBackground){let Gn=(Kn=Gr(e,k.toolbarBackground))!=null?Kn:k.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Gn}}return n}var jg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Iu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},dl=()=>{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"},Kg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":dl()},Gg=e=>Kg(e),Yg=e=>on(e),Xg=e=>{var n;let t=on(void 0,{validate:!1});return on({...e,palette:{...t.palette,colors:{...jg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Xa=e=>{let t=Gg(e),n=Iu(e==null?void 0:e.theme),o=Iu(e==null?void 0:e.darkTheme);return t==="dark"?Xg(Ws(n!=null?n:{},o!=null?o:{})):Yg(n)},Qg=e=>Lu(e),Yr=(e,t)=>{var s;let n=Xa(t),o=Qg(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},Ru=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(dl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(dl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function pl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Ar(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:Ar((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var Qa=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...Et,...n}:n!=null?n:Et,this.theme=on(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?pl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?pl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):pl(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=Ar(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:on();this.config={...this.config,darkTheme:Ar(s,r,n)}}else this.config=Ar(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=Ar(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:on();this.config={...this.config,darkTheme:Ar(l,d,i)},o=!0}else this.config=Ar(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=on((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=on(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Et},this.theme=on(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=on(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Ja(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function Za(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Pu(e,t){return t==="rem"?e*16:e}function Wu(e,t){return t==="rem"?e/16:e}function Xr(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function ei(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function ti(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),u=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(u)?Math.max(0,Math.min(255,Math.round(l?u/100*255:u))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Bs(e,t){let n=s=>{var l;let a=Xr(s),i=a.startsWith("rgb")?(l=ti(a))!=null?l:"#000000":a,d=[1,3,5].map(u=>{let p=parseInt(i.slice(u,u+2),16)/255;return p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ul(e){var f;let t=Xr(e),n=t.startsWith("rgb")?(f=ti(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,u=d>.5?l/(2-a-i):l/(a+i),p;switch(a){case o:p=((r-s)/l+(r<s?6:0))/6;break;case r:p=((s-o)/l+2)/6;break;default:p=((o-r)/l+4)/6;break}return{h:p*360,s:u,l:d}}function ml(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let u=p=>{let f=Math.round((p+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${u(i)}${u(d)}${u(l)}`}function ni(e){let{h:t,s:n,l:o}=ul(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=ml(t,l,d)}return a}var Tr=["50","100","200","300","400","500","600","700","800","900","950"],oi=["primary","secondary","accent","gray","success","warning","error","info"];function Bu(e,t){return`palette.colors.${e}.${t}`}function gl(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?gl(e,`theme.${o}`,n+1):"#cbd5e1"}function Hu(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var xo=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Hs=["primary","secondary","accent","gray"],Du={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ds={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:xo,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Fs={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:xo,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Os={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:xo,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Ns={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:xo,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},_s={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:xo,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},Vs={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:xo,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},$s={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:xo,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},Us={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:xo,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},zs={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:xo,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},or=[Ds,Fs,Os,Ns,_s,Vs,$s,Us,zs];function qs(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Jg(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Jg(e,t,n,o){let r=t==="solid";if(o==="role-header")return Zg(e,r,n);if(o==="role-input")return ef(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function Zg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function ef(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var tf=/^palette\.colors\.(\w+)\.(\d+)$/;function ri(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(tf);if(!r)return null;let s=r[1],a=Hs.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=qs(a,l,t);if(t.targets.every(f=>{var x;return String((x=e(f.path))!=null?x:"")===u[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var nf={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},of={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},rf={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},sf={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},af={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},lf={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},cf={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},df={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},kr=[of,rf,af,sf,nf,lf,cf,df];function Fu(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:oi.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var Ou={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Nu=Fu(),_u=Ou,Vu=[Fu(),Ou],pf={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:lo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ya},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},uf={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},mf={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},gf={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},ff={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},hf={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},bf={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},yf={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},vf={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},xf={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},fl=[pf,uf,mf,gf,ff],hl=[hf,bf,yf,vf,xf],bl=[...fl,...hl],yl=1024*1024,wf=["What can you help me with?","Tell me about your features","How does this work?"],js={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","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"]};function Cf(e){return Number(e)*yl}function Sf(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/yl)):String(t):"10"}function Af(e){var t;return(t=js[String(e)])!=null?t:js.images}function Tf(e){let t=Array.isArray(e)?e:js.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(js)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var kf={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},Ef={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:wf}]},Mf={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},Lf={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},If={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},Rf={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},Pf={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:lo},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},Wf={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},Bf={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},Hf={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},Df={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},Ff={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},Of={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},Nf={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},_f={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*yl,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:Sf,parseValue:Cf},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:js.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Tf,parseValue:Af}]},Vf={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},$f={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},Uf={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},zf={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},qf={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Ks=[{label:"Content",sections:[kf,Ef]},{label:"Layout",sections:[Mf,Lf,If,Rf]},{label:"Widget",sections:[Pf,Wf,Bf,Hf,Df,Ff]},{label:"Features",sections:[Of,Nf,_f,Vf,$f]},{label:"Developer",collapsedByDefault:!0,sections:[Uf,zf,qf]}],vl=Ks.flatMap(e=>e.sections),xl={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},wl={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},Cl={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},Sl={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:Ds},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Fs},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Os},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ns},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:_s},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Vs},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:$s},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Us},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:zs}]},Al={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},Tl={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},$u=[xl,wl,Cl,Sl,Al,Tl],si=[{id:"style",label:"Style",sections:kr},{id:"design-system",label:"Design System",sections:bl},{id:"configure",label:"Configure",sections:vl}];function Uu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function jf(e,t,n){return{...e,id:`${n}-${e.id}`,path:Uu(e.path,t)}}function zu(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function qu(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>jf(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[Uu(d,t),l]))}))}}var kl=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},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"},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"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Qr=[...kl];function ai(e){return Qr.find(t=>t.id===e)}var ju=require("marked"),Kf=e=>{if(e)return e},El=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new ju.Marked({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=Kf(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},ii=e=>e?El({markedOptions:e.options,renderer:e.renderer}):El(),tv=El();var Gs=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Ku=Su(require("dompurify"),1),Gf={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"]},Yf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Xf=()=>{let e=(0,Ku.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Yf.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Gf)},li=e=>e===!1?null:typeof e=="function"?e:Xf();var Ml="webmcp:",ci={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Yu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Qf(t.join(""))}`}function Gu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Qf(e){let t=Gu(e,0).toString(36),n=Gu(e,2654435761).toString(36);return`${t}.${n}`}var di=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ci.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=eh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return wo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let g=typeof document!="undefined"&&!!document.modelContext;return wo(g?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Jf(t),a;try{a=await r.getTools()}catch(g){let x=g instanceof Error?g.message:String(g);return wo(`Failed to read WebMCP registry: ${x}`)}let i=a.find(g=>g.name===s);if(!i)return wo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return wo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return wo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return wo("User declined the tool call.");if(o!=null&&o.aborted)return wo("Aborted by cancel()");let l=new AbortController,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),f=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",f,{once:!0}));try{let g=await r.executeTool(i,rh(n),{signal:l.signal});return th(g)}catch(g){if(u)return wo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return wo("Aborted by cancel()");let x=g instanceof Error?g.message:String(g);return wo(x)}finally{clearTimeout(p),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ci.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ci.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:nh;try{return await n(t)}catch(r){return ci.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Zf(t,o))}},Jf=e=>e.startsWith(Ml)?e.slice(Ml.length):e,Ll=e=>e.startsWith(Ml),Zf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},eh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},th=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:sh(t)}]}},wo=e=>({isError:!0,content:[{type:"text",text:e}]}),nh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=oh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
4
  ${t}`:"")+(e.description?`
5
5
 
6
- ${e.description}`:"");return window.confirm(n)},eh=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)}},th=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Jr=require("partial-json"),Gu=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Zr=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)}},oh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Yu=e=>e.status==="complete"?oh(e):e.status==="pending"?"Waiting":"",rh=e=>{var r,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Xu=e=>e.status==="complete"?rh(e):"Using tool...",pi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Xs=e=>{var n,o,r;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return pi(t)},ui=e=>{var n,o,r;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return pi(t)},Il=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Xs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},mi=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ys(o,n.slice(s,a.index),[]),a[1]!==void 0?Ys(o,a[1],["bold"]):a[2]!==void 0?Ys(o,a[2],["italic"]):a[3]!==void 0&&Ys(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ys(o,n.slice(s),[]),o},Ys=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},sh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(n)},oh=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)}},rh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},sh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Jr=require("partial-json"),Xu=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Zr=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)}},ah=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Qu=e=>e.status==="complete"?ah(e):e.status==="pending"?"Waiting":"",ih=e=>{var r,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Ju=e=>e.status==="complete"?ih(e):"Using tool...",pi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Xs=e=>{var n,o,r;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return pi(t)},ui=e=>{var n,o,r;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return pi(t)},Il=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Xs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},mi=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ys(o,n.slice(s,a.index),[]),a[1]!==void 0?Ys(o,a[1],["bold"]):a[2]!==void 0?Ys(o,a[2],["italic"]):a[3]!==void 0&&Ys(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ys(o,n.slice(s),[]),o},Ys=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},lh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Er=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Qu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ju=()=>{var t;let e=sh();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Zu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Jr.parse)(n,Jr.STR|Jr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Gu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Gu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var em=()=>{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 fi=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,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((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),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 ah="https://api.runtype.com/v1/dispatch",gi="https://api.runtype.com";function ih(e){var s,a;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 r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Rl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function lh(e){switch(e){case"json":return Zu;case"regex-json":return Ju;case"xml":return em;default:return Qu}}var tm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ch(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=tm(n);if(!tm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Er(e);return Er(t)!==null&&a===null?t:e}var Qs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:ah,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:lh(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new di(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,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$/,""))||gi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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 r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||gi}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){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:n})}async submitNPSFeedback(t,n){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:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let m=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:m}),m}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Rl).map(m=>{var w,x,L;return{id:m.id,role:m.role,content:(L=(x=(w=m.contentParts)!=null?w:m.llmContent)!=null?x:m.rawContent)!=null?L:m.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let g=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:o.signal});if(!g.ok){let m=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:x}),x}if(g.status===429){let x=new Error(m.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let w=new Error(m.error||"Failed to send message");throw n({type:"error",error:w}),w}if(!g.body){let m=new Error("No response body received");throw n({type:"error",error:m}),m}n({type:"status",status:"connected"});try{await this.streamResponse(g.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||gi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||gi}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Rl).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(Rl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=p,r(p),p},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Ot,cn,Fn,Zn;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=N=>{let ae=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,De=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,Qe=N.tools?N.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...N,reasoning:ae,toolCall:De,tools:Qe}},p=N=>{n({type:"message",message:u(N)})},g=null,m=null,w={current:null},x={current:null},L=!1,W=new Map,B=new Map,D=new Map,V=new Map,H={lastId:null,byStep:new Map},v={lastId:null,byCall:new Map},C=(N,ae,De="")=>`${N}::${ae}::${De}`,M=(N,ae)=>`${N}::${ae}::`,A=(N,ae,De,Qe)=>{let Ne=C(N,ae,De),_e=D.get(Ne);if(_e)return _e;let rt=De?`-${De}`:"",At={id:`nested-${N}-${ae}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Qe,parentToolId:N,parentStepId:ae}};return D.set(Ne,At),p(At),At},E=N=>{if(N==null)return null;try{return String(N)}catch{return null}},F=N=>{var ae,De,Qe,Ne,_e;return E((_e=(Ne=(Qe=(De=(ae=N.stepId)!=null?ae:N.step_id)!=null?De:N.step)!=null?Qe:N.parentId)!=null?Ne:N.flowStepId)!=null?_e:N.flow_step_id)},U=N=>{var ae,De,Qe,Ne,_e,rt,At;return E((At=(rt=(_e=(Ne=(Qe=(De=(ae=N.callId)!=null?ae:N.call_id)!=null?De:N.requestId)!=null?Qe:N.request_id)!=null?Ne:N.toolCallId)!=null?_e:N.tool_call_id)!=null?rt:N.stepId)!=null?At:N.step_id)},j=o,fe=!1,se=()=>{if(g)return g;let N;return!fe&&j?(N=j,fe=!0):j&&x.current?N=`${j}_${x.current}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:N,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(g),g},ye=(N,ae)=>{H.lastId=ae,N&&H.byStep.set(N,ae)},le=(N,ae)=>{var _e;let De=(_e=N.reasoningId)!=null?_e:N.id,Qe=F(N);if(De){let rt=String(De);return ye(Qe,rt),rt}if(Qe){let rt=H.byStep.get(Qe);if(rt)return H.lastId=rt,rt}if(H.lastId&&!ae)return H.lastId;if(!ae)return null;let Ne=`reason-${l()}`;return ye(Qe,Ne),Ne},Ce=N=>{let ae=W.get(N);if(ae)return ae;let De={id:`reason-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:N,status:"streaming",chunks:[]}};return W.set(N,De),p(De),De},Be=(N,ae)=>{v.lastId=ae,N&&v.byCall.set(N,ae)},ve=new Set,ee=new Map,Me=new Set,Q=new Map,Te=N=>{if(!N)return!1;let ae=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return ae==="emit_artifact_markdown"||ae==="emit_artifact_component"},he=(N,ae)=>{var _e;let De=(_e=N.toolId)!=null?_e:N.id,Qe=U(N);if(De){let rt=String(De);return Be(Qe,rt),rt}if(Qe){let rt=v.byCall.get(Qe);if(rt)return v.lastId=rt,rt}if(v.lastId&&!ae)return v.lastId;if(!ae)return null;let Ne=`tool-${l()}`;return Be(Qe,Ne),Ne},ce=N=>{let ae=B.get(N);if(ae)return ae;let De={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:N,status:"pending"}};return B.set(N,De),p(De),De},me=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let ae=Number(N);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let De=Date.parse(N);if(!Number.isNaN(De))return De}return Date.now()},Ke=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},K=new Map,re=new Map,Pe=new Map,nt=new Map,ge=null,de=(N,ae,De)=>{var At;let Qe=Pe.get(N);Qe||(Qe=[],Pe.set(N,Qe));let Ne=0,_e=Qe.length;for(;Ne<_e;){let _t=Ne+_e>>>1;Qe[_t].seq<ae?Ne=_t+1:_e=_t}((At=Qe[Ne])==null?void 0:At.seq)===ae?Qe[Ne]={seq:ae,text:De}:Qe.splice(Ne,0,{seq:ae,text:De});let rt="";for(let _t=0;_t<Qe.length;_t++)rt+=Qe[_t].text;return rt},Ve=(N,ae)=>{let De=Ke(ae),Qe=re.get(N.id),Ne=ch(Qe,De);N.rawContent=Ne;let _e=K.get(N.id),rt=gt=>{var Ut;let ot=(Ut=N.content)!=null?Ut:"";gt.trim()!==""&&(ot.trim().length===0||gt.startsWith(ot)||gt.trimStart().startsWith(ot.trim()))&&(N.content=gt)},At=()=>{var gt;if(_e){let ot=(gt=_e.close)==null?void 0:gt.call(_e);ot instanceof Promise&&ot.catch(()=>{})}K.delete(N.id),re.delete(N.id),N.streaming=!1,p(N)};if(!_e){rt(De),At();return}let _t=Er(Ne);if(_t!==null&&_t.trim()!==""){rt(_t),At();return}let Kt=gt=>{var ie;let ot=typeof gt=="string"?gt:(ie=gt==null?void 0:gt.text)!=null?ie:null;if(ot!==null&&ot.trim()!=="")return ot;let Ut=_e.getExtractedText();return Ut!==null&&Ut.trim()!==""?Ut:De},G;try{G=_e.processChunk(Ne)}catch{rt(De),At();return}if(G instanceof Promise){G.then(gt=>{rt(Kt(gt)),At()}).catch(()=>{rt(De),At()});return}rt(Kt(G)),At()},Ie=[],pe=!1,X,$e=()=>{pe||(pe=!0,queueMicrotask(()=>{pe=!1,X()}))},St=new fi((N,ae)=>{Ie.push({payloadType:N,payload:ae}),$e()}),J=null,Oe=new Map,In=(Ot=this.config.iterationDisplay)!=null?Ot:"separate";for(X=()=>{var N,ae,De,Qe,Ne,_e,rt,At,_t,Kt,G,gt,ot,Ut,ie,xe,Ct,Vt,Zt,xn,Mt,Tt,bt,vt,zt,et,On,eo,wn,Nn,mt,So,_n,pr,Rn,Fr,Uo,Ro,xt,Vn,$n,Cn,Pt,to,no,Un,zo,Po,qo,zn,Bt,Sn,oo,jo,Wo,Ko,Ao,qn,uo,ht,Gt,Yt,jn,Go,ro,mo,Kn,k,Gn,fo,Bo,To,ms,go,ho,bo,Ho,ur,Ma,fs,La,Or,ft,gs,so,Pn,Ia,Ra,Nr,Do,Pa,mr,hs,Fo,bs,Yo,Xo,Wa,Ba,ll,fr,Qo,Ha,ys,Jo,Da,vs,Zo,xs,Fa,Oo,Oa,er,Ht,_r,Vr,ws,ko,Na,Cs,Ss,_a,$r,Ur,gr,Va,$a,As,Ts,ks,Es,An,Yn,No,st,Ms,hr,yo;for(let zr=0;zr<Ie.length;zr++){let ze=Ie[zr].payloadType,T=Ie[zr].payload;if(ze==="reason_start"){let z=(N=le(T,!0))!=null?N:`reason-${l()}`,R=Ce(z);R.reasoning=(ae=R.reasoning)!=null?ae:{id:z,status:"streaming",chunks:[]},R.reasoning.startedAt=(Qe=R.reasoning.startedAt)!=null?Qe:me((De=T.startedAt)!=null?De:T.timestamp),R.reasoning.completedAt=void 0,R.reasoning.durationMs=void 0,R.streaming=!0,R.reasoning.status="streaming",p(R)}else if(ze==="reason_delta"||ze==="reason_chunk"){let z=(_e=(Ne=le(T,!1))!=null?Ne:le(T,!0))!=null?_e:`reason-${l()}`,R=Ce(z);R.reasoning=(rt=R.reasoning)!=null?rt:{id:z,status:"streaming",chunks:[]},R.reasoning.startedAt=(_t=R.reasoning.startedAt)!=null?_t:me((At=T.startedAt)!=null?At:T.timestamp);let te=(gt=(G=(Kt=T.reasoningText)!=null?Kt:T.text)!=null?G:T.delta)!=null?gt:"";if(te&&T.hidden!==!0){let ne=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ne!==void 0){let Y=de(z,ne,String(te));R.reasoning.chunks=[Y]}else R.reasoning.chunks.push(String(te))}if(R.reasoning.status=T.done?"complete":"streaming",T.done){R.reasoning.completedAt=me((ot=T.completedAt)!=null?ot:T.timestamp);let ne=(Ut=R.reasoning.startedAt)!=null?Ut:Date.now();R.reasoning.durationMs=Math.max(0,((ie=R.reasoning.completedAt)!=null?ie:Date.now())-ne)}R.streaming=R.reasoning.status!=="complete",p(R)}else if(ze==="reason_complete"){let z=(Ct=(xe=le(T,!1))!=null?xe:le(T,!0))!=null?Ct:`reason-${l()}`,R=W.get(z);if(R!=null&&R.reasoning){R.reasoning.status="complete",R.reasoning.completedAt=me((Vt=T.completedAt)!=null?Vt:T.timestamp);let ne=(Zt=R.reasoning.startedAt)!=null?Zt:Date.now();R.reasoning.durationMs=Math.max(0,((xn=R.reasoning.completedAt)!=null?xn:Date.now())-ne),R.streaming=!1,p(R)}let te=F(T);te&&H.byStep.delete(te)}else if(ze==="tool_start"){let z=(Mt=he(T,!0))!=null?Mt:`tool-${l()}`,R=(Tt=T.toolName)!=null?Tt:T.name;if(Te(R)){ve.add(z);continue}let te=ce(z),ne=(bt=te.toolCall)!=null?bt:{id:z,status:"pending"};ne.name=R!=null?R:ne.name,ne.status="running",T.args!==void 0?ne.args=T.args:T.parameters!==void 0&&(ne.args=T.parameters),ne.startedAt=(zt=ne.startedAt)!=null?zt:me((vt=T.startedAt)!=null?vt:T.timestamp),ne.completedAt=void 0,ne.durationMs=void 0,te.toolCall=ne,te.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(te.agentMetadata={executionId:(et=Y==null?void 0:Y.executionId)!=null?et:T.executionId,iteration:(On=Y==null?void 0:Y.iteration)!=null?On:T.iteration}),p(te)}else if(ze==="tool_chunk"||ze==="tool_delta"){let z=(wn=(eo=he(T,!1))!=null?eo:he(T,!0))!=null?wn:`tool-${l()}`;if(ve.has(z))continue;let R=ce(z),te=(Nn=R.toolCall)!=null?Nn:{id:z,status:"running"};te.startedAt=(So=te.startedAt)!=null?So:me((mt=T.startedAt)!=null?mt:T.timestamp);let ne=(Rn=(pr=(_n=T.text)!=null?_n:T.delta)!=null?pr:T.message)!=null?Rn:"";ne&&(te.chunks=(Fr=te.chunks)!=null?Fr:[],te.chunks.push(String(ne))),te.status="running",R.toolCall=te,R.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(R.agentMetadata=(xt=R.agentMetadata)!=null?xt:{executionId:(Uo=Y==null?void 0:Y.executionId)!=null?Uo:T.executionId,iteration:(Ro=Y==null?void 0:Y.iteration)!=null?Ro:T.iteration}),p(R)}else if(ze==="tool_complete"){let z=($n=(Vn=he(T,!1))!=null?Vn:he(T,!0))!=null?$n:`tool-${l()}`;if(ve.has(z)){ve.delete(z);continue}let R=ce(z),te=(Cn=R.toolCall)!=null?Cn:{id:z,status:"running"};te.status="complete",T.result!==void 0&&(te.result=T.result),typeof T.duration=="number"&&(te.duration=T.duration),te.completedAt=me((Pt=T.completedAt)!=null?Pt:T.timestamp);let ne=(to=T.duration)!=null?to:T.executionTime;if(typeof ne=="number")te.durationMs=ne;else{let Fe=(no=te.startedAt)!=null?no:Date.now();te.durationMs=Math.max(0,((Un=te.completedAt)!=null?Un:Date.now())-Fe)}R.toolCall=te,R.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(R.agentMetadata=(qo=R.agentMetadata)!=null?qo:{executionId:(zo=Y==null?void 0:Y.executionId)!=null?zo:T.executionId,iteration:(Po=Y==null?void 0:Y.iteration)!=null?Po:T.iteration}),p(R);let qe=U(T);qe&&v.byCall.delete(qe)}else if(ze==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let z=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,R=(zn=z!=null?z:T.toolId)!=null?zn:`local-${l()}`,te=ce(R),ne=(Bt=te.toolCall)!=null?Bt:{id:R,status:"pending"};ne.name=T.toolName,ne.args=T.parameters,ne.status="complete",ne.chunks=(Sn=ne.chunks)!=null?Sn:[],ne.startedAt=(jo=ne.startedAt)!=null?jo:me((oo=T.startedAt)!=null?oo:T.timestamp),ne.completedAt=(Wo=ne.completedAt)!=null?Wo:ne.startedAt,te.toolCall=ne,te.streaming=!1,te.agentMetadata={...te.agentMetadata,executionId:(Ao=T.executionId)!=null?Ao:(Ko=te.agentMetadata)==null?void 0:Ko.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},p(te)}else if(ze==="text_start"){if((qn=T.toolContext)!=null&&qn.toolId)continue;let z=T.partId;if(z!==void 0&&x.current!==null&&z!==x.current){let R=g;R&&(R.streaming=!1,p(R),ge=R,g=null,L=!0)}z!==void 0&&(x.current=z)}else if(ze==="text_end"){if((uo=T.toolContext)!=null&&uo.toolId)continue;let z=g;z&&(z.streaming=!1,p(z),ge=z,g=null,L=!0)}else if(ze==="step_chunk"||ze==="step_delta"){let z=T.stepType,R=T.executionType;if(z==="tool"||R==="context")continue;let te=T.toolContext;if(te!=null&&te.toolId){let Fe=String((Gt=(ht=T.id)!=null?ht:te.stepId)!=null?Gt:`step-${l()}`),it=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Ge=`${te.toolId}::${Fe}`,Ye=V.get(Ge);if(it!==""&&Ye!==void 0&&Ye!==""&&Ye!==it){let kt=D.get(C(te.toolId,Fe,Ye));kt&&kt.streaming!==!1&&(kt.streaming=!1,p(kt))}it!==""&&V.set(Ge,it);let Je=A(te.toolId,Fe,it,te.executionId),Xt=(ro=(Go=(jn=(Yt=T.text)!=null?Yt:T.delta)!=null?jn:T.content)!=null?Go:T.chunk)!=null?ro:"";Xt&&(Je.content+=String(Xt),Je.streaming=!0,p(Je)),T.isComplete&&(Je.streaming=!1,p(Je));continue}let ne=T.partId;if(ne!==void 0&&x.current!==null&&ne!==x.current){let Fe=g;Fe&&(Fe.streaming=!1,p(Fe),ge=Fe,g=null,L=!0)}ne!==void 0&&(x.current=ne);let Y=ne!==void 0&&(mo=nt.get(ne))!=null?mo:se();ne!==void 0&&(Y.partId||(Y.partId=ne),nt.set(ne,Y));let qe=(fo=(Gn=(k=(Kn=T.text)!=null?Kn:T.delta)!=null?k:T.content)!=null?Gn:T.chunk)!=null?fo:"";if(qe){let Fe=typeof T.seq=="number"?T.seq:void 0,it=ne!=null?ne:Y.id,Ge=Fe!==void 0?de(it,Fe,String(qe)):((Bo=re.get(Y.id))!=null?Bo:"")+qe;Y.rawContent=Ge,K.has(Y.id)||K.set(Y.id,this.createStreamParser());let Ye=K.get(Y.id),Je=Ge.trim().startsWith("{")||Ge.trim().startsWith("[");if(Je&&re.set(Y.id,Ge),Ye.__isPlainTextParser===!0){Y.content=Fe!==void 0?Ge:Y.content+qe,re.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y);continue}let kt=Ye.processChunk(Ge);if(kt instanceof Promise)kt.then(It=>{var fn;let rn=typeof It=="string"?It:(fn=It==null?void 0:It.text)!=null?fn:null;if(rn!==null&&rn.trim()!=="")Y.content=rn,p(Y);else if(!Je&&!Ge.trim().startsWith("<")){let dn=g,en=dn&&dn.id===Y.id?dn:Y;en.id===Y.id&&(en.content=Fe!==void 0?Ge:en.content+qe,re.delete(en.id),K.delete(en.id),en.rawContent=void 0,p(en))}}).catch(()=>{Y.content=Fe!==void 0?Ge:Y.content+qe,re.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y)});else{let It=typeof kt=="string"?kt:(To=kt==null?void 0:kt.text)!=null?To:null;It!==null&&It.trim()!==""?(Y.content=It,p(Y)):!Je&&!Ge.trim().startsWith("<")&&(Y.content=Fe!==void 0?Ge:Y.content+qe,re.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y))}}if(T.isComplete){let Fe=(go=(ms=T.result)==null?void 0:ms.response)!=null?go:Y.content;if(Fe){let it=re.get(Y.id),Ge=it!=null?it:Ke(Fe);Y.rawContent=Ge;let Ye=K.get(Y.id),Je=null,Xt=!1;if(Ye&&(Je=Ye.getExtractedText(),Je===null&&(Je=Er(Ge)),Je===null)){let kt=Ye.processChunk(Ge);kt instanceof Promise?(Xt=!0,kt.then(It=>{var fn;let rn=typeof It=="string"?It:(fn=It==null?void 0:It.text)!=null?fn:null;if(rn!==null){let dn=g;dn&&dn.id===Y.id&&(dn.content=rn,dn.streaming=!1,K.delete(dn.id),re.delete(dn.id),p(dn))}})):Je=typeof kt=="string"?kt:(ho=kt==null?void 0:kt.text)!=null?ho:null}if(!Xt){Je!==null&&Je.trim()!==""?Y.content=Je:re.has(Y.id)||(Y.content=Ke(Fe));let kt=K.get(Y.id);if(kt){let It=(bo=kt.close)==null?void 0:bo.call(kt);It instanceof Promise&&It.catch(()=>{}),K.delete(Y.id)}re.delete(Y.id),Y.streaming=!1,p(Y)}}}}else if(ze==="step_complete"){let z=T.stepType,R=T.executionType;if(z==="tool"||R==="context")continue;let te=T.toolContext;if(te!=null&&te.toolId){let Fe=String((ur=(Ho=T.id)!=null?Ho:te.stepId)!=null?ur:"");if(Fe){let it=M(te.toolId,Fe);for(let[Ge,Ye]of D)Ge.startsWith(it)&&Ye.streaming!==!1&&(Ye.streaming=!1,p(Ye));V.delete(`${te.toolId}::${Fe}`)}continue}let ne=T.stopReason;if(L){if(g!==null){let Ge=g;ne&&(Ge.stopReason=ne),K.delete(Ge.id),re.delete(Ge.id),Ge.streaming!==!1&&(Ge.streaming=!1,p(Ge))}let Fe=(Ma=T.result)==null?void 0:Ma.response,it=ge;it&&(ne&&(it.stopReason=ne),Fe!=null?Ve(it,Fe):(K.delete(it.id),re.delete(it.id))),ge=null;continue}let Y=(fs=T.result)==null?void 0:fs.response,qe=se();if(ne&&(qe.stopReason=ne),Y!=null){let Fe=K.get(qe.id),it=!1,Ge=!1;if(Fe){let Ye=Fe.getExtractedText(),Je=re.get(qe.id),Xt=Je!=null?Je:Ke(Y);if(qe.rawContent=Xt,Ye!==null&&Ye.trim()!=="")qe.content=Ye,it=!0;else{let kt=Er(Xt);if(kt!==null)qe.content=kt,it=!0;else{let It=Fe.processChunk(Xt);if(It instanceof Promise)Ge=!0,It.then(rn=>{var dn;let fn=typeof rn=="string"?rn:(dn=rn==null?void 0:rn.text)!=null?dn:null;if(fn!==null&&fn.trim()!==""){let en=g;en&&en.id===qe.id&&(en.content=fn,en.streaming=!1,K.delete(en.id),re.delete(en.id),p(en))}else{let en=Fe.getExtractedText(),ao=g;ao&&ao.id===qe.id&&(en!==null&&en.trim()!==""?ao.content=en:re.has(ao.id)||(ao.content=Ke(Y)),ao.streaming=!1,K.delete(ao.id),re.delete(ao.id),p(ao))}});else{let rn=typeof It=="string"?It:(La=It==null?void 0:It.text)!=null?La:null;if(rn!==null&&rn.trim()!=="")qe.content=rn,it=!0;else{let fn=Fe.getExtractedText();fn!==null&&fn.trim()!==""&&(qe.content=fn,it=!0)}}}}}if(!Ge){if(!qe.rawContent){let Ye=re.get(qe.id);qe.rawContent=Ye!=null?Ye:Ke(Y)}if(!it&&!re.has(qe.id)&&(qe.content=Ke(Y)),Fe){let Ye=(Or=Fe.close)==null?void 0:Or.call(Fe);Ye instanceof Promise&&Ye.catch(()=>{})}K.delete(qe.id),re.delete(qe.id),qe.streaming=!1,p(qe)}}else K.delete(qe.id),re.delete(qe.id),qe.streaming=!1,p(qe)}else if(ze==="flow_complete"){let z=(ft=T.result)==null?void 0:ft.response;if(L){if(g!==null){let R=g;K.delete(R.id),re.delete(R.id),R.streaming!==!1&&(R.streaming=!1,p(R))}}else if(z!=null){let R=se(),te=re.get(R.id),ne=te!=null?te:Ke(z);R.rawContent=ne;let Y=Ke(z),qe=K.get(R.id);if(qe){let Ge=Er(ne);if(Ge!==null)Y=Ge;else{let Ye=qe.processChunk(ne);Ye instanceof Promise&&Ye.then(Xt=>{var It;let kt=typeof Xt=="string"?Xt:(It=Xt==null?void 0:Xt.text)!=null?It:null;kt!==null&&(R.content=kt,R.streaming=!1,p(R))});let Je=qe.getExtractedText();Je!==null&&(Y=Je)}}K.delete(R.id),re.delete(R.id);let Fe=Y!==R.content,it=R.streaming!==!1;Fe&&(R.content=Y),R.streaming=!1,(Fe||it)&&p(R)}else if(g!==null){let R=g;K.delete(R.id),re.delete(R.id),R.streaming!==!1&&(R.streaming=!1,p(R))}n({type:"status",status:"idle"})}else if(ze==="agent_start")J={executionId:T.executionId,agentId:(gs=T.agentId)!=null?gs:"virtual",agentName:(so=T.agentName)!=null?so:"",status:"running",currentIteration:0,maxTurns:(Pn=T.maxTurns)!=null?Pn:1,startedAt:me(T.startedAt)};else if(ze==="agent_iteration_start"){if(J&&(J.currentIteration=T.iteration),In==="separate"&&T.iteration>1){let z=g;z&&(z.streaming=!1,p(z),Oe.set(T.iteration-1,z),g=null)}}else if(ze==="agent_turn_start")m=null;else if(ze==="agent_turn_delta"){if(T.contentType==="text"){let z=se();z.content+=(Ia=T.delta)!=null?Ia:"",z.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:J==null?void 0:J.agentName},m=z,p(z)}else if(T.contentType==="thinking"){let z=(Ra=T.turnId)!=null?Ra:`agent-think-${T.iteration}`,R=Ce(z);R.reasoning=(Nr=R.reasoning)!=null?Nr:{id:z,status:"streaming",chunks:[]},R.reasoning.chunks.push((Do=T.delta)!=null?Do:""),R.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},p(R)}else if(T.contentType==="tool_input"){let z=(Pa=T.toolCallId)!=null?Pa:v.lastId;if(z){let R=B.get(z);R!=null&&R.toolCall&&(R.toolCall.chunks=(mr=R.toolCall.chunks)!=null?mr:[],R.toolCall.chunks.push((hs=T.delta)!=null?hs:""),p(R))}}}else if(ze==="agent_turn_complete"){let z=T.turnId;if(z){let ne=W.get(z);if(ne!=null&&ne.reasoning){ne.reasoning.status="complete",ne.reasoning.completedAt=me(T.completedAt);let Y=(Fo=ne.reasoning.startedAt)!=null?Fo:Date.now();ne.reasoning.durationMs=Math.max(0,((bs=ne.reasoning.completedAt)!=null?bs:Date.now())-Y),ne.streaming=!1,p(ne)}}let R=T.stopReason,te=g!=null?g:m;if(R&&te!==null){let ne=T.turnId;(!ne||((Yo=te.agentMetadata)==null?void 0:Yo.turnId)===ne)&&(te.stopReason=R,p(te))}}else if(ze==="agent_tool_start"){g&&(g.streaming=!1,p(g),g=null);let z=(Xo=T.toolCallId)!=null?Xo:`agent-tool-${l()}`;Be(U(T),z);let R=ce(z),te=(Wa=R.toolCall)!=null?Wa:{id:z,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};te.name=(ll=(Ba=T.toolName)!=null?Ba:T.name)!=null?ll:te.name,te.status="running",T.parameters!==void 0&&(te.args=T.parameters),te.startedAt=me((fr=T.startedAt)!=null?fr:T.timestamp),R.toolCall=te,R.streaming=!0,R.agentMetadata={executionId:T.executionId,iteration:T.iteration},p(R)}else if(ze==="agent_tool_delta"){let z=(Qo=T.toolCallId)!=null?Qo:v.lastId;if(z){let R=(Ha=B.get(z))!=null?Ha:ce(z);R.toolCall&&(R.toolCall.chunks=(ys=R.toolCall.chunks)!=null?ys:[],R.toolCall.chunks.push((Jo=T.delta)!=null?Jo:""),R.toolCall.status="running",R.streaming=!0,p(R))}}else if(ze==="agent_tool_complete"){let z=(Da=T.toolCallId)!=null?Da:v.lastId;if(z){let R=(vs=B.get(z))!=null?vs:ce(z);if(R.toolCall){R.toolCall.status="complete",T.result!==void 0&&(R.toolCall.result=T.result),typeof T.executionTime=="number"&&(R.toolCall.durationMs=T.executionTime),R.toolCall.completedAt=me((Zo=T.completedAt)!=null?Zo:T.timestamp),R.streaming=!1,p(R);let te=U(T);te&&v.byCall.delete(te)}}}else if(ze==="agent_media"){let z=Array.isArray(T.media)?T.media:[],R=[];for(let te of z){if(!te||typeof te!="object")continue;let ne=te,Y=typeof ne.type=="string"?ne.type:void 0,qe=typeof ne.mediaType=="string"?ne.mediaType.toLowerCase():"",Fe=null,it="";if(Y==="media"){let Ge=typeof ne.data=="string"?ne.data:void 0;if(!Ge)continue;it=qe.length>0?qe:"application/octet-stream",Fe=`data:${it};base64,${Ge}`}else if(Y==="image-url"){let Ge=typeof ne.url=="string"?ne.url:void 0;if(!Ge)continue;it=qe,Fe=Ge}else if(Y==="file-url"){let Ge=typeof ne.url=="string"?ne.url:void 0;if(!Ge)continue;it=qe,Fe=Ge}else continue;if(Fe)if(Y==="image-url"||it.startsWith("image/"))R.push({type:"image",image:Fe,...it?{mimeType:it}:{}});else if(it.startsWith("audio/"))R.push({type:"audio",audio:Fe,mimeType:it});else if(it.startsWith("video/"))R.push({type:"video",video:Fe,mimeType:it});else{let Ge=it||"application/octet-stream";R.push({type:"file",data:Fe,mimeType:Ge,filename:ih(Ge)})}}if(R.length>0){let te=l(),ne=T.toolCallId,qe={id:`agent-media-${typeof ne=="string"&&ne.length>0?`${ne}-${te}`:String(te)}`,role:"assistant",content:"",contentParts:R,createdAt:new Date().toISOString(),streaming:!1,sequence:te,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};p(qe);let Fe=g;Fe&&(Fe.streaming=!1,p(Fe)),g=null,w.current=null}}else if(ze!=="agent_iteration_complete"){if(ze==="agent_reflection"||ze==="agent_reflect"){let z=`agent-reflection-${T.executionId}-${T.iteration}`,R={id:z,role:"assistant",content:(xs=T.reflection)!=null?xs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Fa=T.reflection)!=null?Fa:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};p(R)}else if(ze==="agent_complete"){J&&(J.status=T.success?"complete":"error",J.completedAt=me(T.completedAt),J.stopReason=T.stopReason);let z=g;z&&(z.streaming=!1,p(z)),n({type:"status",status:"idle"})}else if(ze==="agent_error"){let z=typeof T.error=="string"?T.error:(Oa=(Oo=T.error)==null?void 0:Oo.message)!=null?Oa:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(ze!=="agent_ping"){if(ze==="agent_approval_start"){let z=(er=T.approvalId)!=null?er:`approval-${l()}`,R={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ht=J==null?void 0:J.agentId)!=null?Ht:"virtual",executionId:(Vr=(_r=T.executionId)!=null?_r:J==null?void 0:J.executionId)!=null?Vr:"",toolName:(ws=T.toolName)!=null?ws:"",toolType:T.toolType,description:(Na=T.description)!=null?Na:`Execute ${(ko=T.toolName)!=null?ko:"tool"}`,parameters:T.parameters}};p(R)}else if(ze==="step_await"&&T.awaitReason==="approval_required"){let z=(Cs=T.approvalId)!=null?Cs:`approval-${l()}`,R={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ss=J==null?void 0:J.agentId)!=null?Ss:"virtual",executionId:($r=(_a=T.executionId)!=null?_a:J==null?void 0:J.executionId)!=null?$r:"",toolName:(Ur=T.toolName)!=null?Ur:"",toolType:T.toolType,description:(Va=T.description)!=null?Va:`Execute ${(gr=T.toolName)!=null?gr:"tool"}`,parameters:T.parameters}};p(R)}else if(ze==="agent_approval_complete"){let z=T.approvalId;if(z){let te={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:($a=T.decision)!=null?$a:"approved",agentId:(As=J==null?void 0:J.agentId)!=null?As:"virtual",executionId:(ks=(Ts=T.executionId)!=null?Ts:J==null?void 0:J.executionId)!=null?ks:"",toolName:(Es=T.toolName)!=null?Es:"",description:(An=T.description)!=null?An:"",resolvedAt:Date.now()}};p(te)}}else if(ze==="artifact_start"||ze==="artifact_delta"||ze==="artifact_update"||ze==="artifact_complete"){if(ze==="artifact_start"){let z=T.artifactType,R=String(T.id),te=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:R,artifactType:z,title:te,component:typeof T.component=="string"?T.component:void 0}),Q.set(R,{markdown:"",title:te}),!Me.has(R)){Me.add(R);let ne={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:R,title:te,artifactType:z,status:"streaming"}})};ee.set(R,ne),p(ne)}}else if(ze==="artifact_delta"){let z=String(T.id),R=typeof T.delta=="string"?T.delta:String((Yn=T.delta)!=null?Yn:"");n({type:"artifact_delta",id:z,artDelta:R});let te=Q.get(z);te&&(te.markdown+=R)}else if(ze==="artifact_update"){let z=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:z,component:typeof T.component=="string"?T.component:void 0})}else if(ze==="artifact_complete"){let z=String(T.id);n({type:"artifact_complete",id:z});let R=ee.get(z);if(R){R.streaming=!1;try{let te=JSON.parse((No=R.rawContent)!=null?No:"{}");if(te.props){te.props.status="complete";let ne=Q.get(z);ne!=null&&ne.markdown&&(te.props.markdown=ne.markdown)}R.rawContent=JSON.stringify(te)}catch{}Q.delete(z),p(R),ee.delete(z)}}}else if(ze==="transcript_insert"){let z=T.message;if(!z||typeof z!="object")continue;let R=String((st=z.id)!=null?st:`msg-${l()}`),te=z.role,Y={id:R,role:te==="user"?"user":te==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(p(Y),Y.rawContent)try{let qe=JSON.parse(Y.rawContent),Fe=(Ms=qe==null?void 0:qe.props)==null?void 0:Ms.artifactId;typeof Fe=="string"&&Me.add(Fe)}catch{}g=null,w.current=null,K.delete(R),re.delete(R)}else if(ze==="error"||ze==="step_error"||ze==="dispatch_error"||ze==="flow_error"){let z=null;if(T.error instanceof Error)z=T.error;else if(ze==="dispatch_error"){let R=(hr=T.message)!=null?hr:T.error;R!=null&&R!==""&&(z=new Error(String(R)))}else if(ze==="step_error"||ze==="flow_error"){let R=T.error;typeof R=="string"&&R!==""?z=new Error(R):R!=null&&typeof R=="object"&&"message"in R&&(z=new Error(String((yo=R.message)!=null?yo:R)))}else ze==="error"&&T.error!=null&&T.error!==""&&(z=new Error(String(T.error)));if(z){n({type:"error",error:z});let R=g;R&&R.streaming&&(R.streaming=!1,p(R)),n({type:"status",status:"idle"})}}}}}Ie.length=0};;){let{done:N,value:ae}=await r.read();if(N)break;a+=s.decode(ae,{stream:!0});let De=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Er=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Zu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},em=()=>{var t;let e=lh();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},tm=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Jr.parse)(n,Jr.STR|Jr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Xu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Xu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var nm=()=>{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 gi=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,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((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),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 ch="https://api.runtype.com/v1/dispatch",fi="https://api.runtype.com";function dh(e){var s,a;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 r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Rl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ph(e){switch(e){case"json":return tm;case"regex-json":return em;case"xml":return nm;default:return Zu}}var om=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function uh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=om(n);if(!om(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Er(e);return Er(t)!==null&&a===null?t:e}var Qs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:ch,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:ph(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new di(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,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$/,""))||fi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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 r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fi}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){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:n})}async submitNPSFeedback(t,n){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:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let F=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:F}),F}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([F])=>F!=="sessionId"&&F!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Rl).map(F=>{var H,v,w;return{id:F.id,role:F.role,content:(w=(v=(H=F.contentParts)!=null?H:F.llmContent)!=null?v:F.rawContent)!=null?w:F.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,g=!!(f&&f.length>0),x=g?Yu(f):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,L=g&&C&&this.lastSentClientToolsFingerprint===x,B=!1,I=null,D;for(let F=0;;F++){let v={...p,...g&&(B||!L)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),D=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),D.status===409&&F===0&&g){let w=await D.json().catch(()=>null);if((w==null?void 0:w.error)==="client_tools_resend_required"){B=!0,this.lastSentClientToolsFingerprint=null;continue}I=w!=null?w:{error:"Chat request failed"}}break}if(!D.ok){let F=I!=null?I:await D.json().catch(()=>({error:"Chat request failed"}));if(D.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(D.status===429){let v=new Error(F.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let H=new Error(F.error||"Failed to send message");throw n({type:"error",error:H}),H}if(!D.body){let F=new Error("No response body received");throw n({type:"error",error:F}),F}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(D.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||fi}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Rl).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(Rl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=p,r(p),p},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Ot,cn,Fn,Zn;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=_=>{let ae=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,De=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,Qe=_.tools?_.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{..._,reasoning:ae,toolCall:De,tools:Qe}},p=_=>{n({type:"message",message:u(_)})},f=null,g=null,x={current:null},C={current:null},L=!1,B=new Map,I=new Map,D=new Map,F=new Map,H={lastId:null,byStep:new Map},v={lastId:null,byCall:new Map},w=(_,ae,De="")=>`${_}::${ae}::${De}`,M=(_,ae)=>`${_}::${ae}::`,A=(_,ae,De,Qe)=>{let Ne=w(_,ae,De),_e=D.get(Ne);if(_e)return _e;let rt=De?`-${De}`:"",At={id:`nested-${_}-${ae}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Qe,parentToolId:_,parentStepId:ae}};return D.set(Ne,At),p(At),At},E=_=>{if(_==null)return null;try{return String(_)}catch{return null}},O=_=>{var ae,De,Qe,Ne,_e;return E((_e=(Ne=(Qe=(De=(ae=_.stepId)!=null?ae:_.step_id)!=null?De:_.step)!=null?Qe:_.parentId)!=null?Ne:_.flowStepId)!=null?_e:_.flow_step_id)},U=_=>{var ae,De,Qe,Ne,_e,rt,At;return E((At=(rt=(_e=(Ne=(Qe=(De=(ae=_.callId)!=null?ae:_.call_id)!=null?De:_.requestId)!=null?Qe:_.request_id)!=null?Ne:_.toolCallId)!=null?_e:_.tool_call_id)!=null?rt:_.stepId)!=null?At:_.step_id)},j=o,ge=!1,se=()=>{if(f)return f;let _;return!ge&&j?(_=j,ge=!0):j&&C.current?_=`${j}_${C.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},ye=(_,ae)=>{H.lastId=ae,_&&H.byStep.set(_,ae)},le=(_,ae)=>{var _e;let De=(_e=_.reasoningId)!=null?_e:_.id,Qe=O(_);if(De){let rt=String(De);return ye(Qe,rt),rt}if(Qe){let rt=H.byStep.get(Qe);if(rt)return H.lastId=rt,rt}if(H.lastId&&!ae)return H.lastId;if(!ae)return null;let Ne=`reason-${l()}`;return ye(Qe,Ne),Ne},Ce=_=>{let ae=B.get(_);if(ae)return ae;let De={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return B.set(_,De),p(De),De},Be=(_,ae)=>{v.lastId=ae,_&&v.byCall.set(_,ae)},ve=new Set,ee=new Map,Me=new Set,Q=new Map,Te=_=>{if(!_)return!1;let ae=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ae==="emit_artifact_markdown"||ae==="emit_artifact_component"},he=(_,ae)=>{var _e;let De=(_e=_.toolId)!=null?_e:_.id,Qe=U(_);if(De){let rt=String(De);return Be(Qe,rt),rt}if(Qe){let rt=v.byCall.get(Qe);if(rt)return v.lastId=rt,rt}if(v.lastId&&!ae)return v.lastId;if(!ae)return null;let Ne=`tool-${l()}`;return Be(Qe,Ne),Ne},ce=_=>{let ae=I.get(_);if(ae)return ae;let De={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return I.set(_,De),p(De),De},me=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ae=Number(_);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let De=Date.parse(_);if(!Number.isNaN(De))return De}return Date.now()},Ke=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},K=new Map,re=new Map,Pe=new Map,nt=new Map,fe=null,de=(_,ae,De)=>{var At;let Qe=Pe.get(_);Qe||(Qe=[],Pe.set(_,Qe));let Ne=0,_e=Qe.length;for(;Ne<_e;){let _t=Ne+_e>>>1;Qe[_t].seq<ae?Ne=_t+1:_e=_t}((At=Qe[Ne])==null?void 0:At.seq)===ae?Qe[Ne]={seq:ae,text:De}:Qe.splice(Ne,0,{seq:ae,text:De});let rt="";for(let _t=0;_t<Qe.length;_t++)rt+=Qe[_t].text;return rt},Ve=(_,ae)=>{let De=Ke(ae),Qe=re.get(_.id),Ne=uh(Qe,De);_.rawContent=Ne;let _e=K.get(_.id),rt=ft=>{var Ut;let ot=(Ut=_.content)!=null?Ut:"";ft.trim()!==""&&(ot.trim().length===0||ft.startsWith(ot)||ft.trimStart().startsWith(ot.trim()))&&(_.content=ft)},At=()=>{var ft;if(_e){let ot=(ft=_e.close)==null?void 0:ft.call(_e);ot instanceof Promise&&ot.catch(()=>{})}K.delete(_.id),re.delete(_.id),_.streaming=!1,p(_)};if(!_e){rt(De),At();return}let _t=Er(Ne);if(_t!==null&&_t.trim()!==""){rt(_t),At();return}let Kt=ft=>{var ie;let ot=typeof ft=="string"?ft:(ie=ft==null?void 0:ft.text)!=null?ie:null;if(ot!==null&&ot.trim()!=="")return ot;let Ut=_e.getExtractedText();return Ut!==null&&Ut.trim()!==""?Ut:De},G;try{G=_e.processChunk(Ne)}catch{rt(De),At();return}if(G instanceof Promise){G.then(ft=>{rt(Kt(ft)),At()}).catch(()=>{rt(De),At()});return}rt(Kt(G)),At()},Ie=[],pe=!1,X,$e=()=>{pe||(pe=!0,queueMicrotask(()=>{pe=!1,X()}))},St=new gi((_,ae)=>{Ie.push({payloadType:_,payload:ae}),$e()}),J=null,Oe=new Map,In=(Ot=this.config.iterationDisplay)!=null?Ot:"separate";for(X=()=>{var _,ae,De,Qe,Ne,_e,rt,At,_t,Kt,G,ft,ot,Ut,ie,xe,Ct,Vt,Zt,xn,Mt,Tt,bt,vt,zt,et,On,eo,wn,Nn,mt,So,_n,pr,Rn,Fr,Uo,Ro,xt,Vn,$n,Cn,Pt,to,no,Un,zo,Po,qo,zn,Bt,Sn,oo,jo,Wo,Ko,Ao,qn,uo,ht,Gt,Yt,jn,Go,ro,mo,Kn,k,Gn,go,Bo,To,ms,fo,ho,bo,Ho,ur,Ma,gs,La,Or,gt,fs,so,Pn,Ia,Ra,Nr,Do,Pa,mr,hs,Fo,bs,Yo,Xo,Wa,Ba,ll,gr,Qo,Ha,ys,Jo,Da,vs,Zo,xs,Fa,Oo,Oa,er,Ht,_r,Vr,ws,ko,Na,Cs,Ss,_a,$r,Ur,fr,Va,$a,As,Ts,ks,Es,An,Yn,No,st,Ms,hr,yo;for(let zr=0;zr<Ie.length;zr++){let ze=Ie[zr].payloadType,T=Ie[zr].payload;if(ze==="reason_start"){let z=(_=le(T,!0))!=null?_:`reason-${l()}`,P=Ce(z);P.reasoning=(ae=P.reasoning)!=null?ae:{id:z,status:"streaming",chunks:[]},P.reasoning.startedAt=(Qe=P.reasoning.startedAt)!=null?Qe:me((De=T.startedAt)!=null?De:T.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",p(P)}else if(ze==="reason_delta"||ze==="reason_chunk"){let z=(_e=(Ne=le(T,!1))!=null?Ne:le(T,!0))!=null?_e:`reason-${l()}`,P=Ce(z);P.reasoning=(rt=P.reasoning)!=null?rt:{id:z,status:"streaming",chunks:[]},P.reasoning.startedAt=(_t=P.reasoning.startedAt)!=null?_t:me((At=T.startedAt)!=null?At:T.timestamp);let te=(ft=(G=(Kt=T.reasoningText)!=null?Kt:T.text)!=null?G:T.delta)!=null?ft:"";if(te&&T.hidden!==!0){let ne=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ne!==void 0){let Y=de(z,ne,String(te));P.reasoning.chunks=[Y]}else P.reasoning.chunks.push(String(te))}if(P.reasoning.status=T.done?"complete":"streaming",T.done){P.reasoning.completedAt=me((ot=T.completedAt)!=null?ot:T.timestamp);let ne=(Ut=P.reasoning.startedAt)!=null?Ut:Date.now();P.reasoning.durationMs=Math.max(0,((ie=P.reasoning.completedAt)!=null?ie:Date.now())-ne)}P.streaming=P.reasoning.status!=="complete",p(P)}else if(ze==="reason_complete"){let z=(Ct=(xe=le(T,!1))!=null?xe:le(T,!0))!=null?Ct:`reason-${l()}`,P=B.get(z);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=me((Vt=T.completedAt)!=null?Vt:T.timestamp);let ne=(Zt=P.reasoning.startedAt)!=null?Zt:Date.now();P.reasoning.durationMs=Math.max(0,((xn=P.reasoning.completedAt)!=null?xn:Date.now())-ne),P.streaming=!1,p(P)}let te=O(T);te&&H.byStep.delete(te)}else if(ze==="tool_start"){let z=(Mt=he(T,!0))!=null?Mt:`tool-${l()}`,P=(Tt=T.toolName)!=null?Tt:T.name;if(Te(P)){ve.add(z);continue}let te=ce(z),ne=(bt=te.toolCall)!=null?bt:{id:z,status:"pending"};ne.name=P!=null?P:ne.name,ne.status="running",T.args!==void 0?ne.args=T.args:T.parameters!==void 0&&(ne.args=T.parameters),ne.startedAt=(zt=ne.startedAt)!=null?zt:me((vt=T.startedAt)!=null?vt:T.timestamp),ne.completedAt=void 0,ne.durationMs=void 0,te.toolCall=ne,te.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(te.agentMetadata={executionId:(et=Y==null?void 0:Y.executionId)!=null?et:T.executionId,iteration:(On=Y==null?void 0:Y.iteration)!=null?On:T.iteration}),p(te)}else if(ze==="tool_chunk"||ze==="tool_delta"){let z=(wn=(eo=he(T,!1))!=null?eo:he(T,!0))!=null?wn:`tool-${l()}`;if(ve.has(z))continue;let P=ce(z),te=(Nn=P.toolCall)!=null?Nn:{id:z,status:"running"};te.startedAt=(So=te.startedAt)!=null?So:me((mt=T.startedAt)!=null?mt:T.timestamp);let ne=(Rn=(pr=(_n=T.text)!=null?_n:T.delta)!=null?pr:T.message)!=null?Rn:"";ne&&(te.chunks=(Fr=te.chunks)!=null?Fr:[],te.chunks.push(String(ne))),te.status="running",P.toolCall=te,P.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(xt=P.agentMetadata)!=null?xt:{executionId:(Uo=Y==null?void 0:Y.executionId)!=null?Uo:T.executionId,iteration:(Ro=Y==null?void 0:Y.iteration)!=null?Ro:T.iteration}),p(P)}else if(ze==="tool_complete"){let z=($n=(Vn=he(T,!1))!=null?Vn:he(T,!0))!=null?$n:`tool-${l()}`;if(ve.has(z)){ve.delete(z);continue}let P=ce(z),te=(Cn=P.toolCall)!=null?Cn:{id:z,status:"running"};te.status="complete",T.result!==void 0&&(te.result=T.result),typeof T.duration=="number"&&(te.duration=T.duration),te.completedAt=me((Pt=T.completedAt)!=null?Pt:T.timestamp);let ne=(to=T.duration)!=null?to:T.executionTime;if(typeof ne=="number")te.durationMs=ne;else{let Fe=(no=te.startedAt)!=null?no:Date.now();te.durationMs=Math.max(0,((Un=te.completedAt)!=null?Un:Date.now())-Fe)}P.toolCall=te,P.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(qo=P.agentMetadata)!=null?qo:{executionId:(zo=Y==null?void 0:Y.executionId)!=null?zo:T.executionId,iteration:(Po=Y==null?void 0:Y.iteration)!=null?Po:T.iteration}),p(P);let qe=U(T);qe&&v.byCall.delete(qe)}else if(ze==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let z=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,P=(zn=z!=null?z:T.toolId)!=null?zn:`local-${l()}`,te=ce(P),ne=(Bt=te.toolCall)!=null?Bt:{id:P,status:"pending"};ne.name=T.toolName,ne.args=T.parameters,ne.status="complete",ne.chunks=(Sn=ne.chunks)!=null?Sn:[],ne.startedAt=(jo=ne.startedAt)!=null?jo:me((oo=T.startedAt)!=null?oo:T.timestamp),ne.completedAt=(Wo=ne.completedAt)!=null?Wo:ne.startedAt,te.toolCall=ne,te.streaming=!1,te.agentMetadata={...te.agentMetadata,executionId:(Ao=T.executionId)!=null?Ao:(Ko=te.agentMetadata)==null?void 0:Ko.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},p(te)}else if(ze==="text_start"){if((qn=T.toolContext)!=null&&qn.toolId)continue;let z=T.partId;if(z!==void 0&&C.current!==null&&z!==C.current){let P=f;P&&(P.streaming=!1,p(P),fe=P,f=null,L=!0)}z!==void 0&&(C.current=z)}else if(ze==="text_end"){if((uo=T.toolContext)!=null&&uo.toolId)continue;let z=f;z&&(z.streaming=!1,p(z),fe=z,f=null,L=!0)}else if(ze==="step_chunk"||ze==="step_delta"){let z=T.stepType,P=T.executionType;if(z==="tool"||P==="context")continue;let te=T.toolContext;if(te!=null&&te.toolId){let Fe=String((Gt=(ht=T.id)!=null?ht:te.stepId)!=null?Gt:`step-${l()}`),it=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Ge=`${te.toolId}::${Fe}`,Ye=F.get(Ge);if(it!==""&&Ye!==void 0&&Ye!==""&&Ye!==it){let kt=D.get(w(te.toolId,Fe,Ye));kt&&kt.streaming!==!1&&(kt.streaming=!1,p(kt))}it!==""&&F.set(Ge,it);let Je=A(te.toolId,Fe,it,te.executionId),Xt=(ro=(Go=(jn=(Yt=T.text)!=null?Yt:T.delta)!=null?jn:T.content)!=null?Go:T.chunk)!=null?ro:"";Xt&&(Je.content+=String(Xt),Je.streaming=!0,p(Je)),T.isComplete&&(Je.streaming=!1,p(Je));continue}let ne=T.partId;if(ne!==void 0&&C.current!==null&&ne!==C.current){let Fe=f;Fe&&(Fe.streaming=!1,p(Fe),fe=Fe,f=null,L=!0)}ne!==void 0&&(C.current=ne);let Y=ne!==void 0&&(mo=nt.get(ne))!=null?mo:se();ne!==void 0&&(Y.partId||(Y.partId=ne),nt.set(ne,Y));let qe=(go=(Gn=(k=(Kn=T.text)!=null?Kn:T.delta)!=null?k:T.content)!=null?Gn:T.chunk)!=null?go:"";if(qe){let Fe=typeof T.seq=="number"?T.seq:void 0,it=ne!=null?ne:Y.id,Ge=Fe!==void 0?de(it,Fe,String(qe)):((Bo=re.get(Y.id))!=null?Bo:"")+qe;Y.rawContent=Ge,K.has(Y.id)||K.set(Y.id,this.createStreamParser());let Ye=K.get(Y.id),Je=Ge.trim().startsWith("{")||Ge.trim().startsWith("[");if(Je&&re.set(Y.id,Ge),Ye.__isPlainTextParser===!0){Y.content=Fe!==void 0?Ge:Y.content+qe,re.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y);continue}let kt=Ye.processChunk(Ge);if(kt instanceof Promise)kt.then(It=>{var gn;let rn=typeof It=="string"?It:(gn=It==null?void 0:It.text)!=null?gn:null;if(rn!==null&&rn.trim()!=="")Y.content=rn,p(Y);else if(!Je&&!Ge.trim().startsWith("<")){let dn=f,en=dn&&dn.id===Y.id?dn:Y;en.id===Y.id&&(en.content=Fe!==void 0?Ge:en.content+qe,re.delete(en.id),K.delete(en.id),en.rawContent=void 0,p(en))}}).catch(()=>{Y.content=Fe!==void 0?Ge:Y.content+qe,re.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y)});else{let It=typeof kt=="string"?kt:(To=kt==null?void 0:kt.text)!=null?To:null;It!==null&&It.trim()!==""?(Y.content=It,p(Y)):!Je&&!Ge.trim().startsWith("<")&&(Y.content=Fe!==void 0?Ge:Y.content+qe,re.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y))}}if(T.isComplete){let Fe=(fo=(ms=T.result)==null?void 0:ms.response)!=null?fo:Y.content;if(Fe){let it=re.get(Y.id),Ge=it!=null?it:Ke(Fe);Y.rawContent=Ge;let Ye=K.get(Y.id),Je=null,Xt=!1;if(Ye&&(Je=Ye.getExtractedText(),Je===null&&(Je=Er(Ge)),Je===null)){let kt=Ye.processChunk(Ge);kt instanceof Promise?(Xt=!0,kt.then(It=>{var gn;let rn=typeof It=="string"?It:(gn=It==null?void 0:It.text)!=null?gn:null;if(rn!==null){let dn=f;dn&&dn.id===Y.id&&(dn.content=rn,dn.streaming=!1,K.delete(dn.id),re.delete(dn.id),p(dn))}})):Je=typeof kt=="string"?kt:(ho=kt==null?void 0:kt.text)!=null?ho:null}if(!Xt){Je!==null&&Je.trim()!==""?Y.content=Je:re.has(Y.id)||(Y.content=Ke(Fe));let kt=K.get(Y.id);if(kt){let It=(bo=kt.close)==null?void 0:bo.call(kt);It instanceof Promise&&It.catch(()=>{}),K.delete(Y.id)}re.delete(Y.id),Y.streaming=!1,p(Y)}}}}else if(ze==="step_complete"){let z=T.stepType,P=T.executionType;if(z==="tool"||P==="context")continue;let te=T.toolContext;if(te!=null&&te.toolId){let Fe=String((ur=(Ho=T.id)!=null?Ho:te.stepId)!=null?ur:"");if(Fe){let it=M(te.toolId,Fe);for(let[Ge,Ye]of D)Ge.startsWith(it)&&Ye.streaming!==!1&&(Ye.streaming=!1,p(Ye));F.delete(`${te.toolId}::${Fe}`)}continue}let ne=T.stopReason;if(L){if(f!==null){let Ge=f;ne&&(Ge.stopReason=ne),K.delete(Ge.id),re.delete(Ge.id),Ge.streaming!==!1&&(Ge.streaming=!1,p(Ge))}let Fe=(Ma=T.result)==null?void 0:Ma.response,it=fe;it&&(ne&&(it.stopReason=ne),Fe!=null?Ve(it,Fe):(K.delete(it.id),re.delete(it.id))),fe=null;continue}let Y=(gs=T.result)==null?void 0:gs.response,qe=se();if(ne&&(qe.stopReason=ne),Y!=null){let Fe=K.get(qe.id),it=!1,Ge=!1;if(Fe){let Ye=Fe.getExtractedText(),Je=re.get(qe.id),Xt=Je!=null?Je:Ke(Y);if(qe.rawContent=Xt,Ye!==null&&Ye.trim()!=="")qe.content=Ye,it=!0;else{let kt=Er(Xt);if(kt!==null)qe.content=kt,it=!0;else{let It=Fe.processChunk(Xt);if(It instanceof Promise)Ge=!0,It.then(rn=>{var dn;let gn=typeof rn=="string"?rn:(dn=rn==null?void 0:rn.text)!=null?dn:null;if(gn!==null&&gn.trim()!==""){let en=f;en&&en.id===qe.id&&(en.content=gn,en.streaming=!1,K.delete(en.id),re.delete(en.id),p(en))}else{let en=Fe.getExtractedText(),ao=f;ao&&ao.id===qe.id&&(en!==null&&en.trim()!==""?ao.content=en:re.has(ao.id)||(ao.content=Ke(Y)),ao.streaming=!1,K.delete(ao.id),re.delete(ao.id),p(ao))}});else{let rn=typeof It=="string"?It:(La=It==null?void 0:It.text)!=null?La:null;if(rn!==null&&rn.trim()!=="")qe.content=rn,it=!0;else{let gn=Fe.getExtractedText();gn!==null&&gn.trim()!==""&&(qe.content=gn,it=!0)}}}}}if(!Ge){if(!qe.rawContent){let Ye=re.get(qe.id);qe.rawContent=Ye!=null?Ye:Ke(Y)}if(!it&&!re.has(qe.id)&&(qe.content=Ke(Y)),Fe){let Ye=(Or=Fe.close)==null?void 0:Or.call(Fe);Ye instanceof Promise&&Ye.catch(()=>{})}K.delete(qe.id),re.delete(qe.id),qe.streaming=!1,p(qe)}}else K.delete(qe.id),re.delete(qe.id),qe.streaming=!1,p(qe)}else if(ze==="flow_complete"){let z=(gt=T.result)==null?void 0:gt.response;if(L){if(f!==null){let P=f;K.delete(P.id),re.delete(P.id),P.streaming!==!1&&(P.streaming=!1,p(P))}}else if(z!=null){let P=se(),te=re.get(P.id),ne=te!=null?te:Ke(z);P.rawContent=ne;let Y=Ke(z),qe=K.get(P.id);if(qe){let Ge=Er(ne);if(Ge!==null)Y=Ge;else{let Ye=qe.processChunk(ne);Ye instanceof Promise&&Ye.then(Xt=>{var It;let kt=typeof Xt=="string"?Xt:(It=Xt==null?void 0:Xt.text)!=null?It:null;kt!==null&&(P.content=kt,P.streaming=!1,p(P))});let Je=qe.getExtractedText();Je!==null&&(Y=Je)}}K.delete(P.id),re.delete(P.id);let Fe=Y!==P.content,it=P.streaming!==!1;Fe&&(P.content=Y),P.streaming=!1,(Fe||it)&&p(P)}else if(f!==null){let P=f;K.delete(P.id),re.delete(P.id),P.streaming!==!1&&(P.streaming=!1,p(P))}n({type:"status",status:"idle"})}else if(ze==="agent_start")J={executionId:T.executionId,agentId:(fs=T.agentId)!=null?fs:"virtual",agentName:(so=T.agentName)!=null?so:"",status:"running",currentIteration:0,maxTurns:(Pn=T.maxTurns)!=null?Pn:1,startedAt:me(T.startedAt)};else if(ze==="agent_iteration_start"){if(J&&(J.currentIteration=T.iteration),In==="separate"&&T.iteration>1){let z=f;z&&(z.streaming=!1,p(z),Oe.set(T.iteration-1,z),f=null)}}else if(ze==="agent_turn_start")g=null;else if(ze==="agent_turn_delta"){if(T.contentType==="text"){let z=se();z.content+=(Ia=T.delta)!=null?Ia:"",z.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:J==null?void 0:J.agentName},g=z,p(z)}else if(T.contentType==="thinking"){let z=(Ra=T.turnId)!=null?Ra:`agent-think-${T.iteration}`,P=Ce(z);P.reasoning=(Nr=P.reasoning)!=null?Nr:{id:z,status:"streaming",chunks:[]},P.reasoning.chunks.push((Do=T.delta)!=null?Do:""),P.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},p(P)}else if(T.contentType==="tool_input"){let z=(Pa=T.toolCallId)!=null?Pa:v.lastId;if(z){let P=I.get(z);P!=null&&P.toolCall&&(P.toolCall.chunks=(mr=P.toolCall.chunks)!=null?mr:[],P.toolCall.chunks.push((hs=T.delta)!=null?hs:""),p(P))}}}else if(ze==="agent_turn_complete"){let z=T.turnId;if(z){let ne=B.get(z);if(ne!=null&&ne.reasoning){ne.reasoning.status="complete",ne.reasoning.completedAt=me(T.completedAt);let Y=(Fo=ne.reasoning.startedAt)!=null?Fo:Date.now();ne.reasoning.durationMs=Math.max(0,((bs=ne.reasoning.completedAt)!=null?bs:Date.now())-Y),ne.streaming=!1,p(ne)}}let P=T.stopReason,te=f!=null?f:g;if(P&&te!==null){let ne=T.turnId;(!ne||((Yo=te.agentMetadata)==null?void 0:Yo.turnId)===ne)&&(te.stopReason=P,p(te))}}else if(ze==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let z=(Xo=T.toolCallId)!=null?Xo:`agent-tool-${l()}`;Be(U(T),z);let P=ce(z),te=(Wa=P.toolCall)!=null?Wa:{id:z,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};te.name=(ll=(Ba=T.toolName)!=null?Ba:T.name)!=null?ll:te.name,te.status="running",T.parameters!==void 0&&(te.args=T.parameters),te.startedAt=me((gr=T.startedAt)!=null?gr:T.timestamp),P.toolCall=te,P.streaming=!0,P.agentMetadata={executionId:T.executionId,iteration:T.iteration},p(P)}else if(ze==="agent_tool_delta"){let z=(Qo=T.toolCallId)!=null?Qo:v.lastId;if(z){let P=(Ha=I.get(z))!=null?Ha:ce(z);P.toolCall&&(P.toolCall.chunks=(ys=P.toolCall.chunks)!=null?ys:[],P.toolCall.chunks.push((Jo=T.delta)!=null?Jo:""),P.toolCall.status="running",P.streaming=!0,p(P))}}else if(ze==="agent_tool_complete"){let z=(Da=T.toolCallId)!=null?Da:v.lastId;if(z){let P=(vs=I.get(z))!=null?vs:ce(z);if(P.toolCall){P.toolCall.status="complete",T.result!==void 0&&(P.toolCall.result=T.result),typeof T.executionTime=="number"&&(P.toolCall.durationMs=T.executionTime),P.toolCall.completedAt=me((Zo=T.completedAt)!=null?Zo:T.timestamp),P.streaming=!1,p(P);let te=U(T);te&&v.byCall.delete(te)}}}else if(ze==="agent_media"){let z=Array.isArray(T.media)?T.media:[],P=[];for(let te of z){if(!te||typeof te!="object")continue;let ne=te,Y=typeof ne.type=="string"?ne.type:void 0,qe=typeof ne.mediaType=="string"?ne.mediaType.toLowerCase():"",Fe=null,it="";if(Y==="media"){let Ge=typeof ne.data=="string"?ne.data:void 0;if(!Ge)continue;it=qe.length>0?qe:"application/octet-stream",Fe=`data:${it};base64,${Ge}`}else if(Y==="image-url"){let Ge=typeof ne.url=="string"?ne.url:void 0;if(!Ge)continue;it=qe,Fe=Ge}else if(Y==="file-url"){let Ge=typeof ne.url=="string"?ne.url:void 0;if(!Ge)continue;it=qe,Fe=Ge}else continue;if(Fe)if(Y==="image-url"||it.startsWith("image/"))P.push({type:"image",image:Fe,...it?{mimeType:it}:{}});else if(it.startsWith("audio/"))P.push({type:"audio",audio:Fe,mimeType:it});else if(it.startsWith("video/"))P.push({type:"video",video:Fe,mimeType:it});else{let Ge=it||"application/octet-stream";P.push({type:"file",data:Fe,mimeType:Ge,filename:dh(Ge)})}}if(P.length>0){let te=l(),ne=T.toolCallId,qe={id:`agent-media-${typeof ne=="string"&&ne.length>0?`${ne}-${te}`:String(te)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:te,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};p(qe);let Fe=f;Fe&&(Fe.streaming=!1,p(Fe)),f=null,x.current=null}}else if(ze!=="agent_iteration_complete"){if(ze==="agent_reflection"||ze==="agent_reflect"){let z=`agent-reflection-${T.executionId}-${T.iteration}`,P={id:z,role:"assistant",content:(xs=T.reflection)!=null?xs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Fa=T.reflection)!=null?Fa:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};p(P)}else if(ze==="agent_complete"){J&&(J.status=T.success?"complete":"error",J.completedAt=me(T.completedAt),J.stopReason=T.stopReason);let z=f;z&&(z.streaming=!1,p(z)),n({type:"status",status:"idle"})}else if(ze==="agent_error"){let z=typeof T.error=="string"?T.error:(Oa=(Oo=T.error)==null?void 0:Oo.message)!=null?Oa:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(ze!=="agent_ping"){if(ze==="agent_approval_start"){let z=(er=T.approvalId)!=null?er:`approval-${l()}`,P={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ht=J==null?void 0:J.agentId)!=null?Ht:"virtual",executionId:(Vr=(_r=T.executionId)!=null?_r:J==null?void 0:J.executionId)!=null?Vr:"",toolName:(ws=T.toolName)!=null?ws:"",toolType:T.toolType,description:(Na=T.description)!=null?Na:`Execute ${(ko=T.toolName)!=null?ko:"tool"}`,parameters:T.parameters}};p(P)}else if(ze==="step_await"&&T.awaitReason==="approval_required"){let z=(Cs=T.approvalId)!=null?Cs:`approval-${l()}`,P={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ss=J==null?void 0:J.agentId)!=null?Ss:"virtual",executionId:($r=(_a=T.executionId)!=null?_a:J==null?void 0:J.executionId)!=null?$r:"",toolName:(Ur=T.toolName)!=null?Ur:"",toolType:T.toolType,description:(Va=T.description)!=null?Va:`Execute ${(fr=T.toolName)!=null?fr:"tool"}`,parameters:T.parameters}};p(P)}else if(ze==="agent_approval_complete"){let z=T.approvalId;if(z){let te={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:($a=T.decision)!=null?$a:"approved",agentId:(As=J==null?void 0:J.agentId)!=null?As:"virtual",executionId:(ks=(Ts=T.executionId)!=null?Ts:J==null?void 0:J.executionId)!=null?ks:"",toolName:(Es=T.toolName)!=null?Es:"",description:(An=T.description)!=null?An:"",resolvedAt:Date.now()}};p(te)}}else if(ze==="artifact_start"||ze==="artifact_delta"||ze==="artifact_update"||ze==="artifact_complete"){if(ze==="artifact_start"){let z=T.artifactType,P=String(T.id),te=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:P,artifactType:z,title:te,component:typeof T.component=="string"?T.component:void 0}),Q.set(P,{markdown:"",title:te}),!Me.has(P)){Me.add(P);let ne={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:te,artifactType:z,status:"streaming"}})};ee.set(P,ne),p(ne)}}else if(ze==="artifact_delta"){let z=String(T.id),P=typeof T.delta=="string"?T.delta:String((Yn=T.delta)!=null?Yn:"");n({type:"artifact_delta",id:z,artDelta:P});let te=Q.get(z);te&&(te.markdown+=P)}else if(ze==="artifact_update"){let z=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:z,component:typeof T.component=="string"?T.component:void 0})}else if(ze==="artifact_complete"){let z=String(T.id);n({type:"artifact_complete",id:z});let P=ee.get(z);if(P){P.streaming=!1;try{let te=JSON.parse((No=P.rawContent)!=null?No:"{}");if(te.props){te.props.status="complete";let ne=Q.get(z);ne!=null&&ne.markdown&&(te.props.markdown=ne.markdown)}P.rawContent=JSON.stringify(te)}catch{}Q.delete(z),p(P),ee.delete(z)}}}else if(ze==="transcript_insert"){let z=T.message;if(!z||typeof z!="object")continue;let P=String((st=z.id)!=null?st:`msg-${l()}`),te=z.role,Y={id:P,role:te==="user"?"user":te==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(p(Y),Y.rawContent)try{let qe=JSON.parse(Y.rawContent),Fe=(Ms=qe==null?void 0:qe.props)==null?void 0:Ms.artifactId;typeof Fe=="string"&&Me.add(Fe)}catch{}f=null,x.current=null,K.delete(P),re.delete(P)}else if(ze==="error"||ze==="step_error"||ze==="dispatch_error"||ze==="flow_error"){let z=null;if(T.error instanceof Error)z=T.error;else if(ze==="dispatch_error"){let P=(hr=T.message)!=null?hr:T.error;P!=null&&P!==""&&(z=new Error(String(P)))}else if(ze==="step_error"||ze==="flow_error"){let P=T.error;typeof P=="string"&&P!==""?z=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(z=new Error(String((yo=P.message)!=null?yo:P)))}else ze==="error"&&T.error!=null&&T.error!==""&&(z=new Error(String(T.error)));if(z){n({type:"error",error:z});let P=f;P&&P.streaming&&(P.streaming=!1,p(P)),n({type:"status",status:"idle"})}}}}}Ie.length=0};;){let{done:_,value:ae}=await r.read();if(_)break;a+=s.decode(ae,{stream:!0});let De=a.split(`
10
10
 
11
11
  `);a=(cn=De.pop())!=null?cn:"";for(let Qe of De){let Ne=Qe.split(`
12
- `),_e="message",rt="";for(let Kt of Ne)Kt.startsWith("event:")?_e=Kt.replace("event:","").trim():Kt.startsWith("data:")&&(rt+=Kt.replace("data:","").trim());if(!rt)continue;let At;try{At=JSON.parse(rt)}catch(Kt){n({type:"error",error:Kt instanceof Error?Kt:new Error("Failed to parse chat stream payload")});continue}let _t=_e!=="message"?_e:(Fn=At.type)!=null?Fn:"message";if((Zn=this.onSSEEvent)==null||Zn.call(this,_t,At),this.parseSSEEvent){w.current=g;let Kt=await this.handleCustomSSEEvent(At,n,w,p,l,x);if(w.current&&w.current!==g&&(g=w.current),Kt)continue}St.push(_t,At),X()}}St.flushPending(),X(),St.destroy()}};function hi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Js(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var bi="[Image]";function Pl(e){return{type:"text",text:e}}var nm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],dh=["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"],$o=[...nm,...dh];function ph(e){return nm.includes(e)||e.startsWith("image/")}function yi(e){return ph(e.type)}async function om(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;yi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function rm(e,t=$o,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function uh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function sm(e,t){let n=uh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var vi=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var xi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Zs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new xi;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let w=!1,x=W=>{w||(w=!0,clearTimeout(L),m(new Error(W)))},L=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(L),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",W=>{if(!W.wasClean&&!w){let B=W.code!==1006?` (code ${W.code})`:"";x("WebSocket connection failed"+B+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new vi(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Mr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let 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=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("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 ea(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Zs(e.runtype);case"browser":if(!Mr.isSupported())throw new Error("Browser speech recognition not supported");return new Mr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function am(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ea({type:"runtype",runtype:e.runtype});if(Mr.isSupported())return ea({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Wl(e){try{return am(e),!0}catch{return!1}}function im(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let 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 n.message?`${o}
12
+ `),_e="message",rt="";for(let Kt of Ne)Kt.startsWith("event:")?_e=Kt.replace("event:","").trim():Kt.startsWith("data:")&&(rt+=Kt.replace("data:","").trim());if(!rt)continue;let At;try{At=JSON.parse(rt)}catch(Kt){n({type:"error",error:Kt instanceof Error?Kt:new Error("Failed to parse chat stream payload")});continue}let _t=_e!=="message"?_e:(Fn=At.type)!=null?Fn:"message";if((Zn=this.onSSEEvent)==null||Zn.call(this,_t,At),this.parseSSEEvent){x.current=f;let Kt=await this.handleCustomSSEEvent(At,n,x,p,l,C);if(x.current&&x.current!==f&&(f=x.current),Kt)continue}St.push(_t,At),X()}}St.flushPending(),X(),St.destroy()}};function hi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Js(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var bi="[Image]";function Pl(e){return{type:"text",text:e}}var rm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],mh=["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"],$o=[...rm,...mh];function gh(e){return rm.includes(e)||e.startsWith("image/")}function yi(e){return gh(e.type)}async function sm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;yi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function am(e,t=$o,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function fh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function im(e,t){let n=fh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var vi=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var xi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Zs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new xi;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let x=!1,C=B=>{x||(x=!0,clearTimeout(L),g(new Error(B)))},L=setTimeout(()=>C("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(L),f())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",B=>{if(!B.wasClean&&!x){let I=B.code!==1006?` (code ${B.code})`:"";C("WebSocket connection failed"+I+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new vi(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Mr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let 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=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("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 ea(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Zs(e.runtype);case"browser":if(!Mr.isSupported())throw new Error("Browser speech recognition not supported");return new Mr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function lm(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ea({type:"runtype",runtype:e.runtype});if(Mr.isSupported())return ea({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Wl(e){try{return lm(e),!0}catch{return!1}}function cm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let 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 n.message?`${o}
13
13
 
14
- _Details: ${n.message}_`:o}var wi=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(u!=null&&u.name)&&Ll(u.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.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:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qs(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Wl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=ea(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,g,m,w,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let L=(x=this.pendingVoiceAssistantMessageId)!=null?x:(w=[...this.messages].reverse().find(W=>W.role==="assistant"))==null?void 0:w.id;L&&this.ttsSpokenMessageIds.add(L)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.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 n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Qs(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=t,m={id:a!=null?a:n==="user"?hi():n==="assistant"?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:g,rawContent:m}=o,x={id:d!=null?d:r==="user"?hi():r==="assistant"?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,u,p,g,m;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=hi(),s=Js(),a={id:r,role:"user",content:o||bi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(w){let x=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!x){let L=im(w,this.config.errorMessage);if(L){let W={id:s,role:"assistant",createdAt:new Date().toISOString(),content:L,sequence:this.nextSequence()};this.appendMessage(W)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(w instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,w):(m=(g=this.callbacks).onError)==null||m.call(g,new Error(String(w))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Js();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=im(l,this.config.errorMessage);if(p){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.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,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,u,p;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let m=null;if(g instanceof Response){if(!g.ok){let w=await g.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${g.status}`)}m=g.body}else g instanceof ReadableStream&&(m=g);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let m=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var u,p,g,m,w,x,L,W,B,D,V,H;let o=this.messages.find(v=>v.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let r=(p=t.agentMetadata)==null?void 0:p.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!r||!s){(w=(m=this.callbacks).onError)==null||w.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(x=t.toolCall)==null?void 0:x.args,C=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(C.length===1){let M=typeof((L=C[0])==null?void 0:L.question)=="string"?C[0].question:"";M&&(a={[M]:n})}}this.markAskUserQuestionResolved(t,a),(W=this.abortController)==null||W.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(B=t.toolCall)==null?void 0:B.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof n=="string"?n:Object.entries(n).map(([C,M])=>`${C}: ${Array.isArray(M)?M.join(", "):M}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((C,M)=>{let A=typeof(C==null?void 0:C.question)=="string"?C.question:"";if(!A)return;let E=v[A],F=Array.isArray(E)?E.join(", "):typeof E=="string"?E:"";this.appendMessage({id:`ask-user-q-${i}-${M}`,role:"assistant",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${M}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let C=await v.json().catch(()=>null);throw new Error((D=C==null?void 0:C.error)!=null?D:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,C||(H=(V=this.callbacks).onError)==null||H.call(V,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var B,D,V,H,v,C,M;let p=(B=u.toolCall)==null?void 0:B.name,g=(D=u.toolCall)==null?void 0:D.id;if(!p||!g)return null;let m=`${t}:${g}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),o.push(m),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let w=new AbortController;this.webMcpResolveControllers.add(w),r.push(w);let x=(H=(V=u.agentMetadata)==null?void 0:V.webMcpToolCallId)!=null?H:p,L=this.client.executeWebMcpToolCall(p,(v=u.toolCall)==null?void 0:v.args,w.signal),W;if(!L)W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{W=await L}catch(A){return A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"))||(M=(C=this.callbacks).onError)==null||M.call(C,A instanceof Error?A:new Error(String(A))),this.webMcpInflightKeys.delete(m),null}return w.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:x,output:W}}));try{let u=a.filter(m=>m!==null);if(u.length===0)return;let p={};for(let m of u)p[m.resumeKey]=m.output;let g=await this.client.resumeFlow(t,p,{signal:s.signal});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${g.status}`)}for(let m of u)this.webMcpResolvedKeys.add(m.dedupeKey);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,p,g,m,w,x,L,W,B,D,V,H;let n=(u=t.agentMetadata)==null?void 0:u.executionId,o=(p=t.toolCall)==null?void 0:p.name,r=(g=t.toolCall)==null?void 0:g.id;if(!n){(w=(m=this.callbacks).onError)==null||w.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(C){(L=(x=this.callbacks).onError)==null||L.call(x,C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(W=t.toolCall)==null?void 0:W.args,l=this.client.executeWebMcpToolCall(o,d,i);try{let v;if(l?v=await l:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let C=(D=(B=t.agentMetadata)==null?void 0:B.webMcpToolCallId)!=null?D:o;await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(v){v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"))||(H=(V=this.callbacks).onError)==null||H.call(V,v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.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 r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,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:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var u,p,g,m,w,x;if(s!==o)return r;let a={...r,...n};((u=r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(m=n.toolCall)==null?void 0:m.id;if(i&&Ll(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let L=`${d}:${l}`;(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Mo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var S=require("lucide"),mh={activity:S.Activity,"arrow-down":S.ArrowDown,"arrow-up":S.ArrowUp,"arrow-up-right":S.ArrowUpRight,bot:S.Bot,"chevron-down":S.ChevronDown,"chevron-up":S.ChevronUp,"chevron-right":S.ChevronRight,"chevron-left":S.ChevronLeft,check:S.Check,clipboard:S.Clipboard,"clipboard-copy":S.ClipboardCopy,copy:S.Copy,file:S.File,"file-code":S.FileCode,"file-spreadsheet":S.FileSpreadsheet,"file-text":S.FileText,"image-plus":S.ImagePlus,loader:S.Loader,"loader-circle":S.LoaderCircle,mic:S.Mic,paperclip:S.Paperclip,"refresh-cw":S.RefreshCw,search:S.Search,send:S.Send,"shield-alert":S.ShieldAlert,"shield-check":S.ShieldCheck,"shield-x":S.ShieldX,square:S.Square,"thumbs-down":S.ThumbsDown,"thumbs-up":S.ThumbsUp,upload:S.Upload,"volume-2":S.Volume2,x:S.X,user:S.User,mail:S.Mail,phone:S.Phone,calendar:S.Calendar,clock:S.Clock,building:S.Building,"map-pin":S.MapPin,lock:S.Lock,key:S.Key,"credit-card":S.CreditCard,"at-sign":S.AtSign,hash:S.Hash,globe:S.Globe,link:S.Link,"circle-check":S.CircleCheck,"circle-x":S.CircleX,"triangle-alert":S.TriangleAlert,info:S.Info,ban:S.Ban,shield:S.Shield,"arrow-left":S.ArrowLeft,"arrow-right":S.ArrowRight,"external-link":S.ExternalLink,ellipsis:S.Ellipsis,"ellipsis-vertical":S.EllipsisVertical,menu:S.Menu,house:S.House,plus:S.Plus,minus:S.Minus,pencil:S.Pencil,trash:S.Trash,"trash-2":S.Trash2,save:S.Save,download:S.Download,share:S.Share,funnel:S.Funnel,settings:S.Settings,"rotate-cw":S.RotateCw,maximize:S.Maximize,minimize:S.Minimize,"shopping-cart":S.ShoppingCart,"shopping-bag":S.ShoppingBag,package:S.Package,truck:S.Truck,tag:S.Tag,gift:S.Gift,receipt:S.Receipt,wallet:S.Wallet,store:S.Store,"dollar-sign":S.DollarSign,percent:S.Percent,play:S.Play,pause:S.Pause,"volume-x":S.VolumeX,camera:S.Camera,image:S.Image,film:S.Film,headphones:S.Headphones,"message-circle":S.MessageCircle,"message-square":S.MessageSquare,bell:S.Bell,heart:S.Heart,star:S.Star,eye:S.Eye,"eye-off":S.EyeOff,bookmark:S.Bookmark,"calendar-days":S.CalendarDays,history:S.History,timer:S.Timer,folder:S.Folder,"folder-open":S.FolderOpen,files:S.Files,sparkles:S.Sparkles,zap:S.Zap,sun:S.Sun,moon:S.Moon,flag:S.Flag,monitor:S.Monitor,smartphone:S.Smartphone},Ae=(e,t=24,n="currentColor",o=2)=>{let r=mh[e];return r?fh(r,t,n,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 fh(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),r.appendChild(d)}),r}var Ci={allowedTypes:$o,maxFileSize:10*1024*1024,maxFiles:4};function gh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function hh(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 ta=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ci.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ci.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Ci.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ci.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let u=rm(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(r=u.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await om(l),g=yi(l)?URL.createObjectURL(l):null,m={id:gh(),file:l,previewUrl:g,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=yi(t.file),o=b("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",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=hh(t.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=sm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var lm=require("idiomorph"),Si=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;lm.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Ai={index:-1,draft:""};function cm(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ai}}}function dm(e,t){var n,o,r,s,a,i,d,l,u,p,g,m,w,x,L,W,B,D,V,H,v,C,M,A,E,F,U,j,fe,se,ye,le,Ce,Be,ve,ee,Me,Q;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(g=(p=e.approval)==null?void 0:p.status)!=null?g:"",(w=(m=e.toolCall)==null?void 0:m.status)!=null?w:"",(L=(x=e.toolCall)==null?void 0:x.name)!=null?L:"",(D=(B=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:B.length)!=null?D:0,(C=(v=(H=(V=e.toolCall)==null?void 0:V.chunks)==null?void 0:H[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?C:"",typeof((M=e.toolCall)==null?void 0:M.args)=="string"?e.toolCall.args.length:(A=e.toolCall)!=null&&A.args?JSON.stringify(e.toolCall.args).length:0,(U=(F=(E=e.reasoning)==null?void 0:E.chunks)==null?void 0:F.length)!=null?U:0,(ye=(se=(fe=(j=e.reasoning)==null?void 0:j.chunks)==null?void 0:fe[e.reasoning.chunks.length-1])==null?void 0:se.length)!=null?ye:0,(ve=(Be=(Ce=(le=e.reasoning)==null?void 0:le.chunks)==null?void 0:Ce[e.reasoning.chunks.length-1])==null?void 0:Be.slice(-32))!=null?ve:"",(Me=(ee=e.contentParts)==null?void 0:ee.length)!=null?Me:0,(Q=e.stopReason)!=null?Q:"",t].join("\0")}function pm(){return new Map}function um(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function mm(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function fm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ti(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function na(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function oa(e,t){return na(e)-e.scrollTop<=t}function ki(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Ei(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var bn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,rr=yn+1;var ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},bh=["pre","code","a","script","style"],Mi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:ra.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ra.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:ra.speed,duration:(r=e==null?void 0:e.duration)!=null?r:ra.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ra.buffer}},yh=[{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"}],hm=new Map;for(let e of yh)hm.set(e.name,e);var sa=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=hm.get(e))!=null?o:null},Li=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
15
- `);return s<0?"":e.slice(0,s)}return e},vh=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},xh=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Bl=/\s/,wh=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Ch=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(Bl.test(s[i])){let l=i;for(;l<s.length&&Bl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Bl.test(s[u]);)l.appendChild(vh(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}r.replaceChild(a,e)},Sh=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(o.createTextNode(l)):(a.appendChild(xh(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},aa=(e,t,n,o)=>{var p,g;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((p=o==null?void 0:o.skipTags)!=null?p:bh).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)wh(d,s)||i.push(d),d=a.nextNode();let l={value:(g=o==null?void 0:o.startIndex)!=null?g:0},u=t==="char"?Ch:Sh;for(let m of i)u(m,n,l);return r.innerHTML},Ii=(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},ia=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},gm=new WeakMap,Ah=(e,t)=>{var s;if(!e.styles)return;let n=gm.get(t);if(n||(n=new Set,gm.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Hl=new WeakMap,Th=(e,t)=>{if(!e.onAttach)return;let n=Hl.get(t);if(n||(n=new Map,Hl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},bm=e=>{let t=Hl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Dl=(e,t)=>{Ah(e,t),Th(e,t)};function Fl(e,t=yn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var la=0,sr=null;function Ol(e=document){var n;if(la++,la===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;sr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:s},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${s}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,la=Math.max(0,la-1),la===0&&sr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=sr.originalOverflow,r.style.position=sr.originalPosition,r.style.top=sr.originalTop,r.style.width=sr.originalWidth,s.scrollTo(0,sr.scrollY),sr=null}}}var Ri={side:"right",width:"420px",animate:!0,reveal:"resize"},mn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},ca=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Lo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Ri.side,width:(r=t==null?void 0:t.width)!=null?r:Ri.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ri.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ri.reveal}};var Co={"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 da=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:o}var wi=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(u!=null&&u.name)&&Ll(u.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.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:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qs(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Wl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=ea(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,g,x,C;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.text)!=null&&g.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let L=(C=this.pendingVoiceAssistantMessageId)!=null?C:(x=[...this.messages].reverse().find(B=>B.role==="assistant"))==null?void 0:x.id;L&&this.ttsSpokenMessageIds.add(L)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.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 n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Qs(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=t,g={id:a!=null?a:n==="user"?hi():n==="assistant"?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:g}=o,C={id:d!=null?d:r==="user"?hi():r==="assistant"?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,u,p,f,g;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=hi(),s=Js(),a={id:r,role:"user",content:o||bi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let L=cm(x,this.config.errorMessage);if(L){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:L,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Js();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=cm(l,this.config.errorMessage);if(p){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.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,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,u,p;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):f=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let g=null;if(f instanceof Response){if(!f.ok){let x=await f.json().catch(()=>null);throw new Error((l=x==null?void 0:x.error)!=null?l:`Approval request failed: ${f.status}`)}g=f.body}else f instanceof ReadableStream&&(g=f);g?await this.connectStream(g,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let g=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var u,p,f,g,x,C,L,B,I,D,F,H;let o=this.messages.find(v=>v.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let r=(p=t.agentMetadata)==null?void 0:p.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(x=(g=this.callbacks).onError)==null||x.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(C=t.toolCall)==null?void 0:C.args,w=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(w.length===1){let M=typeof((L=w[0])==null?void 0:L.question)=="string"?w[0].question:"";M&&(a={[M]:n})}}this.markAskUserQuestionResolved(t,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof n=="string"?n:Object.entries(n).map(([w,M])=>`${w}: ${Array.isArray(M)?M.join(", "):M}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((w,M)=>{let A=typeof(w==null?void 0:w.question)=="string"?w.question:"";if(!A)return;let E=v[A],O=Array.isArray(E)?E.join(", "):typeof E=="string"?E:"";this.appendMessage({id:`ask-user-q-${i}-${M}`,role:"assistant",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${M}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let w=await v.json().catch(()=>null);throw new Error((D=w==null?void 0:w.error)!=null?D:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let w=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(H=(F=this.callbacks).onError)==null||H.call(F,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var I,D,F,H,v,w,M;let p=(I=u.toolCall)==null?void 0:I.name,f=(D=u.toolCall)==null?void 0:D.id;if(!p||!f)return null;let g=`${t}:${f}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g))return null;this.webMcpInflightKeys.add(g),o.push(g),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let x=new AbortController;this.webMcpResolveControllers.add(x),r.push(x);let C=(H=(F=u.agentMetadata)==null?void 0:F.webMcpToolCallId)!=null?H:p,L=this.client.executeWebMcpToolCall(p,(v=u.toolCall)==null?void 0:v.args,x.signal),B;if(!L)B={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{B=await L}catch(A){return A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"))||(M=(w=this.callbacks).onError)==null||M.call(w,A instanceof Error?A:new Error(String(A))),this.webMcpInflightKeys.delete(g),null}return x.signal.aborted?(this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:C,output:B}}));try{let u=a.filter(g=>g!==null);if(u.length===0)return;let p={};for(let g of u)p[g.resumeKey]=g.output;let f=await this.client.resumeFlow(t,p,{signal:s.signal});if(!f.ok){let g=await f.json().catch(()=>null);throw new Error((i=g==null?void 0:g.error)!=null?i:`Resume failed: ${f.status}`)}for(let g of u)this.webMcpResolvedKeys.add(g.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,p,f,g,x,C,L,B,I,D,F,H;let n=(u=t.agentMetadata)==null?void 0:u.executionId,o=(p=t.toolCall)==null?void 0:p.name,r=(f=t.toolCall)==null?void 0:f.id;if(!n){(x=(g=this.callbacks).onError)==null||x.call(g,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(w){(L=(C=this.callbacks).onError)==null||L.call(C,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(B=t.toolCall)==null?void 0:B.args,l=this.client.executeWebMcpToolCall(o,d,i);try{let v;if(l?v=await l:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let w=(D=(I=t.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?D:o;await this.resumeWithToolOutput(n,w,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(v){v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"))||(H=(F=this.callbacks).onError)==null||H.call(F,v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,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:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var u,p,f,g,x,C;if(s!==o)return r;let a={...r,...n};((u=r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(g=n.toolCall)==null?void 0:g.id;if(i&&Ll(i)&&d&&l&&((x=n.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let L=`${d}:${l}`;(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))&&(a.agentMetadata={...(C=a.agentMetadata)!=null?C:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Mo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var S=require("lucide"),hh={activity:S.Activity,"arrow-down":S.ArrowDown,"arrow-up":S.ArrowUp,"arrow-up-right":S.ArrowUpRight,bot:S.Bot,"chevron-down":S.ChevronDown,"chevron-up":S.ChevronUp,"chevron-right":S.ChevronRight,"chevron-left":S.ChevronLeft,check:S.Check,clipboard:S.Clipboard,"clipboard-copy":S.ClipboardCopy,copy:S.Copy,file:S.File,"file-code":S.FileCode,"file-spreadsheet":S.FileSpreadsheet,"file-text":S.FileText,"image-plus":S.ImagePlus,loader:S.Loader,"loader-circle":S.LoaderCircle,mic:S.Mic,paperclip:S.Paperclip,"refresh-cw":S.RefreshCw,search:S.Search,send:S.Send,"shield-alert":S.ShieldAlert,"shield-check":S.ShieldCheck,"shield-x":S.ShieldX,square:S.Square,"thumbs-down":S.ThumbsDown,"thumbs-up":S.ThumbsUp,upload:S.Upload,"volume-2":S.Volume2,x:S.X,user:S.User,mail:S.Mail,phone:S.Phone,calendar:S.Calendar,clock:S.Clock,building:S.Building,"map-pin":S.MapPin,lock:S.Lock,key:S.Key,"credit-card":S.CreditCard,"at-sign":S.AtSign,hash:S.Hash,globe:S.Globe,link:S.Link,"circle-check":S.CircleCheck,"circle-x":S.CircleX,"triangle-alert":S.TriangleAlert,info:S.Info,ban:S.Ban,shield:S.Shield,"arrow-left":S.ArrowLeft,"arrow-right":S.ArrowRight,"external-link":S.ExternalLink,ellipsis:S.Ellipsis,"ellipsis-vertical":S.EllipsisVertical,menu:S.Menu,house:S.House,plus:S.Plus,minus:S.Minus,pencil:S.Pencil,trash:S.Trash,"trash-2":S.Trash2,save:S.Save,download:S.Download,share:S.Share,funnel:S.Funnel,settings:S.Settings,"rotate-cw":S.RotateCw,maximize:S.Maximize,minimize:S.Minimize,"shopping-cart":S.ShoppingCart,"shopping-bag":S.ShoppingBag,package:S.Package,truck:S.Truck,tag:S.Tag,gift:S.Gift,receipt:S.Receipt,wallet:S.Wallet,store:S.Store,"dollar-sign":S.DollarSign,percent:S.Percent,play:S.Play,pause:S.Pause,"volume-x":S.VolumeX,camera:S.Camera,image:S.Image,film:S.Film,headphones:S.Headphones,"message-circle":S.MessageCircle,"message-square":S.MessageSquare,bell:S.Bell,heart:S.Heart,star:S.Star,eye:S.Eye,"eye-off":S.EyeOff,bookmark:S.Bookmark,"calendar-days":S.CalendarDays,history:S.History,timer:S.Timer,folder:S.Folder,"folder-open":S.FolderOpen,files:S.Files,sparkles:S.Sparkles,zap:S.Zap,sun:S.Sun,moon:S.Moon,flag:S.Flag,monitor:S.Monitor,smartphone:S.Smartphone},Ae=(e,t=24,n="currentColor",o=2)=>{let r=hh[e];return r?bh(r,t,n,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 bh(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),r.appendChild(d)}),r}var Ci={allowedTypes:$o,maxFileSize:10*1024*1024,maxFiles:4};function yh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vh(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 ta=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ci.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ci.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Ci.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ci.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let u=am(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(r=u.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await sm(l),f=yi(l)?URL.createObjectURL(l):null,g={id:yh(),file:l,previewUrl:f,contentPart:p};this.attachments.push(g),this.renderPreview(g)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=yi(t.file),o=b("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",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=vh(t.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=im(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var dm=require("idiomorph"),Si=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;dm.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Ai={index:-1,draft:""};function pm(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ai}}}function um(e,t){var n,o,r,s,a,i,d,l,u,p,f,g,x,C,L,B,I,D,F,H,v,w,M,A,E,O,U,j,ge,se,ye,le,Ce,Be,ve,ee,Me,Q;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(L=(C=e.toolCall)==null?void 0:C.name)!=null?L:"",(D=(I=(B=e.toolCall)==null?void 0:B.chunks)==null?void 0:I.length)!=null?D:0,(w=(v=(H=(F=e.toolCall)==null?void 0:F.chunks)==null?void 0:H[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?w:"",typeof((M=e.toolCall)==null?void 0:M.args)=="string"?e.toolCall.args.length:(A=e.toolCall)!=null&&A.args?JSON.stringify(e.toolCall.args).length:0,(U=(O=(E=e.reasoning)==null?void 0:E.chunks)==null?void 0:O.length)!=null?U:0,(ye=(se=(ge=(j=e.reasoning)==null?void 0:j.chunks)==null?void 0:ge[e.reasoning.chunks.length-1])==null?void 0:se.length)!=null?ye:0,(ve=(Be=(Ce=(le=e.reasoning)==null?void 0:le.chunks)==null?void 0:Ce[e.reasoning.chunks.length-1])==null?void 0:Be.slice(-32))!=null?ve:"",(Me=(ee=e.contentParts)==null?void 0:ee.length)!=null?Me:0,(Q=e.stopReason)!=null?Q:"",t].join("\0")}function mm(){return new Map}function gm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function fm(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function hm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ti(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function na(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function oa(e,t){return na(e)-e.scrollTop<=t}function ki(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Ei(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var bn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,rr=yn+1;var ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},xh=["pre","code","a","script","style"],Mi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:ra.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ra.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:ra.speed,duration:(r=e==null?void 0:e.duration)!=null?r:ra.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ra.buffer}},wh=[{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"}],ym=new Map;for(let e of wh)ym.set(e.name,e);var sa=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=ym.get(e))!=null?o:null},Li=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
15
+ `);return s<0?"":e.slice(0,s)}return e},Ch=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},Sh=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Bl=/\s/,Ah=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Th=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(Bl.test(s[i])){let l=i;for(;l<s.length&&Bl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Bl.test(s[u]);)l.appendChild(Ch(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}r.replaceChild(a,e)},kh=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(o.createTextNode(l)):(a.appendChild(Sh(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},aa=(e,t,n,o)=>{var p,f;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((p=o==null?void 0:o.skipTags)!=null?p:xh).map(g=>g.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Ah(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},u=t==="char"?Th:kh;for(let g of i)u(g,n,l);return r.innerHTML},Ii=(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},ia=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},bm=new WeakMap,Eh=(e,t)=>{var s;if(!e.styles)return;let n=bm.get(t);if(n||(n=new Set,bm.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Hl=new WeakMap,Mh=(e,t)=>{if(!e.onAttach)return;let n=Hl.get(t);if(n||(n=new Map,Hl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},vm=e=>{let t=Hl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Dl=(e,t)=>{Eh(e,t),Mh(e,t)};function Fl(e,t=yn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var la=0,sr=null;function Ol(e=document){var n;if(la++,la===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;sr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:s},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${s}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,la=Math.max(0,la-1),la===0&&sr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=sr.originalOverflow,r.style.position=sr.originalPosition,r.style.top=sr.originalTop,r.style.width=sr.originalWidth,s.scrollTo(0,sr.scrollY),sr=null}}}var Ri={side:"right",width:"420px",animate:!0,reveal:"resize"},mn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},ca=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Lo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Ri.side,width:(r=t==null?void 0:t.width)!=null?r:Ri.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ri.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ri.reveal}};var Co={"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 da=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
16
16
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
17
17
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
18
18
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -20,14 +20,14 @@ _Details: ${n.message}_`:o}var wi=class e{constructor(t={},n){this.config=t;this
20
20
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
21
21
  </span>
22
22
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
23
- `,n.addEventListener("click",t);let o=s=>{var D,V,H,v,C,M,A,E,F,U,j,fe,se,ye;let a=(D=s.launcher)!=null?D:{},i=mn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let le=(V=a.title)!=null?V:"Chat Assistant";d.textContent=le,d.setAttribute("title",le)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let le=(H=a.subtitle)!=null?H:"Get answers fast";l.textContent=le,l.setAttribute("title",le)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let le=(v=a.agentIconSize)!=null?v:"40px";if(p.style.height=le,p.style.width=le,p.innerHTML="",a.agentIconName){let Ce=parseFloat(le)||24,Be=Ae(a.agentIconName,Ce*.6,"var(--persona-text-inverse, #ffffff)",2);Be?(p.appendChild(Be),p.style.display=""):(p.textContent=(C=a.agentIconText)!=null?C:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(M=a.agentIconText)!=null?M:"\u{1F4AC}",p.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let le=(A=a.agentIconSize)!=null?A:"40px";g.style.height=le,g.style.width=le,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let le=(E=a.callToActionIconSize)!=null?E:"32px";m.style.height=le,m.style.width=le,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ce=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Ce=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Be=parseFloat(le)||24,ve=Math.max(Be-Ce,8),ee=Ae(a.callToActionIconName,ve,"currentColor",2);ee?m.appendChild(ee):m.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}let w=a.position&&Co[a.position]?Co[a.position]:Co["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?L:`${x} ${w}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:yn));let W="1px solid var(--persona-border, #e5e7eb)",B="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(fe=a.border)!=null?fe:W,n.style.boxShadow=(se=a.shadow)!=null?se:B,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ye=a.collapsedMaxWidth)!=null?ye:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var kh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Pi=(e,t={})=>{var x,L,W,B,D,V;let{showClose:n=!0,wrapperClassName:o=kh,buttonSize:r,iconSize:s="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(L=r!=null?r:a.closeButtonSize)!=null?L:"32px",d=b("div",o),l=b("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=(W=a.closeButtonTooltipText)!=null?W:"Close chat",p=(B=a.closeButtonShowTooltip)!=null?B:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let g=(D=a.closeButtonIconName)!=null?D:"x",m=(V=a.closeButtonIconText)!=null?V:"\xD7";l.style.color=a.closeButtonColor||Ln.actionIconColor;let w=Ae(g,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let H=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${H} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let H=null,v=()=>{if(H)return;let M=l.ownerDocument,A=M.body;if(!A)return;H=Mo(M,"div","persona-clear-chat-tooltip"),H.textContent=u;let E=Mo(M,"div");E.className="persona-clear-chat-tooltip-arrow",H.appendChild(E);let F=l.getBoundingClientRect();H.style.position="fixed",H.style.zIndex=String(rr),H.style.left=`${F.left+F.width/2}px`,H.style.top=`${F.top-8}px`,H.style.transform="translate(-50%, -100%)",A.appendChild(H)},C=()=>{H&&H.parentNode&&(H.parentNode.removeChild(H),H=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",C),l.addEventListener("focus",v),l.addEventListener("blur",C),d._cleanupTooltip=()=>{C(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",C),l.removeEventListener("focus",v),l.removeEventListener("blur",C)}}return{button:l,wrapper:d}},Eh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wi=(e,t={})=>{var H,v,C,M,A,E,F,U,j,fe,se,ye,le;let{wrapperClassName:n=Eh,buttonSize:o,iconSize:r="20px"}=t,a=(v=((H=e==null?void 0:e.launcher)!=null?H:{}).clearChat)!=null?v:{},i=(C=o!=null?o:a.size)!=null?C:"32px",d=(M=a.iconName)!=null?M:"refresh-cw",l=(A=a.iconColor)!=null?A:"",u=(E=a.backgroundColor)!=null?E:"",p=(F=a.borderWidth)!=null?F:"",g=(U=a.borderColor)!=null?U:"",m=(j=a.borderRadius)!=null?j:"",w=(fe=a.paddingX)!=null?fe:"",x=(se=a.paddingY)!=null?se:"",L=(ye=a.tooltipText)!=null?ye:"Clear chat",W=(le=a.showTooltip)!=null?le:!0,B=b("div",n),D=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");D.style.height=i,D.style.width=i,D.type="button",D.setAttribute("aria-label",L),D.style.color=l||Ln.actionIconColor;let V=Ae(d,r,"currentColor",1);if(V&&(V.style.display="block",D.appendChild(V)),u&&(D.style.backgroundColor=u,D.classList.remove("hover:persona-bg-gray-100")),p||g){let Ce=p||"0px",Be=g||"transparent";D.style.border=`${Ce} solid ${Be}`,D.classList.remove("persona-border-none")}if(m&&(D.style.borderRadius=m,D.classList.remove("persona-rounded-full")),w&&(D.style.paddingLeft=w,D.style.paddingRight=w),x&&(D.style.paddingTop=x,D.style.paddingBottom=x),B.appendChild(D),W&&L){let Ce=null,Be=()=>{if(Ce)return;let ee=D.ownerDocument,Me=ee.body;if(!Me)return;Ce=Mo(ee,"div","persona-clear-chat-tooltip"),Ce.textContent=L;let Q=Mo(ee,"div");Q.className="persona-clear-chat-tooltip-arrow",Ce.appendChild(Q);let Te=D.getBoundingClientRect();Ce.style.position="fixed",Ce.style.zIndex=String(rr),Ce.style.left=`${Te.left+Te.width/2}px`,Ce.style.top=`${Te.top-8}px`,Ce.style.transform="translate(-50%, -100%)",Me.appendChild(Ce)},ve=()=>{Ce&&Ce.parentNode&&(Ce.parentNode.removeChild(Ce),Ce=null)};B.addEventListener("mouseenter",Be),B.addEventListener("mouseleave",ve),D.addEventListener("focus",Be),D.addEventListener("blur",ve),B._cleanupTooltip=()=>{ve(),B.removeEventListener("mouseenter",Be),B.removeEventListener("mouseleave",ve),D.removeEventListener("focus",Be),D.removeEventListener("blur",ve)}}return{button:D,wrapper:B}};var Ln={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Lr=e=>{var H,v,C,M,A,E,F,U,j,fe,se,ye,le,Ce,Be,ve;let{config:t,showClose:n=!0}=e,o=b("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 r=(H=t==null?void 0:t.launcher)!=null?H:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(C=r.closeButtonPlacement)!=null?C:"inline",i=(M=r.headerIconHidden)!=null?M:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(s)||24,Me=Ae(d,ee*.6,"currentColor",1);Me?l.replaceChildren(Me):l.textContent=(E=(A=t==null?void 0:t.launcher)==null?void 0:A.agentIconText)!=null?E:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let ee=b("img");ee.src=t.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=s,ee.style.width=s,l.replaceChildren(ee)}else l.textContent=(j=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?j:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=b("span","persona-text-base persona-font-semibold");p.style.color=Ln.titleColor,p.textContent=(se=(fe=t==null?void 0:t.launcher)==null?void 0:fe.title)!=null?se:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Ln.subtitleColor,g.textContent=(le=(ye=t==null?void 0:t.launcher)==null?void 0:ye.subtitle)!=null?le:"Here to help you get answers fast",u.append(p,g),i?o.append(u):o.append(l,u);let m=(Ce=r.clearChat)!=null?Ce:{},w=(Be=m.enabled)!=null?Be:!0,x=(ve=m.placement)!=null?ve:"inline",L=null,W=null;if(w){let Me=Wi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=Me.button,W=Me.wrapper,x==="top-right"&&(W.style.right="48px"),x==="inline"&&o.appendChild(W)}let B=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:D,wrapper:V}=Pi(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&o.appendChild(V),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:g,closeButton:D,closeButtonWrapper:V,clearChatButton:L,clearChatButtonWrapper:W}},pa=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function es(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(rr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let L=document.createElement("hr");a.appendChild(L)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",m.id),m.destructive&&w.setAttribute("data-destructive",""),m.icon){let L=Ae(m.icon,16,"currentColor",1.5);L&&w.appendChild(L)}let x=document.createElement("span");x.textContent=m.label,w.appendChild(x),w.addEventListener("click",L=>{L.stopPropagation(),u(),n(m.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let m=o.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=w=>{!a.contains(w.target)&&!o.contains(w.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function g(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:g}}function vn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ae(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Nl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let u=b("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let g=Ae(t,s!=null?s:14,"currentColor",2);g&&u.appendChild(g)}let p=b("span");if(p.textContent=n,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[g,m]of Object.entries(d))u.setAttribute(g,m);return u}function ym(e){var m,w;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let u=b("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let p=Ae(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,L;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(L=d.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=es({items:o,onSelect:x=>{l.setAttribute("aria-expanded","false"),r(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let L=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Mh=e=>{var o;let t=Lr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Lh(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("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",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Ae(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=es({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Ih=e=>{var B,D,V,H,v,C,M,A,E;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(B=t==null?void 0:t.launcher)!=null?B:{},i=b("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=r==null?void 0:r.titleMenu,l,u;if(d)l=ym({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Ln.titleColor,u=(V=l.querySelector(".persona-combo-btn-label"))!=null?V:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Ln.titleColor,u.textContent=(H=a.title)!=null?H:"Chat Assistant",l.appendChild(u),Lh(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let U=r.onTitleClick;l.addEventListener("click",j=>{j.target.closest("button")||U()}),l.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),U())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(C=F.borderRadius)!=null?C:"10px",l.style.padding=(M=F.padding)!=null?M:"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 U,j;l.style.backgroundColor=(U=F.background)!=null?U:"",l.style.borderColor=(j=F.border)!=null?j:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(A=a.closeButtonSize)!=null?A:"32px",g=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Ln.actionIconColor;let w=(E=a.closeButtonIconName)!=null?E:"x",x=Ae(w,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m),i.appendChild(g);let L=b("div");L.style.display="none";let W=b("span");return W.style.display="none",{header:i,iconHolder:L,headerTitle:u,headerSubtitle:W,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},vm={default:Mh,minimal:Ih},Rh=e=>{var t;return(t=vm[e])!=null?t:vm.default},Bi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=b("div");u.style.display="none";let p=b("span"),g=b("span"),m=b("button");m.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:g,closeButton:m,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Rh(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Hi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Di=e=>{var H,v,C,M,A,E,F,U,j,fe,se,ye;let t=(H=e==null?void 0:e.sendButton)!=null?H:{},n=(v=t.useIcon)!=null?v:!1,o=(C=t.iconText)!=null?C:"\u2191",r=t.iconName,s=(M=t.stopIconName)!=null?M:"square",a=(A=t.tooltipText)!=null?A:"Send message",i=(E=t.stopTooltipText)!=null?E:"Stop generating",d=(U=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?U:"Send",l=(fe=(j=e==null?void 0:e.copy)==null?void 0:j.stopButtonLabel)!=null?fe:"Stop",u=(se=t.showTooltip)!=null?se:!1,p=(ye=t.size)!=null?ye:"40px",g=t.backgroundColor,m=t.textColor,w=b("div","persona-send-button-wrapper"),x=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let L=null,W=null;if(n){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let le=parseFloat(p)||24,Ce=(m==null?void 0:m.trim())||"currentColor";r?(L=Ae(r,le,Ce,2),L?x.appendChild(L):x.textContent=o):x.textContent=o,W=Ae(s,le,Ce,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let B=null;u&&a&&(B=b("div","persona-send-button-tooltip"),B.textContent=a,w.appendChild(B)),x.setAttribute("aria-label",a),w.appendChild(x);let D="send";return{button:x,wrapper:w,setMode:le=>{if(le===D)return;D=le;let Ce=le==="stop"?i:a;if(x.setAttribute("aria-label",Ce),B&&(B.textContent=Ce),n){if(L&&W){let Be=le==="stop"?W:L;x.replaceChildren(Be)}}else x.textContent=le==="stop"?l:d}}},Fi=e=>{var B,D,V,H,v,C,M,A,E,F,U,j;let t=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((D=t.provider)==null?void 0:D.type)==="runtype";if(!(o||r))return null;let a=(H=(V=e==null?void 0:e.sendButton)==null?void 0:V.size)!=null?H:"40px",i=b("div","persona-send-button-wrapper"),d=b("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=t.iconName)!=null?v:"mic",u=(C=t.iconSize)!=null?C:a,p=parseFloat(u)||24,g=(A=t.backgroundColor)!=null?A:(M=e==null?void 0:e.sendButton)==null?void 0:M.backgroundColor,m=(F=t.iconColor)!=null?F:(E=e==null?void 0:e.sendButton)==null?void 0:E.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Ae(l,p,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let L=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((j=t.showTooltip)!=null?j:!1)&&L){let fe=b("div","persona-send-button-tooltip");fe.textContent=L,i.appendChild(fe)}return{button:d,wrapper:i}},Oi=e=>{var w,x,L,W,B,D,V,H;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(L=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?L:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((W=t.allowedTypes)!=null?W:$o).join(","),r.multiple=((B=t.maxFiles)!=null?B:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(D=t.buttonTooltipText)!=null?D:"Attach file");let i=(V=t.buttonIconName)!=null?V:"paperclip",d=n,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=Ae(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let g=(H=t.buttonTooltipText)!=null?H:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=g,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},Ni=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},_i=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Vi=e=>{var w,x,L,W,B,D;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=_i(),r=b("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");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=Hi(t);a();let i=Di(t),d=Fi(t),l=Oi(t),u=Ni(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let p=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),p.append(g,m),r.append(p),r.addEventListener("click",V=>{V.target!==i.button&&V.target!==i.wrapper&&V.target!==(d==null?void 0:d.button)&&V.target!==(d==null?void 0:d.wrapper)&&V.target!==(l==null?void 0:l.button)&&V.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(W=l==null?void 0:l.wrapper)!=null?W:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:p,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var xm=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},wm=e=>{var w,x,L,W,B,D;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=_i();o.style.display="none";let r=Ni(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Hi(t);s.style.maxHeight="100px",a();let i=Di(t),d=Fi(t),l=Oi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=b("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),u.addEventListener("click",V=>{V.target!==i.button&&V.target!==i.wrapper&&V.target!==(d==null?void 0:d.button)&&V.target!==(d==null?void 0:d.wrapper)&&V.target!==(l==null?void 0:l.button)&&V.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(p,s,g),l&&n.append(l.previewsContainer),n.append(u,o,r);let m=u;return{footer:n,suggestions:o,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:r,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(W=l==null?void 0:l.wrapper)!=null?W:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:m,leftActions:p,rightActions:g,setSendButtonMode:i.setMode}};var Cm=e=>{var u,p,g,m,w,x,L,W,B,D,V,H,v,C,M,A,E;let t=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,n=mn(e);if(ca(e)){let F=(m=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?m:{},U=b("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(w=F.expandedSize)!=null?w:"anchored",U.style.zIndex=String((L=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?L:yn);let j=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");j.style.width="100%",U.appendChild(j);let fe=b("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(W=F.expandedSize)!=null?W:"anchored",fe.style.zIndex=String((D=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?D:yn),{wrapper:U,panel:j,pillRoot:fe}}if(n){let F=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild(U),{wrapper:F,panel:U}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),j=(H=(V=e==null?void 0:e.launcher)==null?void 0:V.width)!=null?H:"100%";return F.style.width=j,U.style.width="100%",F.appendChild(U),{wrapper:F,panel:U}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&Co[r.position]?Co[r.position]:Co["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:yn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(E=(A=e==null?void 0:e.launcher)==null?void 0:A.width)!=null?E:e==null?void 0:e.launcherWidth,l=d!=null?d:lo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ph=(e,t)=>{var V,H,v,C,M,A,E,F,U;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Pi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(H=(V=e==null?void 0:e.launcher)==null?void 0:V.clearChat)==null?void 0:H.enabled)!=null?v:!0,a=null,i=null;if(s){let j=Wi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,i=j.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(M=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?M:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(E=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",u.append(p,g);let m=b("div","persona-flex persona-flex-col persona-gap-3"),w=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;w&&(m.style.maxWidth=w,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let L=b("div","persona-composer-overlay persona-pointer-events-none");L.setAttribute("data-persona-composer-overlay",""),L.style.position="absolute",L.style.left="0",L.style.right="0",L.style.bottom="0",L.style.zIndex="20";let W=wm({config:e}),{root:B,textNode:D}=xm();return n.append(d,r,l,L),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:L,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:p,introSubtitle:g,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:B,peekTextNode:D}},Sm=(e,t=!0)=>{var L,W,B,D,V,H,v,C,M;if(ca(e))return Ph(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(L=e==null?void 0:e.layout)==null?void 0:L.header,r=((W=e==null?void 0:e.layout)==null?void 0:W.showHeader)!==!1,s=o?Bi(e,o,{showClose:t}):Lr({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=mn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(D=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?D:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(H=(V=e==null?void 0:e.copy)==null?void 0:V.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",i.append(d,l);let u=b("div","persona-flex persona-flex-col persona-gap-3"),p=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((C=e==null?void 0:e.copy)==null?void 0:C.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=Vi({config:e}),w=((M=e==null?void 0:e.layout)==null?void 0:M.showFooter)!==!1;r?pa(n,s,e):(s.header.style.display="none",pa(n,s,e)),n.append(a);let x=b("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",w||(m.footer.style.display="none"),n.append(m.footer),n.append(x),{container:n,body:a,messagesWrapper:u,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Wh=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}},Bh=(e,t)=>{if(!e)return null;let n=Wh(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Hh=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Dh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},_l=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(":"))},Vl=320,Tm=320,Fh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Oh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Nh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),_h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Vh=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=b("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Vl}px`,l.style.maxHeight=`${Tm}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;r+=1,l.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{u=!0}),Dh(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},$h=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!_l(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Uh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!_l(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vl}px`,r.style.maxHeight=`${Tm}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},zh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!_l(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===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 n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let 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 r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},qh=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let r=t(o);if(r!==null)return r}return ua()},jh=(e,t)=>{let n=b("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 r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Am=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Kh=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Gh=(e,t,n)=>{var m,w,x,L,W,B;let o=(m=t.showCopy)!=null?m:!0,r=(w=t.showUpvote)!=null?w:!0,s=(x=t.showDownvote)!=null?x:!0;if(!o&&!r&&!s){let D=b("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let a=(L=t.visibility)!=null?L:"hover",i=(W=t.align)!=null?W:"right",d=(B=t.layout)!=null?B:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let g=(D,V,H)=>{let v=vn({icon:D,label:V,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",H),v};return o&&p.appendChild(g("copy","Copy message","copy")),r&&p.appendChild(g("thumbs-up","Upvote","upvote")),s&&p.appendChild(g("thumbs-down","Downvote","downvote")),p},$l=(e,t,n,o,r,s)=>{var ee,Me,Q,Te,he,ce,me,Ke,K,re,Pe,nt,ge,de,Ve,Ie,pe;let a=n!=null?n:{},i=(ee=a.layout)!=null?ee:"bubble",d=a.avatar,l=a.timestamp,u=(Me=d==null?void 0:d.show)!=null?Me:!1,p=(Q=l==null?void 0:l.show)!=null?Q:!1,g=(Te=d==null?void 0:d.position)!=null?Te:"left",m=(he=l==null?void 0:l.position)!=null?he:"below",w=Kh(e.role,i),x=b("div",w.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=Fh(e),W=(me=(ce=e.content)==null?void 0:ce.trim())!=null?me:"",D=L.length>0&&W===bi,V=Mi((K=(Ke=s==null?void 0:s.widgetConfig)==null?void 0:Ke.features)==null?void 0:K.streamAnimation),H=(nt=(Pe=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.features)==null?void 0:Pe.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&V.type!=="none"?sa(V.type,H):null,C=e.role==="assistant"&&((ge=v==null?void 0:v.isAnimating)==null?void 0:ge.call(v,e))===!0,M=e.role==="assistant"&&v!==null&&(!!e.streaming||C);M&&(v!=null&&v.bubbleClass)&&x.classList.add(v.bubbleClass);let A=document.createElement("div");A.classList.add("persona-message-content"),M&&v&&(v.containerClass&&A.classList.add(v.containerClass),A.style.setProperty("--persona-stream-step",`${V.speed}ms`),A.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let E=M?Li((de=e.content)!=null?de:"",V.buffer,v,e,!!e.streaming):(Ve=e.content)!=null?Ve:"",F=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=F;M&&(v==null?void 0:v.wrap)==="char"?U=aa(F,"char",e.id,{skipTags:v.skipTags}):M&&(v==null?void 0:v.wrap)==="word"&&(U=aa(F,"word",e.id,{skipTags:v.skipTags}));let j=null;if(D?(j=document.createElement("div"),j.innerHTML=U,j.style.display="none",A.appendChild(j)):A.innerHTML=U,M&&(v!=null&&v.useCaret)&&!D&&W){let X=Ii(),$e=A.querySelectorAll(".persona-stream-char, .persona-stream-word"),St=$e[$e.length-1];if(St!=null&&St.parentNode)St.parentNode.insertBefore(X,St.nextSibling);else{let J=A.lastElementChild;J?J.appendChild(X):A.appendChild(X)}}if(p&&m==="inline"&&e.createdAt){let X=Am(e,l);X.classList.add("persona-ml-2","persona-inline"),A.appendChild(X)}if(L.length>0){let X=Vh(L,!D&&!!W,()=>{D&&j&&(j.style.display="")});X?x.appendChild(X):D&&j&&(j.style.display="")}let fe=Oh(e);if(fe.length>0){let X=$h(fe);X&&x.appendChild(X)}let se=Nh(e);if(se.length>0){let X=Uh(se);X&&x.appendChild(X)}let ye=_h(e);if(ye.length>0){let X=zh(ye);X&&x.appendChild(X)}if(x.appendChild(A),p&&m==="below"&&e.createdAt){let X=Am(e,l);X.classList.add("persona-mt-1"),x.appendChild(X)}let le=e.role==="assistant"?Bh(e.stopReason,(pe=(Ie=s==null?void 0:s.widgetConfig)==null?void 0:Ie.copy)==null?void 0:pe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(E&&E.trim()),$e=V.placeholder==="skeleton",St=$e&&V.buffer==="line"&&X;if(X)St&&x.appendChild(ia());else if($e)x.appendChild(ia());else{let J=qh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);J&&x.appendChild(J)}}if(le&&e.stopReason&&!e.streaming&&(W||(A.style.display="none"),x.appendChild(Hh(e.stopReason,le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=Gh(e,o,r);x.appendChild(X)}if(!u||e.role==="system")return x;let Be=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=jh(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Be.append(x,ve):Be.append(ve,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Be};var ts=new Set,Yh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Xh=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
24
- `):""},km=(e,t)=>{let n=ts.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ae(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Ul=(e,t)=>{var se,ye,le,Ce,Be,ve,ee,Me,Q,Te,he;let n=e.reasoning,o=b("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),!n)return o;let r=(ye=(se=t==null?void 0:t.features)==null?void 0:se.reasoningDisplay)!=null?ye:{},s=r.expandable!==!1,a=s&&ts.has(e.id),i=n.status!=="complete",d=Xh(e,(le=r.previewMaxLines)!=null?le:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=(Ce=t==null?void 0:t.reasoning)!=null?Ce:{},w=String((Be=n.startedAt)!=null?Be:Date.now()),x=()=>{let ce=b("span","");return ce.setAttribute("data-tool-elapsed",w),ce.textContent=ui(n),ce},L=(ve=m.renderCollapsedSummary)==null?void 0:ve.call(m,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ui(n),createElapsedElement:x});typeof L=="string"&&L.trim()?(p.textContent=L,u.appendChild(p)):L instanceof HTMLElement?u.appendChild(L):(p.textContent=g,u.appendChild(p));let W=b("span","persona-text-xs persona-text-persona-primary");W.textContent=Yu(n),u.appendChild(W);let B=(ee=r.loadingAnimation)!=null?ee:"none",D=m.activeTextTemplate,V=m.completeTextTemplate,H=i?D:V,v=L instanceof HTMLElement,C=(ce,me,Ke)=>{let K=Ke;for(let re of me){let Pe=b("span","persona-tool-char");Pe.style.setProperty("--char-index",String(K)),Pe.textContent=re===" "?"\xA0":re,ce.appendChild(Pe),K++}return K},M=(ce,me)=>{p.textContent="";let Ke=mi(ce,""),K=0;for(let re of Ke){let Pe=re.styles.length>0?(()=>{let nt=b("span",re.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return p.appendChild(nt),nt})():p;if(re.isDuration&&i)Pe.appendChild(x());else{let nt=re.isDuration?ui(n):re.text;me?K=C(Pe,nt,K):Pe.appendChild(document.createTextNode(nt))}}};if(!v&&H)if(W.style.display="none",p.style.display="",i&&B!=="none"){let ce=(Me=m.loadingAnimationDuration)!=null?Me:2e3;p.setAttribute("data-preserve-animation","true"),B==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),M(H,!1)):(p.classList.add(`persona-tool-loading-${B}`),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),B==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),M(H,!0))}else M(H,!1);else if(!v&&i&&B!=="none"){p.style.display="";let ce=(Q=m.loadingAnimationDuration)!=null?Q:2e3;if(p.setAttribute("data-preserve-animation","true"),B==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`);else{p.classList.add(`persona-tool-loading-${B}`),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),B==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let me=p.textContent||g;p.textContent="",C(p,me,0)}n.status==="complete"&&(p.style.display="none")}else v||(n.status==="complete"?p.style.display="none":p.style.display="");let A=null;if(s){A=b("div","persona-flex persona-items-center");let me=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);me?A.appendChild(me):A.textContent=a?"Hide":"Show";let Ke=b("div","persona-flex persona-items-center persona-ml-auto");Ke.append(A),l.append(u,Ke)}else l.append(u);let E=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(E.setAttribute("data-persona-collapsed-preview","reasoning"),E.style.display="none",E.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let ce=(he=(Te=t==null?void 0:t.reasoning)==null?void 0:Te.renderCollapsedPreview)==null?void 0:he.call(Te,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Yh(E,ce)||(E.textContent=d),E.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,E),o;let F=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let U=n.chunks.join(""),j=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return j.textContent=U||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(j),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),A){A.innerHTML="";let me=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);me?A.appendChild(me):A.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",E.style.display=a?"none":E.textContent||E.childNodes.length?"":"none"})(),o.append(l,E,F),o};var ns=new Set,Qh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Jh=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let o=((s=n.chunks)!=null?s:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
23
+ `,n.addEventListener("click",t);let o=s=>{var D,F,H,v,w,M,A,E,O,U,j,ge,se,ye;let a=(D=s.launcher)!=null?D:{},i=mn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let le=(F=a.title)!=null?F:"Chat Assistant";d.textContent=le,d.setAttribute("title",le)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let le=(H=a.subtitle)!=null?H:"Get answers fast";l.textContent=le,l.setAttribute("title",le)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let le=(v=a.agentIconSize)!=null?v:"40px";if(p.style.height=le,p.style.width=le,p.innerHTML="",a.agentIconName){let Ce=parseFloat(le)||24,Be=Ae(a.agentIconName,Ce*.6,"var(--persona-text-inverse, #ffffff)",2);Be?(p.appendChild(Be),p.style.display=""):(p.textContent=(w=a.agentIconText)!=null?w:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(M=a.agentIconText)!=null?M:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let le=(A=a.agentIconSize)!=null?A:"40px";f.style.height=le,f.style.width=le,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let le=(E=a.callToActionIconSize)!=null?E:"32px";g.style.height=le,g.style.width=le,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Ce=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Ce=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Be=parseFloat(le)||24,ve=Math.max(Be-Ce,8),ee=Ae(a.callToActionIconName,ve,"currentColor",2);ee?g.appendChild(ee):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}let x=a.position&&Co[a.position]?Co[a.position]:Co["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",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?L:`${C} ${x}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:yn));let B="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ge=a.border)!=null?ge:B,n.style.boxShadow=(se=a.shadow)!=null?se:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ye=a.collapsedMaxWidth)!=null?ye:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var Lh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Pi=(e,t={})=>{var C,L,B,I,D,F;let{showClose:n=!0,wrapperClassName:o=Lh,buttonSize:r,iconSize:s="28px"}=t,a=(C=e==null?void 0:e.launcher)!=null?C:{},i=(L=r!=null?r:a.closeButtonSize)!=null?L:"32px",d=b("div",o),l=b("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=(B=a.closeButtonTooltipText)!=null?B:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(D=a.closeButtonIconName)!=null?D:"x",g=(F=a.closeButtonIconText)!=null?F:"\xD7";l.style.color=a.closeButtonColor||Ln.actionIconColor;let x=Ae(f,s,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):l.textContent=g,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let H=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${H} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let H=null,v=()=>{if(H)return;let M=l.ownerDocument,A=M.body;if(!A)return;H=Mo(M,"div","persona-clear-chat-tooltip"),H.textContent=u;let E=Mo(M,"div");E.className="persona-clear-chat-tooltip-arrow",H.appendChild(E);let O=l.getBoundingClientRect();H.style.position="fixed",H.style.zIndex=String(rr),H.style.left=`${O.left+O.width/2}px`,H.style.top=`${O.top-8}px`,H.style.transform="translate(-50%, -100%)",A.appendChild(H)},w=()=>{H&&H.parentNode&&(H.parentNode.removeChild(H),H=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",w),l.addEventListener("focus",v),l.addEventListener("blur",w),d._cleanupTooltip=()=>{w(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",w),l.removeEventListener("focus",v),l.removeEventListener("blur",w)}}return{button:l,wrapper:d}},Ih="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wi=(e,t={})=>{var H,v,w,M,A,E,O,U,j,ge,se,ye,le;let{wrapperClassName:n=Ih,buttonSize:o,iconSize:r="20px"}=t,a=(v=((H=e==null?void 0:e.launcher)!=null?H:{}).clearChat)!=null?v:{},i=(w=o!=null?o:a.size)!=null?w:"32px",d=(M=a.iconName)!=null?M:"refresh-cw",l=(A=a.iconColor)!=null?A:"",u=(E=a.backgroundColor)!=null?E:"",p=(O=a.borderWidth)!=null?O:"",f=(U=a.borderColor)!=null?U:"",g=(j=a.borderRadius)!=null?j:"",x=(ge=a.paddingX)!=null?ge:"",C=(se=a.paddingY)!=null?se:"",L=(ye=a.tooltipText)!=null?ye:"Clear chat",B=(le=a.showTooltip)!=null?le:!0,I=b("div",n),D=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");D.style.height=i,D.style.width=i,D.type="button",D.setAttribute("aria-label",L),D.style.color=l||Ln.actionIconColor;let F=Ae(d,r,"currentColor",1);if(F&&(F.style.display="block",D.appendChild(F)),u&&(D.style.backgroundColor=u,D.classList.remove("hover:persona-bg-gray-100")),p||f){let Ce=p||"0px",Be=f||"transparent";D.style.border=`${Ce} solid ${Be}`,D.classList.remove("persona-border-none")}if(g&&(D.style.borderRadius=g,D.classList.remove("persona-rounded-full")),x&&(D.style.paddingLeft=x,D.style.paddingRight=x),C&&(D.style.paddingTop=C,D.style.paddingBottom=C),I.appendChild(D),B&&L){let Ce=null,Be=()=>{if(Ce)return;let ee=D.ownerDocument,Me=ee.body;if(!Me)return;Ce=Mo(ee,"div","persona-clear-chat-tooltip"),Ce.textContent=L;let Q=Mo(ee,"div");Q.className="persona-clear-chat-tooltip-arrow",Ce.appendChild(Q);let Te=D.getBoundingClientRect();Ce.style.position="fixed",Ce.style.zIndex=String(rr),Ce.style.left=`${Te.left+Te.width/2}px`,Ce.style.top=`${Te.top-8}px`,Ce.style.transform="translate(-50%, -100%)",Me.appendChild(Ce)},ve=()=>{Ce&&Ce.parentNode&&(Ce.parentNode.removeChild(Ce),Ce=null)};I.addEventListener("mouseenter",Be),I.addEventListener("mouseleave",ve),D.addEventListener("focus",Be),D.addEventListener("blur",ve),I._cleanupTooltip=()=>{ve(),I.removeEventListener("mouseenter",Be),I.removeEventListener("mouseleave",ve),D.removeEventListener("focus",Be),D.removeEventListener("blur",ve)}}return{button:D,wrapper:I}};var Ln={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Lr=e=>{var H,v,w,M,A,E,O,U,j,ge,se,ye,le,Ce,Be,ve;let{config:t,showClose:n=!0}=e,o=b("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 r=(H=t==null?void 0:t.launcher)!=null?H:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(w=r.closeButtonPlacement)!=null?w:"inline",i=(M=r.headerIconHidden)!=null?M:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(s)||24,Me=Ae(d,ee*.6,"currentColor",1);Me?l.replaceChildren(Me):l.textContent=(E=(A=t==null?void 0:t.launcher)==null?void 0:A.agentIconText)!=null?E:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let ee=b("img");ee.src=t.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=s,ee.style.width=s,l.replaceChildren(ee)}else l.textContent=(j=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?j:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=b("span","persona-text-base persona-font-semibold");p.style.color=Ln.titleColor,p.textContent=(se=(ge=t==null?void 0:t.launcher)==null?void 0:ge.title)!=null?se:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Ln.subtitleColor,f.textContent=(le=(ye=t==null?void 0:t.launcher)==null?void 0:ye.subtitle)!=null?le:"Here to help you get answers fast",u.append(p,f),i?o.append(u):o.append(l,u);let g=(Ce=r.clearChat)!=null?Ce:{},x=(Be=g.enabled)!=null?Be:!0,C=(ve=g.placement)!=null?ve:"inline",L=null,B=null;if(x){let Me=Wi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=Me.button,B=Me.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let I=a==="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:D,wrapper:F}=Pi(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(F),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:D,closeButtonWrapper:F,clearChatButton:L,clearChatButtonWrapper:B}},pa=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function es(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(rr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let L=document.createElement("hr");a.appendChild(L)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let L=Ae(g.icon,16,"currentColor",1.5);L&&x.appendChild(L)}let C=document.createElement("span");C.textContent=g.label,x.appendChild(C),x.addEventListener("click",L=>{L.stopPropagation(),u(),n(g.id)}),a.appendChild(x)}let i=null;function d(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function vn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ae(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Nl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let u=b("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let f=Ae(t,s!=null?s:14,"currentColor",2);f&&u.appendChild(f)}let p=b("span");if(p.textContent=n,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))u.setAttribute(f,g);return u}function xm(e){var g,x;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let u=b("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let p=Ae(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",l.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var C,L;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(L=d.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=es({items:o,onSelect:C=>{l.setAttribute("aria-expanded","false"),r(C)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",C=>{C.stopPropagation();let L=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"false":"true"),f.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{u.textContent=C,l.setAttribute("aria-label",C)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let C=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Rh=e=>{var o;let t=Lr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Ph(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("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",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Ae(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=es({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Wh=e=>{var I,D,F,H,v,w,M,A,E;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},i=b("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=r==null?void 0:r.titleMenu,l,u;if(d)l=xm({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Ln.titleColor,u=(F=l.querySelector(".persona-combo-btn-label"))!=null?F:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Ln.titleColor,u.textContent=(H=a.title)!=null?H:"Chat Assistant",l.appendChild(u),Ph(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let U=r.onTitleClick;l.addEventListener("click",j=>{j.target.closest("button")||U()}),l.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),U())})}let O=r==null?void 0:r.titleRowHover;O&&(l.style.borderRadius=(w=O.borderRadius)!=null?w:"10px",l.style.padding=(M=O.padding)!=null?M:"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 U,j;l.style.backgroundColor=(U=O.background)!=null?U:"",l.style.borderColor=(j=O.border)!=null?j:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(A=a.closeButtonSize)!=null?A:"32px",f=b("div",""),g=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=p,g.style.width=p,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Ln.actionIconColor;let x=(E=a.closeButtonIconName)!=null?E:"x",C=Ae(x,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),f.appendChild(g),i.appendChild(f);let L=b("div");L.style.display="none";let B=b("span");return B.style.display="none",{header:i,iconHolder:L,headerTitle:u,headerSubtitle:B,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},wm={default:Rh,minimal:Wh},Bh=e=>{var t;return(t=wm[e])!=null?t:wm.default},Bi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=b("div");u.style.display="none";let p=b("span"),f=b("span"),g=b("button");g.style.display="none";let x=b("div");return x.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Bh(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Hi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Di=e=>{var H,v,w,M,A,E,O,U,j,ge,se,ye;let t=(H=e==null?void 0:e.sendButton)!=null?H:{},n=(v=t.useIcon)!=null?v:!1,o=(w=t.iconText)!=null?w:"\u2191",r=t.iconName,s=(M=t.stopIconName)!=null?M:"square",a=(A=t.tooltipText)!=null?A:"Send message",i=(E=t.stopTooltipText)!=null?E:"Stop generating",d=(U=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?U:"Send",l=(ge=(j=e==null?void 0:e.copy)==null?void 0:j.stopButtonLabel)!=null?ge:"Stop",u=(se=t.showTooltip)!=null?se:!1,p=(ye=t.size)!=null?ye:"40px",f=t.backgroundColor,g=t.textColor,x=b("div","persona-send-button-wrapper"),C=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");C.type="submit",C.setAttribute("data-persona-composer-submit","");let L=null,B=null;if(n){C.style.width=p,C.style.height=p,C.style.minWidth=p,C.style.minHeight=p,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",g?C.style.color=g:C.style.color="var(--persona-button-primary-fg, #ffffff)";let le=parseFloat(p)||24,Ce=(g==null?void 0:g.trim())||"currentColor";r?(L=Ae(r,le,Ce,2),L?C.appendChild(L):C.textContent=o):C.textContent=o,B=Ae(s,le,Ce,2),f?C.style.backgroundColor=f:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,g?C.style.color=g:C.classList.add("persona-text-white");t.borderWidth&&(C.style.borderWidth=t.borderWidth,C.style.borderStyle="solid"),t.borderColor&&(C.style.borderColor=t.borderColor),t.paddingX?(C.style.paddingLeft=t.paddingX,C.style.paddingRight=t.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),t.paddingY?(C.style.paddingTop=t.paddingY,C.style.paddingBottom=t.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let I=null;u&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,x.appendChild(I)),C.setAttribute("aria-label",a),x.appendChild(C);let D="send";return{button:C,wrapper:x,setMode:le=>{if(le===D)return;D=le;let Ce=le==="stop"?i:a;if(C.setAttribute("aria-label",Ce),I&&(I.textContent=Ce),n){if(L&&B){let Be=le==="stop"?B:L;C.replaceChildren(Be)}}else C.textContent=le==="stop"?l:d}}},Fi=e=>{var I,D,F,H,v,w,M,A,E,O,U,j;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((D=t.provider)==null?void 0:D.type)==="runtype";if(!(o||r))return null;let a=(H=(F=e==null?void 0:e.sendButton)==null?void 0:F.size)!=null?H:"40px",i=b("div","persona-send-button-wrapper"),d=b("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=t.iconName)!=null?v:"mic",u=(w=t.iconSize)!=null?w:a,p=parseFloat(u)||24,f=(A=t.backgroundColor)!=null?A:(M=e==null?void 0:e.sendButton)==null?void 0:M.backgroundColor,g=(O=t.iconColor)!=null?O:(E=e==null?void 0:e.sendButton)==null?void 0:E.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",g?d.style.color=g:d.style.color="var(--persona-text, #111827)";let C=Ae(l,p,g||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let L=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((j=t.showTooltip)!=null?j:!1)&&L){let ge=b("div","persona-send-button-tooltip");ge.textContent=L,i.appendChild(ge)}return{button:d,wrapper:i}},Oi=e=>{var x,C,L,B,I,D,F,H;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(L=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?L:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((B=t.allowedTypes)!=null?B:$o).join(","),r.multiple=((I=t.maxFiles)!=null?I:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(D=t.buttonTooltipText)!=null?D:"Attach file");let i=(F=t.buttonIconName)!=null?F:"paperclip",d=n,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=Ae(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let f=(H=t.buttonTooltipText)!=null?H:"Attach file",g=b("div","persona-send-button-tooltip");return g.textContent=f,s.appendChild(g),{button:a,wrapper:s,input:r,previewsContainer:o}},Ni=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},_i=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Vi=e=>{var x,C,L,B,I,D;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=_i(),r=b("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");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=Hi(t);a();let i=Di(t),d=Fi(t),l=Oi(t),u=Ni(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let p=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),p.append(f,g),r.append(p),r.addEventListener("click",F=>{F.target!==i.button&&F.target!==i.wrapper&&F.target!==(d==null?void 0:d.button)&&F.target!==(d==null?void 0:d.wrapper)&&F.target!==(l==null?void 0:l.button)&&F.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:u,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(B=l==null?void 0:l.wrapper)!=null?B:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Cm=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Sm=e=>{var x,C,L,B,I,D;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=_i();o.style.display="none";let r=Ni(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Hi(t);s.style.maxHeight="100px",a();let i=Di(t),d=Fi(t),l=Oi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=b("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",F=>{F.target!==i.button&&F.target!==i.wrapper&&F.target!==(d==null?void 0:d.button)&&F.target!==(d==null?void 0:d.wrapper)&&F.target!==(l==null?void 0:l.button)&&F.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(p,s,f),l&&n.append(l.previewsContainer),n.append(u,o,r);let g=u;return{footer:n,suggestions:o,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:r,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(B=l==null?void 0:l.wrapper)!=null?B:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Am=e=>{var u,p,f,g,x,C,L,B,I,D,F,H,v,w,M,A,E;let t=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,n=mn(e);if(ca(e)){let O=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},U=b("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(x=O.expandedSize)!=null?x:"anchored",U.style.zIndex=String((L=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?L:yn);let j=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");j.style.width="100%",U.appendChild(j);let ge=b("div","persona-widget-pill-root");return ge.setAttribute("data-persona-composer-bar",""),ge.dataset.state="collapsed",ge.dataset.expandedSize=(B=O.expandedSize)!=null?B:"anchored",ge.style.zIndex=String((D=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?D:yn),{wrapper:U,panel:j,pillRoot:ge}}if(n){let O=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(U),{wrapper:O,panel:U}}if(!t){let O=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),j=(H=(F=e==null?void 0:e.launcher)==null?void 0:F.width)!=null?H:"100%";return O.style.width=j,U.style.width="100%",O.appendChild(U),{wrapper:O,panel:U}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&Co[r.position]?Co[r.position]:Co["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((M=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?M:yn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(E=(A=e==null?void 0:e.launcher)==null?void 0:A.width)!=null?E:e==null?void 0:e.launcherWidth,l=d!=null?d:lo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Hh=(e,t)=>{var F,H,v,w,M,A,E,O,U;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Pi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(H=(F=e==null?void 0:e.launcher)==null?void 0:F.clearChat)==null?void 0:H.enabled)!=null?v:!0,a=null,i=null;if(s){let j=Wi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,i=j.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(M=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?M:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(E=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",u.append(p,f);let g=b("div","persona-flex persona-flex-col persona-gap-3"),x=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;x&&(g.style.maxWidth=x,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let L=b("div","persona-composer-overlay persona-pointer-events-none");L.setAttribute("data-persona-composer-overlay",""),L.style.position="absolute",L.style.left="0",L.style.right="0",L.style.bottom="0",L.style.zIndex="20";let B=Sm({config:e}),{root:I,textNode:D}=Cm();return n.append(d,r,l,L),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:g,composerOverlay:L,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:p,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:I,peekTextNode:D}},Tm=(e,t=!0)=>{var L,B,I,D,F,H,v,w,M;if(ca(e))return Hh(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(L=e==null?void 0:e.layout)==null?void 0:L.header,r=((B=e==null?void 0:e.layout)==null?void 0:B.showHeader)!==!1,s=o?Bi(e,o,{showClose:t}):Lr({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=mn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(D=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?D:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(H=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",i.append(d,l);let u=b("div","persona-flex persona-flex-col persona-gap-3"),p=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((w=e==null?void 0:e.copy)==null?void 0:w.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=Vi({config:e}),x=((M=e==null?void 0:e.layout)==null?void 0:M.showFooter)!==!1;r?pa(n,s,e):(s.header.style.display="none",pa(n,s,e)),n.append(a);let C=b("div","persona-composer-overlay persona-pointer-events-none");return C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20",x||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:a,messagesWrapper:u,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Dh=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}},Fh=(e,t)=>{if(!e)return null;let n=Dh(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Oh=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Nh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},_l=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(":"))},Vl=320,Em=320,_h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Vh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),$h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Uh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),zh=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=b("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Vl}px`,l.style.maxHeight=`${Em}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;r+=1,l.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{u=!0}),Nh(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},qh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!_l(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!_l(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vl}px`,r.style.maxHeight=`${Em}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Kh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!_l(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===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 n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let 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 r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Gh=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let r=t(o);if(r!==null)return r}return ua()},Yh=(e,t)=>{let n=b("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 r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},km=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Xh=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Qh=(e,t,n)=>{var g,x,C,L,B,I;let o=(g=t.showCopy)!=null?g:!0,r=(x=t.showUpvote)!=null?x:!0,s=(C=t.showDownvote)!=null?C:!0;if(!o&&!r&&!s){let D=b("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let a=(L=t.visibility)!=null?L:"hover",i=(B=t.align)!=null?B:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(D,F,H)=>{let v=vn({icon:D,label:F,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",H),v};return o&&p.appendChild(f("copy","Copy message","copy")),r&&p.appendChild(f("thumbs-up","Upvote","upvote")),s&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},$l=(e,t,n,o,r,s)=>{var ee,Me,Q,Te,he,ce,me,Ke,K,re,Pe,nt,fe,de,Ve,Ie,pe;let a=n!=null?n:{},i=(ee=a.layout)!=null?ee:"bubble",d=a.avatar,l=a.timestamp,u=(Me=d==null?void 0:d.show)!=null?Me:!1,p=(Q=l==null?void 0:l.show)!=null?Q:!1,f=(Te=d==null?void 0:d.position)!=null?Te:"left",g=(he=l==null?void 0:l.position)!=null?he:"below",x=Xh(e.role,i),C=b("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 L=_h(e),B=(me=(ce=e.content)==null?void 0:ce.trim())!=null?me:"",D=L.length>0&&B===bi,F=Mi((K=(Ke=s==null?void 0:s.widgetConfig)==null?void 0:Ke.features)==null?void 0:K.streamAnimation),H=(nt=(Pe=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.features)==null?void 0:Pe.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&F.type!=="none"?sa(F.type,H):null,w=e.role==="assistant"&&((fe=v==null?void 0:v.isAnimating)==null?void 0:fe.call(v,e))===!0,M=e.role==="assistant"&&v!==null&&(!!e.streaming||w);M&&(v!=null&&v.bubbleClass)&&C.classList.add(v.bubbleClass);let A=document.createElement("div");A.classList.add("persona-message-content"),M&&v&&(v.containerClass&&A.classList.add(v.containerClass),A.style.setProperty("--persona-stream-step",`${F.speed}ms`),A.style.setProperty("--persona-stream-duration",`${F.duration}ms`));let E=M?Li((de=e.content)!=null?de:"",F.buffer,v,e,!!e.streaming):(Ve=e.content)!=null?Ve:"",O=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=O;M&&(v==null?void 0:v.wrap)==="char"?U=aa(O,"char",e.id,{skipTags:v.skipTags}):M&&(v==null?void 0:v.wrap)==="word"&&(U=aa(O,"word",e.id,{skipTags:v.skipTags}));let j=null;if(D?(j=document.createElement("div"),j.innerHTML=U,j.style.display="none",A.appendChild(j)):A.innerHTML=U,M&&(v!=null&&v.useCaret)&&!D&&B){let X=Ii(),$e=A.querySelectorAll(".persona-stream-char, .persona-stream-word"),St=$e[$e.length-1];if(St!=null&&St.parentNode)St.parentNode.insertBefore(X,St.nextSibling);else{let J=A.lastElementChild;J?J.appendChild(X):A.appendChild(X)}}if(p&&g==="inline"&&e.createdAt){let X=km(e,l);X.classList.add("persona-ml-2","persona-inline"),A.appendChild(X)}if(L.length>0){let X=zh(L,!D&&!!B,()=>{D&&j&&(j.style.display="")});X?C.appendChild(X):D&&j&&(j.style.display="")}let ge=Vh(e);if(ge.length>0){let X=qh(ge);X&&C.appendChild(X)}let se=$h(e);if(se.length>0){let X=jh(se);X&&C.appendChild(X)}let ye=Uh(e);if(ye.length>0){let X=Kh(ye);X&&C.appendChild(X)}if(C.appendChild(A),p&&g==="below"&&e.createdAt){let X=km(e,l);X.classList.add("persona-mt-1"),C.appendChild(X)}let le=e.role==="assistant"?Fh(e.stopReason,(pe=(Ie=s==null?void 0:s.widgetConfig)==null?void 0:Ie.copy)==null?void 0:pe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(E&&E.trim()),$e=F.placeholder==="skeleton",St=$e&&F.buffer==="line"&&X;if(X)St&&C.appendChild(ia());else if($e)C.appendChild(ia());else{let J=Gh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);J&&C.appendChild(J)}}if(le&&e.stopReason&&!e.streaming&&(B||(A.style.display="none"),C.appendChild(Oh(e.stopReason,le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=Qh(e,o,r);C.appendChild(X)}if(!u||e.role==="system")return C;let Be=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=Yh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Be.append(C,ve):Be.append(ve,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Be};var ts=new Set,Jh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Zh=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
24
+ `):""},Mm=(e,t)=>{let n=ts.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ae(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Ul=(e,t)=>{var se,ye,le,Ce,Be,ve,ee,Me,Q,Te,he;let n=e.reasoning,o=b("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),!n)return o;let r=(ye=(se=t==null?void 0:t.features)==null?void 0:se.reasoningDisplay)!=null?ye:{},s=r.expandable!==!1,a=s&&ts.has(e.id),i=n.status!=="complete",d=Zh(e,(le=r.previewMaxLines)!=null?le:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Ce=t==null?void 0:t.reasoning)!=null?Ce:{},x=String((Be=n.startedAt)!=null?Be:Date.now()),C=()=>{let ce=b("span","");return ce.setAttribute("data-tool-elapsed",x),ce.textContent=ui(n),ce},L=(ve=g.renderCollapsedSummary)==null?void 0:ve.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ui(n),createElapsedElement:C});typeof L=="string"&&L.trim()?(p.textContent=L,u.appendChild(p)):L instanceof HTMLElement?u.appendChild(L):(p.textContent=f,u.appendChild(p));let B=b("span","persona-text-xs persona-text-persona-primary");B.textContent=Qu(n),u.appendChild(B);let I=(ee=r.loadingAnimation)!=null?ee:"none",D=g.activeTextTemplate,F=g.completeTextTemplate,H=i?D:F,v=L instanceof HTMLElement,w=(ce,me,Ke)=>{let K=Ke;for(let re of me){let Pe=b("span","persona-tool-char");Pe.style.setProperty("--char-index",String(K)),Pe.textContent=re===" "?"\xA0":re,ce.appendChild(Pe),K++}return K},M=(ce,me)=>{p.textContent="";let Ke=mi(ce,""),K=0;for(let re of Ke){let Pe=re.styles.length>0?(()=>{let nt=b("span",re.styles.map(fe=>`persona-tool-text-${fe}`).join(" "));return p.appendChild(nt),nt})():p;if(re.isDuration&&i)Pe.appendChild(C());else{let nt=re.isDuration?ui(n):re.text;me?K=w(Pe,nt,K):Pe.appendChild(document.createTextNode(nt))}}};if(!v&&H)if(B.style.display="none",p.style.display="",i&&I!=="none"){let ce=(Me=g.loadingAnimationDuration)!=null?Me:2e3;p.setAttribute("data-preserve-animation","true"),I==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),M(H,!1)):(p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),M(H,!0))}else M(H,!1);else if(!v&&i&&I!=="none"){p.style.display="";let ce=(Q=g.loadingAnimationDuration)!=null?Q:2e3;if(p.setAttribute("data-preserve-animation","true"),I==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`);else{p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let me=p.textContent||f;p.textContent="",w(p,me,0)}n.status==="complete"&&(p.style.display="none")}else v||(n.status==="complete"?p.style.display="none":p.style.display="");let A=null;if(s){A=b("div","persona-flex persona-items-center");let me=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);me?A.appendChild(me):A.textContent=a?"Hide":"Show";let Ke=b("div","persona-flex persona-items-center persona-ml-auto");Ke.append(A),l.append(u,Ke)}else l.append(u);let E=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(E.setAttribute("data-persona-collapsed-preview","reasoning"),E.style.display="none",E.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let ce=(he=(Te=t==null?void 0:t.reasoning)==null?void 0:Te.renderCollapsedPreview)==null?void 0:he.call(Te,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Jh(E,ce)||(E.textContent=d),E.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,E),o;let O=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let U=n.chunks.join(""),j=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return j.textContent=U||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(j),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),A){A.innerHTML="";let me=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);me?A.appendChild(me):A.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",E.style.display=a?"none":E.textContent||E.childNodes.length?"":"none"})(),o.append(l,E,O),o};var ns=new Set,eb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),tb=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let o=((s=n.chunks)!=null?s:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
25
  `);let r=Zr(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Zh=(e,t)=>{var u,p,g,m,w;let n=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,r=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",s=Jh(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Xu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return r==="tool-name"?l=((w=n.name)==null?void 0:w.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Il(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Il(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Em=(e,t,n)=>{var u;let o=ns.has(e),r=(u=n==null?void 0:n.toolCall)!=null?u:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"currentColor",g=Ae(o?"chevron-up":"chevron-down",16,p,2);g?l.appendChild(g):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},zl=(e,t)=>{var U,j,fe,se,ye,le,Ce,Be,ve;let n=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},r=b("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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),!n)return r;let s=(fe=(j=t==null?void 0:t.features)==null?void 0:j.toolCallDisplay)!=null?fe:{},a=s.expandable!==!1,i=a&&ns.has(e.id),{summary:d,previewText:l,isActive:u}=Zh(e,t),p=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(p.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(p.style.paddingLeft=o.headerPaddingX,p.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(p.style.paddingTop=o.headerPaddingY,p.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let w=String((se=n.startedAt)!=null?se:Date.now()),x=()=>{let ee=b("span","");return ee.setAttribute("data-tool-elapsed",w),ee.textContent=Xs(n),ee},L=(le=o.renderCollapsedSummary)==null?void 0:le.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ye=s.collapsedMode)!=null?ye:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Xs(n),createElapsedElement:x});typeof L=="string"&&L.trim()?(m.textContent=L,g.appendChild(m)):L instanceof HTMLElement?g.appendChild(L):(m.textContent=d,g.appendChild(m));let W=(Ce=s.loadingAnimation)!=null?Ce:"none",B=o.activeTextTemplate,D=o.completeTextTemplate,V=u?B:D,H=L instanceof HTMLElement,v=(ee,Me,Q)=>{let Te=Q;for(let he of Me){let ce=b("span","persona-tool-char");ce.style.setProperty("--char-index",String(Te)),ce.textContent=he===" "?"\xA0":he,ee.appendChild(ce),Te++}return Te},C=(ee,Me)=>{var ce;m.textContent="";let Q=((ce=n.name)==null?void 0:ce.trim())||"tool",Te=mi(ee,Q),he=0;for(let me of Te){let Ke=me.styles.length>0?(()=>{let K=b("span",me.styles.map(re=>`persona-tool-text-${re}`).join(" "));return m.appendChild(K),K})():m;if(me.isDuration&&u)Ke.appendChild(x());else{let K=me.isDuration?Xs(n):me.text;Me?he=v(Ke,K,he):Ke.appendChild(document.createTextNode(K))}}};if(!H)if(u&&W!=="none"){let ee=(Be=o.loadingAnimationDuration)!=null?Be:2e3;if(m.setAttribute("data-preserve-animation","true"),W==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),V&&C(V,!1);else if(m.classList.add(`persona-tool-loading-${W}`),m.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),W==="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)),V)C(V,!0);else{let Me=m.textContent||d;m.textContent="",v(m,Me,0)}}else V&&C(V,!1);let M=null;if(a){M=b("div","persona-flex persona-items-center");let ee=o.toggleTextColor||o.headerTextColor||"currentColor",Me=Ae(i?"chevron-up":"chevron-down",16,ee,2);Me?M.appendChild(Me):M.textContent=i?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(M),p.append(g,Q)}else p.append(g);let A=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(A.setAttribute("data-persona-collapsed-preview","tool"),A.style.display="none",A.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let ee=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});Qh(A,ee)||(A.textContent=l),A.style.display=""}if(!i&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,A),r;let E=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(E.style.display=i?"":"none",o.contentBackgroundColor&&(E.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(E.style.color=o.contentTextColor),o.contentPaddingX&&(E.style.paddingLeft=o.contentPaddingX,E.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(E.style.paddingTop=o.contentPaddingY,E.style.paddingBottom=o.contentPaddingY),n.name){let ee=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ee.style.color=o.contentTextColor:o.headerTextColor&&(ee.style.color=o.headerTextColor),ee.textContent=n.name,E.appendChild(ee)}if(n.args!==void 0){let ee=b("div","persona-space-y-1"),Me=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Me.style.color=o.labelTextColor),Me.textContent="Arguments";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Q.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Q.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Q.style.color=o.codeBlockTextColor),Q.textContent=Zr(n.args),ee.append(Me,Q),E.appendChild(ee)}if(n.chunks&&n.chunks.length){let ee=b("div","persona-space-y-1"),Me=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Me.style.color=o.labelTextColor),Me.textContent="Activity";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Q.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Q.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Q.style.color=o.codeBlockTextColor),Q.textContent=n.chunks.join(""),ee.append(Me,Q),E.appendChild(ee)}if(n.status==="complete"&&n.result!==void 0){let ee=b("div","persona-space-y-1"),Me=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Me.style.color=o.labelTextColor),Me.textContent="Result";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Q.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Q.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Q.style.color=o.codeBlockTextColor),Q.textContent=Zr(n.result),ee.append(Me,Q),E.appendChild(ee)}if(n.status==="complete"&&typeof n.duration=="number"){let ee=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ee.style.color=o.contentTextColor),ee.textContent=`Duration: ${n.duration}ms`,E.appendChild(ee)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),M){M.innerHTML="";let ee=o.toggleTextColor||o.headerTextColor||"currentColor",Me=Ae(i?"chevron-up":"chevron-down",16,ee,2);Me?M.appendChild(Me):M.textContent=i?"Hide":"Show"}E.style.display=i?"":"none",A.style.display=i?"none":A.textContent||A.childNodes.length?"":"none"})(),r.append(p,A,E),r};var ar=require("partial-json");var eb="ask_user_question",ql=8,os="data-persona-ask-sheet-for",tb="Other",nb="Other\u2026",Lm="Type your own answer here",Im="Send",ob="Next",rb="Back",sb="Submit all",ab="Skip",ib=3,jl="data-ask-current-index",Kl="data-ask-question-count",Rm="data-ask-answers",Gl="data-ask-grouped",Pm="data-ask-layout",lb=e=>e.layout==="pills"?"pills":"rows",cb=e=>e.getAttribute(Pm)==="pills"?"pills":"rows",Mm=!1,Wm=e=>e.replace(/["\\]/g,"\\$&"),Ir=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===eb,Yl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},rs=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ar.parse)(r,ar.STR|ar.OBJ|ar.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ma=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ql&&!Mm&&(Mm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ql}.`)),t.slice(0,ql)},db=e=>{var t;return(t=ma(e)[0])!=null?t:null},pb=(e,t)=>{var n;return(n=ma(e)[t])!=null?n:null},ub=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Bm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},mb=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Bm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},fb=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},gb=(e,t,n,o)=>{var u,p,g;let s=b("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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<ib;m++)s.appendChild(fb(o));return s}if(d.forEach((m,w)=>{s.appendChild(mb(m,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?tb:nb;if(o==="rows"){let w=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let x=b("span","persona-ask-row-content"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(u=t.freeTextPlaceholder)!=null?u:Lm,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:m),x.appendChild(L),w.appendChild(x);let W=Bm(o,a,d.length);W&&w.appendChild(W),s.appendChild(w)}else{let w=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(g=t.freeTextLabel)!=null?g:m,s.appendChild(w)}}return s},Hm=(e,t)=>{var s,a;let o=b("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 r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:Lm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Im,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},hb=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:Im,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},bb=(e,t,n)=>{var l,u,p,g;let o=b("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 r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:rb,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:ab,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:sb:(g=n.nextLabel)!=null?g:ob,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Rr=e=>{let t=e.getAttribute(Rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Dm=(e,t)=>{e.setAttribute(Rm,JSON.stringify(t))},co=e=>{var n;let t=Number((n=e.getAttribute(jl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},yb=(e,t)=>{e.setAttribute(jl,String(Math.max(0,Math.floor(t))))},ss=e=>{var n;let t=Number((n=e.getAttribute(Kl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ir=e=>e.getAttribute(Gl)==="true",vb=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},xb=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},$i=(e,t)=>{let{payload:n}=rs(t),o=ma(n),r=Rr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},Fm=e=>{let t=Rr(e),n=co(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=r.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.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=""},Om=e=>{if(!ir(e))return;let t=Rr(e),n=co(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Xl=(e,t,n)=>{let o=Yl(n),r=cb(e),{payload:s,complete:a}=rs(t),i=ir(e),d=co(e),l=ss(e),u=i?pb(s,d):db(s),p=!!(u!=null&&u.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let B=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=B,w.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let B=gb(u,o,a,r);x.replaceWith(B)}if(r!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(Hm(o,r))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!L?e.appendChild(hb(o)):(!p||i)&&L&&L.remove(),e.setAttribute("data-multi-select",p?"true":"false");let W=e.querySelector('[data-ask-nav-row="true"]');if(i){let B=bb(d,l,o);W?W.replaceWith(B):e.appendChild(B)}else W&&W.remove();Fm(e),Om(e)},wb=(e,t,n)=>{let o=Yl(t),r=lb(o),s=e.toolCall.id,a=ma(n),i=Math.max(1,a.length),d=i>1,l=vb(e,a),u=d?xb(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(os,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Kl,String(i)),p.setAttribute(jl,String(u)),p.setAttribute(Gl,d?"true":"false"),p.setAttribute(Pm,r),Dm(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),ub(p,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",g.appendChild(w),p.appendChild(g);let L=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),p.appendChild(L),r!=="rows"&&p.appendChild(Hm(o,r)),Xl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Cb=(e,t,n)=>{let{payload:o}=rs(t),r=Math.max(1,ma(o).length);r>ss(e)&&(e.setAttribute(Kl,String(r)),r>1&&!ir(e)&&e.setAttribute(Gl,"true")),Xl(e,t,n)};var Ui=(e,t,n)=>{if(!n||!Ir(e)||Yl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${os}]`).forEach(l=>{l.getAttribute(os)!==r&&l.remove()});let a=n.querySelector(`[${os}="${Wm(r)}"]`);if(a){Cb(a,e,t);return}let{payload:i}=rs(e),d=wb(e,t,i);n.appendChild(d)},as=(e,t)=>{if(!e)return;let n=t?`[${os}="${Wm(t)}"]`:`[${os}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ql=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),lr=(e,t)=>{let n=Rr(e),o=co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Dm(e,n),Fm(e),Om(e)},zi=(e,t,n,o)=>{let r=ss(e),s=Math.max(0,Math.min(r-1,o));yb(e,s),Xl(e,t,n)};var Jl=(e,t)=>{var x,L,W,B,D,V,H,v,C,M,A,E;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(x=o==null?void 0:o.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(L=o==null?void 0:o.borderColor)!=null?L:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(W=o==null?void 0:o.titleColor)!=null?W:"currentColor",u=Ae(d,20,l,2);u&&i.appendChild(u);let p=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(B=o==null?void 0:o.title)!=null?B:"Approval Required",g.appendChild(m),!r){let F=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",n.status),n.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):n.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):n.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),g.appendChild(F)}p.appendChild(g);let w=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(w.style.color=o.descriptionColor),w.textContent=n.description,p.appendChild(w),n.parameters){let F=b("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&&(F.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(F.style.color=o.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=Zr(n.parameters),p.appendChild(F)}if(r){let F=b("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let U=b("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");U.type="button",U.style.backgroundColor=(D=o==null?void 0:o.approveButtonColor)!=null?D:"var(--persona-approval-approve-bg, #22c55e)",U.style.color=(V=o==null?void 0:o.approveButtonTextColor)!=null?V:"#ffffff",U.setAttribute("data-approval-action","approve");let j=Ae("shield-check",14,(H=o==null?void 0:o.approveButtonTextColor)!=null?H:"#ffffff",2);j&&(j.style.marginRight="4px",U.appendChild(j));let fe=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");U.appendChild(fe);let se=b("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");se.type="button",se.style.backgroundColor=(C=o==null?void 0:o.denyButtonColor)!=null?C:"transparent",se.style.color=(M=o==null?void 0:o.denyButtonTextColor)!=null?M:"var(--persona-feedback-error, #dc2626)",se.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,se.setAttribute("data-approval-action","deny");let ye=Ae("shield-x",14,(A=o==null?void 0:o.denyButtonTextColor)!=null?A:"var(--persona-feedback-error, #dc2626)",2);ye&&(ye.style.marginRight="4px",se.appendChild(ye));let le=document.createTextNode((E=o==null?void 0:o.denyLabel)!=null?E:"Deny");se.appendChild(le),F.append(U,se),p.appendChild(F)}return a.append(i,p),s.appendChild(a),s};var Nm=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=r?r.isStreaming():!1,g=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(m=>{let w=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=m,w.disabled=p,i!=null&&i.fontFamily&&(w.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(m))}),u.appendChild(w),t.push(w)}),e.appendChild(u)}}};var fa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)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,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ga=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}};var Sb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ab=new Set(["step_start","execution_start"]),Tb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),kb=new Set(["step_complete","agent_turn_complete"]),Eb=new Set(["flow_complete","agent_complete"]),_m=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),$m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pr=(e,t)=>{let n=e[t];return $m(n)?n:void 0};function Zl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function qi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Mb(e,t){return typeof t.type=="string"?t.type:e}function Lb(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 Ib(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Vm(e){var o,r,s,a,i;let t=Pr(e,"result"),n=[Pr(e,"tokens"),Pr(e,"totalTokens"),t?Pr(t,"tokens"):void 0,Pr(e,"usage"),t?Pr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Jn(d.output))!=null?o:Jn(d.outputTokens))!=null?r:Jn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Jn(e.outputTokens))!=null?s:Jn(e.completionTokens))!=null?i:t?(a=Jn(t.outputTokens))!=null?a:Jn(t.completionTokens):void 0}function Rb(e){var n,o,r,s,a;let t=Pr(e,"result");return(a=(r=(o=(n=Jn(e.executionTime))!=null?n:Jn(e.executionTimeMs))!=null?o:Jn(e.execution_time))!=null?r:Jn(e.duration))!=null?a:t?(s=Jn(t.executionTime))!=null?s:Jn(t.executionTimeMs):void 0}function Pb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ha=class{constructor(t=Pb){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:qi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!$m(n)){_m.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Mb(t,n),r=this.now();if(Sb.has(o)){this.startRun(r);return}if(Ab.has(o)){this.run||this.startRun(r);return}if(Tb.has(o)){if(!Ib(o,n))return;let a=Lb(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Zl(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:qi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(kb.has(o)){if(!this.run)return;let a=this.run,i=Vm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Zl(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:qi(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Eb.has(o)){if(!this.run)return;let a=this.run,i=Vm(n),d=i!=null?i:a.exactOutputTokens+Zl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:qi(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(_m.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Rb(n);return s!=null?s:o-t.startedAt}};function is(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Wb={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)"}},Bb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Hb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Db=100;function Fb(e,t){let n={...Wb,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Bb}function Ob(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Nb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function _b(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Vb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{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),n()})}function $b(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 Ub(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function zb(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 qb(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("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=b("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 ec(e,t,n,o,r,s,a,i){var g;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");is(l,(g=o.classNames)==null?void 0:g.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var U,j;let m=b("div",""),w=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");w.setAttribute("data-event-id",e.id);let x=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),L=Ae(d?"chevron-down":"chevron-right","14px","currentColor",2);L&&x.appendChild(L);let W=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=(U=o.timestampFormat)!=null?U:"relative";W.textContent=B==="relative"?Ob(e.timestamp,n):Nb(e.timestamp);let D=null;o.showSequenceNumbers!==!1&&(D=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(t+1));let V=Fb(e.type,o.badgeColors),H=b("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");H.style.backgroundColor=V.bg,H.style.color=V.text,H.style.borderColor=V.text+"50",H.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Hb,C=_b(e.payload,v),M=null;C&&(M=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),M.textContent=C);let A=b("div","persona-flex-1 persona-min-w-0"),E=b("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"),F=Ae("clipboard","12px","currentColor",1.5);return F&&E.appendChild(F),E.addEventListener("click",async fe=>{fe.stopPropagation(),await Vb($b(e)),E.innerHTML="";let se=Ae("check","12px","currentColor",1.5);se&&E.appendChild(se),setTimeout(()=>{E.innerHTML="";let ye=Ae("clipboard","12px","currentColor",1.5);ye&&E.appendChild(ye)},1500)}),w.appendChild(x),w.appendChild(W),D&&w.appendChild(D),w.appendChild(H),M&&w.appendChild(M),w.appendChild(A),w.appendChild(E),m.appendChild(w),d&&m.appendChild(qb(e,a,i)),m}}function Um(e){var w,x,L,W,B;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(w=r==null?void 0:r.features)==null?void 0:w.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",u=(L=i==null?void 0:i.label)!=null?L:"",p=(B=(W=r==null?void 0:r.features)==null?void 0:W.eventStream)!=null?B:{},g=s.find(D=>D.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let D=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(D)return{element:D,update:()=>{},destroy:()=>{}}}return m();function m(){let D=p.classNames,V=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");is(V,D==null?void 0:D.panel);let H=[],v="",C="",M=null,A=[],E={},F=0,U=Ti(),j=0,fe=0,se=!1,ye=null,le=!1,Ce=0,Be=new Set,ve=new Map,ee="",Me="",Q=null,Te,he,ce,me,Ke,K=null,re=null,Pe=null;function nt(){let ie=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),xe=b("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");is(xe,D==null?void 0:D.headerBar);let Ct=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ct.textContent="Events",Te=b("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"),Te.textContent="0",a){re=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),re.style.cursor="help";let On=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");On.textContent="Throughput",K=b("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"),K.textContent="-- tok/s",Pe=b("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"),Pe.style.display="none",Pe.style.pointerEvents="none";let eo=re,wn=Pe,Nn=()=>{if(!wn.textContent)return;let So=eo.getBoundingClientRect(),_n=ie.getBoundingClientRect();wn.style.left=`${So.left-_n.left}px`,wn.style.top=`${So.bottom-_n.top+4}px`,wn.style.display="block"},mt=()=>{wn.style.display="none"};re.addEventListener("mouseenter",Nn),re.addEventListener("mouseleave",mt),re.appendChild(On),re.appendChild(K)}let Vt=b("div","persona-flex-1");he=b("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=b("option","");Zt.value="",Zt.textContent="All events",he.appendChild(Zt),ce=b("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"),ce.type="button",ce.title="Copy All";let Mt=Ae("clipboard-copy","12px","currentColor",1.5);Mt&&ce.appendChild(Mt);let Tt=b("span","persona-text-xs");Tt.textContent="Copy All",ce.appendChild(Tt),xe.appendChild(Ct),xe.appendChild(Te),re&&xe.appendChild(re),xe.appendChild(Vt),xe.appendChild(he),xe.appendChild(ce);let bt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");is(bt,D==null?void 0:D.searchBar);let vt=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");vt&&zt.appendChild(vt),me=b("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"),is(me,D==null?void 0:D.searchInput),me.type="text",me.placeholder="Search event payloads...",Ke=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ke.type="button",Ke.style.display="none";let et=Ae("x","12px","currentColor",2);return et&&Ke.appendChild(et),bt.appendChild(zt),bt.appendChild(me),bt.appendChild(Ke),ie.appendChild(xe),ie.appendChild(bt),Pe&&ie.appendChild(Pe),ie}let ge,de=s.find(ie=>ie.renderEventStreamToolbar);if(de!=null&&de.renderEventStreamToolbar&&r){let ie=de.renderEventStreamToolbar({config:r,defaultRenderer:()=>nt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:xe=>{v=xe,Fn(),ae()},onSearchChange:xe=>{C=xe,Fn(),ae()}});ge=ie!=null?ie:nt()}else ge=nt();let Ve=b("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");Ve.style.display="none";function Ie(){if(!a||!K||!re)return;let ie=a();K.textContent=Ub(ie);let xe=zb(ie);Pe&&(Pe.textContent=xe,xe||(Pe.style.display="none")),xe?re.setAttribute("aria-label",xe):re.removeAttribute("aria-label")}let pe=b("div","persona-flex-1 persona-min-h-0 persona-relative"),X=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let $e=b("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");is($e,D==null?void 0:D.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let St=Ae(l,"14px","currentColor",2);St&&$e.appendChild(St);let J=b("span","");J.textContent=u,$e.appendChild(J);let Oe=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Oe.style.display="none",pe.appendChild(X),pe.appendChild(Oe),pe.appendChild($e),V.setAttribute("tabindex","0"),V.appendChild(ge),V.appendChild(Ve),V.appendChild(pe);function In(){let ie=t.getAll(),xe={};for(let Tt of ie)xe[Tt.type]=(xe[Tt.type]||0)+1;let Ct=Object.keys(xe).sort(),Vt=Ct.length!==A.length||!Ct.every((Tt,bt)=>Tt===A[bt]),Zt=!Vt&&Ct.some(Tt=>xe[Tt]!==E[Tt]),xn=ie.length!==Object.values(E).reduce((Tt,bt)=>Tt+bt,0);if(!Vt&&!Zt&&!xn||(A=Ct,E=xe,!he))return;let Mt=he.value;if(he.options[0].textContent="All events",Vt){for(;he.options.length>1;)he.remove(1);for(let Tt of Ct){let bt=b("option","");bt.value=Tt,bt.textContent=`${Tt} (${xe[Tt]||0})`,he.appendChild(bt)}Mt&&Ct.includes(Mt)?he.value=Mt:Mt&&(he.value="",v="")}else for(let Tt=1;Tt<he.options.length;Tt++){let bt=he.options[Tt];bt.textContent=`${bt.value} (${xe[bt.value]||0})`}}function Ot(){let ie=t.getAll();if(v&&(ie=ie.filter(xe=>xe.type===v)),C){let xe=C.toLowerCase();ie=ie.filter(Ct=>Ct.type.toLowerCase().includes(xe)||Ct.payload.toLowerCase().includes(xe))}return ie}function cn(){return v!==""||C!==""}function Fn(){F=0,j=0,U.resume(),$e.style.display="none"}function Zn(ie){Be.has(ie)?Be.delete(ie):Be.add(ie),Q=ie;let xe=X.scrollTop,Ct=U.isFollowing();le=!0,U.pause(),ae(),X.scrollTop=xe,Ct&&U.resume(),le=!1}function N(){return oa(X,50)}function ae(){fe=Date.now(),se=!1,Ie(),In();let ie=t.getEvictedCount();ie>0?(Ve.textContent=`${ie.toLocaleString()} older events truncated`,Ve.style.display=""):Ve.style.display="none",H=Ot();let xe=H.length,Ct=t.getSize()>0;Te&&(Te.textContent=String(t.getSize())),xe===0&&Ct&&cn()?(Oe.textContent=C?`No events matching '${C}'`:"No events matching filter",Oe.style.display="",X.style.display="none"):(Oe.style.display="none",X.style.display=""),ce&&(ce.title=cn()?`Copy Filtered (${xe})`:"Copy All"),d&&!U.isFollowing()&&xe>F&&(j+=xe-F,J.textContent=u?`${u}${j>0?` (${j})`:""}`:"",$e.style.display=""),F=xe;let Vt=t.getAll(),Zt=Vt.length>0?Vt[0].timestamp:0,xn=new Set(H.map(bt=>bt.id));for(let bt of Be)xn.has(bt)||Be.delete(bt);let Mt=v!==ee||C!==Me,Tt=ve.size===0&&H.length>0;if(Mt||Tt||H.length===0){X.innerHTML="",ve.clear();let bt=document.createDocumentFragment();for(let vt=0;vt<H.length;vt++){let zt=ec(H[vt],vt,Zt,p,Be,Zn,s,r);ve.set(H[vt].id,zt),bt.appendChild(zt)}X.appendChild(bt),ee=v,Me=C,Q=null}else{if(Q!==null){let vt=ve.get(Q);if(vt&&vt.parentNode===X){let zt=H.findIndex(et=>et.id===Q);if(zt>=0){let et=ec(H[zt],zt,Zt,p,Be,Zn,s,r);X.insertBefore(et,vt),vt.remove(),ve.set(Q,et)}}Q=null}let bt=new Set(H.map(vt=>vt.id));for(let[vt,zt]of ve)bt.has(vt)||(zt.remove(),ve.delete(vt));for(let vt=0;vt<H.length;vt++){let zt=H[vt];if(!ve.has(zt.id)){let et=ec(zt,vt,Zt,p,Be,Zn,s,r);ve.set(zt.id,et),X.appendChild(et)}}}U.isFollowing()&&(X.scrollTop=X.scrollHeight)}function De(){if(Date.now()-fe>=Db){ye!==null&&(cancelAnimationFrame(ye),ye=null),ae();return}se||(se=!0,ye=requestAnimationFrame(()=>{ye=null,ae()}))}let Qe=(ie,xe)=>{if(!ce)return;ce.innerHTML="";let Ct=Ae(ie,"12px","currentColor",1.5);Ct&&ce.appendChild(Ct);let Vt=b("span","persona-text-xs");Vt.textContent="Copy All",ce.appendChild(Vt),setTimeout(()=>{ce.innerHTML="";let Zt=Ae("clipboard-copy","12px","currentColor",1.5);Zt&&ce.appendChild(Zt);let xn=b("span","persona-text-xs");xn.textContent="Copy All",ce.appendChild(xn),ce.disabled=!1},xe)},Ne=async()=>{if(ce){ce.disabled=!0;try{let ie;cn()?ie=H:n?(ie=await n(),ie.length===0&&(ie=t.getAll())):ie=t.getAll();let xe=ie.map(Ct=>{try{return JSON.parse(Ct.payload)}catch{return Ct.payload}});await navigator.clipboard.writeText(JSON.stringify(xe,null,2)),Qe("check",1500)}catch{Qe("x",1500)}}},_e=()=>{he&&(v=he.value,Fn(),ae())},rt=()=>{!me||!Ke||(Ke.style.display=me.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{C=me.value,Fn(),ae()},150))},At=()=>{!me||!Ke||(me.value="",C="",Ke.style.display="none",M&&clearTimeout(M),Fn(),ae())},_t=()=>{if(le)return;let ie=X.scrollTop,{action:xe,nextLastScrollTop:Ct}=ki({following:U.isFollowing(),currentScrollTop:ie,lastScrollTop:Ce,nearBottom:N(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ce=Ct,xe==="resume"?(U.resume(),j=0,$e.style.display="none"):xe==="pause"&&(U.pause(),d&&(J.textContent=u,$e.style.display=""))},Kt=ie=>{let xe=Ei({following:U.isFollowing(),deltaY:ie.deltaY,nearBottom:N(),resumeWhenNearBottom:!0});xe==="pause"?(U.pause(),d&&(J.textContent=u,$e.style.display="")):xe==="resume"&&(U.resume(),j=0,$e.style.display="none")},G=()=>{d&&(X.scrollTop=X.scrollHeight,U.resume(),j=0,$e.style.display="none")},gt=ie=>{let xe=ie.target;if(!xe||xe.closest("button"))return;let Ct=xe.closest("[data-event-id]");if(!Ct)return;let Vt=Ct.getAttribute("data-event-id");Vt&&Zn(Vt)},ot=ie=>{if((ie.metaKey||ie.ctrlKey)&&ie.key==="f"){ie.preventDefault(),me==null||me.focus(),me==null||me.select();return}ie.key==="Escape"&&(me&&document.activeElement===me?(At(),me.blur(),V.focus()):o&&o())};ce&&ce.addEventListener("click",Ne),he&&he.addEventListener("change",_e),me&&me.addEventListener("input",rt),Ke&&Ke.addEventListener("click",At),X.addEventListener("scroll",_t),X.addEventListener("wheel",Kt,{passive:!0}),X.addEventListener("click",gt),$e.addEventListener("click",G),V.addEventListener("keydown",ot);function Ut(){M&&clearTimeout(M),ye!==null&&(cancelAnimationFrame(ye),ye=null),se=!1,ve.clear(),ce&&ce.removeEventListener("click",Ne),he&&he.removeEventListener("change",_e),me&&me.removeEventListener("input",rt),Ke&&Ke.removeEventListener("click",At),X.removeEventListener("scroll",_t),X.removeEventListener("wheel",Kt),X.removeEventListener("click",gt),$e.removeEventListener("click",G),V.removeEventListener("keydown",ot)}return{element:V,update:De,destroy:Ut}}}function zm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),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=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(g);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(l.append(u,p),i.append(d,l),r==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var qm=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>zm(e,t)});if(u)return u}return zm(e,t)};var tc=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Wr=new tc;Wr.register("PersonaArtifactCard",qm);function jb(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function jm(e,t){var he,ce,me,Ke;let n=(ce=(he=e.features)==null?void 0:he.artifacts)==null?void 0:ce.layout,r=((me=n==null?void 0:n.toolbarPreset)!=null?me:"default")==="document",s=(Ke=n==null?void 0:n.panePadding)==null?void 0:Ke.trim(),a=e.markdown?ii(e.markdown):null,i=li(e.sanitize),d=K=>{let re=a?a(K):Gs(K);return i?i(re):re},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=t.onDismiss)==null||K.call(t)});let p=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),r&&p.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&g.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let w=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var K;u(),(K=t.onDismiss)==null||K.call(t)});let x="rendered",L=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),W=r?vn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):vn({icon:"eye",label:"Rendered view"}),B=r?vn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):vn({icon:"code-2",label:"Source"}),D=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),V=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,H=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,C=!!(H&&v&&v.length>0),M=null,A,E=null,F=null;if(r&&(V||H)&&!C){if(A=V?Nl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H){let K=Ae("chevron-down",14,"currentColor",2);K&&A.appendChild(K)}}else r&&C?(M=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),A=V?Nl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=vn({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"}}),M.append(A,E)):r?A=vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):A=vn({icon:"copy",label:"Copy"});let U=r?vn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vn({icon:"refresh-cw",label:"Refresh"}),j=r?vn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):vn({icon:"x",label:"Close"}),fe=()=>{var ge,de,Ve;let K=(ge=ve.find(Ie=>Ie.id===ee))!=null?ge:ve[ve.length-1],re=(de=K==null?void 0:K.id)!=null?de:null,Pe=(K==null?void 0:K.artifactType)==="markdown"&&(Ve=K.markdown)!=null?Ve:"",nt=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Pe,jsonPayload:nt,id:re}},se=async()=>{var ge;let{markdown:K,jsonPayload:re}=fe(),Pe=(ge=ve.find(de=>de.id===ee))!=null?ge:ve[ve.length-1],nt=(Pe==null?void 0:Pe.artifactType)==="markdown"?K:Pe?re:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(A.addEventListener("click",async()=>{let K=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(K&&C){let{markdown:re,jsonPayload:Pe,id:nt}=fe();try{await K({actionId:"primary",artifactId:nt,markdown:re,jsonPayload:Pe})}catch{}return}await se()}),E&&(v!=null&&v.length)){let K=()=>{var Pe;return(Pe=p.closest("[data-persona-root]"))!=null?Pe:document.body},re=()=>{F=es({items:v.map(Pe=>({id:Pe.id,label:Pe.label})),onSelect:async Pe=>{let{markdown:nt,jsonPayload:ge,id:de}=fe(),Ve=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ve?await Ve({actionId:Pe,artifactId:de,markdown:nt,jsonPayload:ge}):Pe==="markdown"||Pe==="md"?await navigator.clipboard.writeText(nt):Pe==="json"||Pe==="source"?await navigator.clipboard.writeText(ge):await navigator.clipboard.writeText(nt||ge)}catch{}},anchor:M!=null?M:E,position:"bottom-right",portal:K()})};p.isConnected?re():requestAnimationFrame(re),E.addEventListener("click",Pe=>{Pe.stopPropagation(),F==null||F.toggle()})}U.addEventListener("click",async()=>{var K;try{await((K=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:K.call(n))}catch{}Q()}),j.addEventListener("click",()=>{var K;u(),(K=t.onDismiss)==null||K.call(t)});let ye=()=>{r&&(W.setAttribute("aria-pressed",x==="rendered"?"true":"false"),B.setAttribute("aria-pressed",x==="source"?"true":"false"))};W.addEventListener("click",()=>{x="rendered",ye(),Q()}),B.addEventListener("click",()=>{x="source",ye(),Q()});let le=b("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");r?(g.replaceChildren(),L.append(W,B),M?D.append(M,U,j):D.append(A,U,j),g.append(L,le,D),ye()):(g.appendChild(m),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Ce=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Be=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ce.style.paddingLeft=s,Ce.style.paddingRight=s,Be.style.padding=s),p.appendChild(g),p.appendChild(Ce),p.appendChild(Be);let ve=[],ee=null,Me=!1,Q=()=>{var nt,ge,de,Ve;let K=r&&ve.length<=1;Ce.classList.toggle("persona-hidden",K),Ce.replaceChildren();for(let Ie of ve){let pe=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");pe.type="button",pe.textContent=Ie.title||Ie.id.slice(0,8),Ie.id===ee&&pe.classList.add("persona-bg-persona-container","persona-border-persona-border"),pe.addEventListener("click",()=>t.onSelect(Ie.id)),Ce.appendChild(pe)}Be.replaceChildren();let re=ee&&ve.find(Ie=>Ie.id===ee)||ve[ve.length-1];if(!re)return;if(r){let Ie=re.artifactType==="markdown"?"MD":(nt=re.component)!=null?nt:"Component",X=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${X} \xB7 ${Ie}`}else m.textContent="Artifacts";if(re.artifactType==="markdown"){if(r&&x==="source"){let pe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");pe.textContent=(ge=re.markdown)!=null?ge:"",Be.appendChild(pe);return}let Ie=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ie.innerHTML=d((de=re.markdown)!=null?de:""),Be.appendChild(Ie);return}let Pe=re.component?Wr.get(re.component):void 0;if(Pe){let pe={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=Pe((Ve=re.props)!=null?Ve:{},pe);if(X){Be.appendChild(X);return}}catch{}}Be.appendChild(jb(re))},Te=()=>{var re;let K=ve.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Pe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,ge=((re=Pe==null?void 0:Pe.classList.contains("persona-artifact-narrow-host"))!=null?re:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&ge&&Me?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var re,Pe,nt;ve=K.artifacts,ee=(nt=(Pe=K.selectedId)!=null?Pe:(re=K.artifacts[K.artifacts.length-1])==null?void 0:re.id)!=null?nt:null,ve.length>0&&(Me=!0),Q(),Te()},setMobileOpen(K){Me=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):Te()}}}function po(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Km(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!po(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Kb(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 ji(e,t){var d,l,u,p,g,m,w,x,L,W;if(!po(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"),Kb(e),Km(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(w=n==null?void 0:n.panePadding)==null?void 0:w.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(L=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:L.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(W=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:W.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Km(e,t)}var Gm=["panel","seamless"];function Ki(e,t){var i,d,l,u,p,g;for(let m of Gm)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!po(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=Gm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Ym(e,t){var n,o,r;return!t||!po(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function Gb(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Yb(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 Xb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Qb(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Xm(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Qm(e,t,n,o,r,s){let a=Gb(r,200),i=Qb(t,n,o,200);i=Math.max(a,i);let d=Yb(s);return d!==null&&(i=Math.min(i,d)),Xb(e,a,i)}var Jm={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"}},nc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,x,L;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(x=Jm[a])!=null?x:Jm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let W=b("p","persona-text-sm persona-text-persona-muted");W.textContent=i.description,d.appendChild(W)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(W=>{var v,C;let B=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${t.id}-${a}-${W.name}`;let D=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=W.label,B.appendChild(D);let V=(v=W.type)!=null?v:"text",H;V==="textarea"?(H=document.createElement("textarea"),H.rows=3):(H=document.createElement("input"),H.type=V),H.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",H.id=`${t.id}-${a}-${W.name}`,H.name=W.name,H.placeholder=(C=W.placeholder)!=null?C:"",W.required&&(H.required=!0),B.appendChild(H),u.appendChild(B)});let p=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=b("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=(L=i.submitLabel)!=null?L:"Submit",p.appendChild(g),p.appendChild(m),u.appendChild(p),s.replaceChildren(d,u),u.addEventListener("submit",async W=>{var H,v;W.preventDefault();let B=(H=n.formEndpoint)!=null?H:"/form",D=new FormData(u),V={};D.forEach((C,M)=>{V[M]=C}),V.type=a,m.disabled=!0,g.textContent="Submitting\u2026";try{let C=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(V)});if(!C.ok)throw new Error(`Form submission failed (${C.status})`);let M=await C.json();g.textContent=(v=M.message)!=null?v:"Thanks! We'll be in touch soon.",M.success&&M.nextPrompt&&await o.sendMessage(String(M.nextPrompt))}catch(C){g.textContent=C instanceof Error?C.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var oc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},rc=new oc;var Zm=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Jb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Zb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},ac=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Jb(e),n=Zb(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},sc=e=>typeof e=="string"?e:e==null?"":String(e),ba={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:sc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=sc(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:sc(n.text)}}},ef=e=>Array.isArray(e)?e.map(t=>String(t)):[],ic=e=>{let t=new Set(ef(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ef(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let g=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:g,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var ey=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}},ty=e=>e.map(t=>({...t,streaming:!1})),ny=e=>e.map(t=>({...t,status:"complete"})),tf=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?ey(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?ty(n.messages):void 0,artifacts:n.artifacts?ny(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var lc=require("partial-json");function nf(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Wr.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function of(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 rf(e){let t=of(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function sf(e){let t=of(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var oy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function af(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=oy}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,m.appendChild(w);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,m.appendChild(x),g.appendChild(m);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let W=[];for(let v=1;v<=5;v++){let C=document.createElement("button");C.type="button",C.className="persona-feedback-rating-btn persona-feedback-star-btn",C.setAttribute("role","radio"),C.setAttribute("aria-checked","false"),C.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),C.title=l[v-1],C.dataset.rating=String(v),C.innerHTML=`
26
+ `):""},nb=(e,t)=>{var u,p,f,g,x;let n=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,r=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",s=tb(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Ju(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},l=a;return r==="tool-name"?l=((x=n.name)==null?void 0:x.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Il(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Il(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Lm=(e,t,n)=>{var u;let o=ns.has(e),r=(u=n==null?void 0:n.toolCall)!=null?u:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"currentColor",f=Ae(o?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},zl=(e,t)=>{var U,j,ge,se,ye,le,Ce,Be,ve;let n=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},r=b("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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),!n)return r;let s=(ge=(j=t==null?void 0:t.features)==null?void 0:j.toolCallDisplay)!=null?ge:{},a=s.expandable!==!1,i=a&&ns.has(e.id),{summary:d,previewText:l,isActive:u}=nb(e,t),p=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(p.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(p.style.paddingLeft=o.headerPaddingX,p.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(p.style.paddingTop=o.headerPaddingY,p.style.paddingBottom=o.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let x=String((se=n.startedAt)!=null?se:Date.now()),C=()=>{let ee=b("span","");return ee.setAttribute("data-tool-elapsed",x),ee.textContent=Xs(n),ee},L=(le=o.renderCollapsedSummary)==null?void 0:le.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ye=s.collapsedMode)!=null?ye:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Xs(n),createElapsedElement:C});typeof L=="string"&&L.trim()?(g.textContent=L,f.appendChild(g)):L instanceof HTMLElement?f.appendChild(L):(g.textContent=d,f.appendChild(g));let B=(Ce=s.loadingAnimation)!=null?Ce:"none",I=o.activeTextTemplate,D=o.completeTextTemplate,F=u?I:D,H=L instanceof HTMLElement,v=(ee,Me,Q)=>{let Te=Q;for(let he of Me){let ce=b("span","persona-tool-char");ce.style.setProperty("--char-index",String(Te)),ce.textContent=he===" "?"\xA0":he,ee.appendChild(ce),Te++}return Te},w=(ee,Me)=>{var ce;g.textContent="";let Q=((ce=n.name)==null?void 0:ce.trim())||"tool",Te=mi(ee,Q),he=0;for(let me of Te){let Ke=me.styles.length>0?(()=>{let K=b("span",me.styles.map(re=>`persona-tool-text-${re}`).join(" "));return g.appendChild(K),K})():g;if(me.isDuration&&u)Ke.appendChild(C());else{let K=me.isDuration?Xs(n):me.text;Me?he=v(Ke,K,he):Ke.appendChild(document.createTextNode(K))}}};if(!H)if(u&&B!=="none"){let ee=(Be=o.loadingAnimationDuration)!=null?Be:2e3;if(g.setAttribute("data-preserve-animation","true"),B==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),F&&w(F,!1);else if(g.classList.add(`persona-tool-loading-${B}`),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),F)w(F,!0);else{let Me=g.textContent||d;g.textContent="",v(g,Me,0)}}else F&&w(F,!1);let M=null;if(a){M=b("div","persona-flex persona-items-center");let ee=o.toggleTextColor||o.headerTextColor||"currentColor",Me=Ae(i?"chevron-up":"chevron-down",16,ee,2);Me?M.appendChild(Me):M.textContent=i?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(M),p.append(f,Q)}else p.append(f);let A=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(A.setAttribute("data-persona-collapsed-preview","tool"),A.style.display="none",A.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let ee=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});eb(A,ee)||(A.textContent=l),A.style.display=""}if(!i&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,A),r;let E=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(E.style.display=i?"":"none",o.contentBackgroundColor&&(E.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(E.style.color=o.contentTextColor),o.contentPaddingX&&(E.style.paddingLeft=o.contentPaddingX,E.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(E.style.paddingTop=o.contentPaddingY,E.style.paddingBottom=o.contentPaddingY),n.name){let ee=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ee.style.color=o.contentTextColor:o.headerTextColor&&(ee.style.color=o.headerTextColor),ee.textContent=n.name,E.appendChild(ee)}if(n.args!==void 0){let ee=b("div","persona-space-y-1"),Me=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Me.style.color=o.labelTextColor),Me.textContent="Arguments";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Q.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Q.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Q.style.color=o.codeBlockTextColor),Q.textContent=Zr(n.args),ee.append(Me,Q),E.appendChild(ee)}if(n.chunks&&n.chunks.length){let ee=b("div","persona-space-y-1"),Me=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Me.style.color=o.labelTextColor),Me.textContent="Activity";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Q.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Q.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Q.style.color=o.codeBlockTextColor),Q.textContent=n.chunks.join(""),ee.append(Me,Q),E.appendChild(ee)}if(n.status==="complete"&&n.result!==void 0){let ee=b("div","persona-space-y-1"),Me=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Me.style.color=o.labelTextColor),Me.textContent="Result";let Q=b("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Q.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Q.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Q.style.color=o.codeBlockTextColor),Q.textContent=Zr(n.result),ee.append(Me,Q),E.appendChild(ee)}if(n.status==="complete"&&typeof n.duration=="number"){let ee=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ee.style.color=o.contentTextColor),ee.textContent=`Duration: ${n.duration}ms`,E.appendChild(ee)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),M){M.innerHTML="";let ee=o.toggleTextColor||o.headerTextColor||"currentColor",Me=Ae(i?"chevron-up":"chevron-down",16,ee,2);Me?M.appendChild(Me):M.textContent=i?"Hide":"Show"}E.style.display=i?"":"none",A.style.display=i?"none":A.textContent||A.childNodes.length?"":"none"})(),r.append(p,A,E),r};var ar=require("partial-json");var ob="ask_user_question",ql=8,os="data-persona-ask-sheet-for",rb="Other",sb="Other\u2026",Rm="Type your own answer here",Pm="Send",ab="Next",ib="Back",lb="Submit all",cb="Skip",db=3,jl="data-ask-current-index",Kl="data-ask-question-count",Wm="data-ask-answers",Gl="data-ask-grouped",Bm="data-ask-layout",pb=e=>e.layout==="pills"?"pills":"rows",ub=e=>e.getAttribute(Bm)==="pills"?"pills":"rows",Im=!1,Hm=e=>e.replace(/["\\]/g,"\\$&"),Ir=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ob,Yl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},rs=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ar.parse)(r,ar.STR|ar.OBJ|ar.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ma=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ql&&!Im&&(Im=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ql}.`)),t.slice(0,ql)},mb=e=>{var t;return(t=ma(e)[0])!=null?t:null},gb=(e,t)=>{var n;return(n=ma(e)[t])!=null?n:null},fb=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Dm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},hb=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Dm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},bb=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},yb=(e,t,n,o)=>{var u,p,f;let s=b("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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<db;g++)s.appendChild(bb(o));return s}if(d.forEach((g,x)=>{s.appendChild(hb(g,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=o==="rows"?rb:sb;if(o==="rows"){let x=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let C=b("span","persona-ask-row-content"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(u=t.freeTextPlaceholder)!=null?u:Rm,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:g),C.appendChild(L),x.appendChild(C);let B=Dm(o,a,d.length);B&&x.appendChild(B),s.appendChild(x)}else{let x=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(x)}}return s},Fm=(e,t)=>{var s,a;let o=b("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 r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:Rm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Pm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},vb=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:Pm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},xb=(e,t,n)=>{var l,u,p,f;let o=b("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 r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:ib,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:cb,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:lb:(f=n.nextLabel)!=null?f:ab,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Rr=e=>{let t=e.getAttribute(Wm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Om=(e,t)=>{e.setAttribute(Wm,JSON.stringify(t))},co=e=>{var n;let t=Number((n=e.getAttribute(jl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wb=(e,t)=>{e.setAttribute(jl,String(Math.max(0,Math.floor(t))))},ss=e=>{var n;let t=Number((n=e.getAttribute(Kl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ir=e=>e.getAttribute(Gl)==="true",Cb=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},Sb=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},$i=(e,t)=>{let{payload:n}=rs(t),o=ma(n),r=Rr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},Nm=e=>{let t=Rr(e),n=co(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=r.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.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=""},_m=e=>{if(!ir(e))return;let t=Rr(e),n=co(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Xl=(e,t,n)=>{let o=Yl(n),r=ub(e),{payload:s,complete:a}=rs(t),i=ir(e),d=co(e),l=ss(e),u=i?gb(s,d):mb(s),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let I=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=I,x.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let I=yb(u,o,a,r);C.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(Fm(o,r))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!L?e.appendChild(vb(o)):(!p||i)&&L&&L.remove(),e.setAttribute("data-multi-select",p?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=xb(d,l,o);B?B.replaceWith(I):e.appendChild(I)}else B&&B.remove();Nm(e),_m(e)},Ab=(e,t,n)=>{let o=Yl(t),r=pb(o),s=e.toolCall.id,a=ma(n),i=Math.max(1,a.length),d=i>1,l=Cb(e,a),u=d?Sb(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(os,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Kl,String(i)),p.setAttribute(jl,String(u)),p.setAttribute(Gl,d?"true":"false"),p.setAttribute(Bm,r),Om(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),fb(p,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let x=b("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),p.appendChild(f);let L=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),p.appendChild(L),r!=="rows"&&p.appendChild(Fm(o,r)),Xl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Tb=(e,t,n)=>{let{payload:o}=rs(t),r=Math.max(1,ma(o).length);r>ss(e)&&(e.setAttribute(Kl,String(r)),r>1&&!ir(e)&&e.setAttribute(Gl,"true")),Xl(e,t,n)};var Ui=(e,t,n)=>{if(!n||!Ir(e)||Yl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${os}]`).forEach(l=>{l.getAttribute(os)!==r&&l.remove()});let a=n.querySelector(`[${os}="${Hm(r)}"]`);if(a){Tb(a,e,t);return}let{payload:i}=rs(e),d=Ab(e,t,i);n.appendChild(d)},as=(e,t)=>{if(!e)return;let n=t?`[${os}="${Hm(t)}"]`:`[${os}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ql=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),lr=(e,t)=>{let n=Rr(e),o=co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Om(e,n),Nm(e),_m(e)},zi=(e,t,n,o)=>{let r=ss(e),s=Math.max(0,Math.min(r-1,o));wb(e,s),Xl(e,t,n)};var Jl=(e,t)=>{var C,L,B,I,D,F,H,v,w,M,A,E;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(C=o==null?void 0:o.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(L=o==null?void 0:o.borderColor)!=null?L:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(B=o==null?void 0:o.titleColor)!=null?B:"currentColor",u=Ae(d,20,l,2);u&&i.appendChild(u);let p=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),g=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(g.style.color=o.titleColor),g.textContent=(I=o==null?void 0:o.title)!=null?I:"Approval Required",f.appendChild(g),!r){let O=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",n.status),n.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):n.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):n.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}p.appendChild(f);let x=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(x.style.color=o.descriptionColor),x.textContent=n.description,p.appendChild(x),n.parameters){let O=b("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&&(O.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(O.style.color=o.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=Zr(n.parameters),p.appendChild(O)}if(r){let O=b("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let U=b("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");U.type="button",U.style.backgroundColor=(D=o==null?void 0:o.approveButtonColor)!=null?D:"var(--persona-approval-approve-bg, #22c55e)",U.style.color=(F=o==null?void 0:o.approveButtonTextColor)!=null?F:"#ffffff",U.setAttribute("data-approval-action","approve");let j=Ae("shield-check",14,(H=o==null?void 0:o.approveButtonTextColor)!=null?H:"#ffffff",2);j&&(j.style.marginRight="4px",U.appendChild(j));let ge=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");U.appendChild(ge);let se=b("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");se.type="button",se.style.backgroundColor=(w=o==null?void 0:o.denyButtonColor)!=null?w:"transparent",se.style.color=(M=o==null?void 0:o.denyButtonTextColor)!=null?M:"var(--persona-feedback-error, #dc2626)",se.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,se.setAttribute("data-approval-action","deny");let ye=Ae("shield-x",14,(A=o==null?void 0:o.denyButtonTextColor)!=null?A:"var(--persona-feedback-error, #dc2626)",2);ye&&(ye.style.marginRight="4px",se.appendChild(ye));let le=document.createTextNode((E=o==null?void 0:o.denyLabel)!=null?E:"Deny");se.appendChild(le),O.append(U,se),p.appendChild(O)}return a.append(i,p),s.appendChild(a),s};var Vm=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(g=>g.role==="user"))return;let u=document.createDocumentFragment(),p=r?r.isStreaming():!1,f=g=>{switch(g){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(g=>{let x=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=g,x.disabled=p,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(g))}),u.appendChild(x),t.push(x)}),e.appendChild(u)}}};var ga=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)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,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var fa=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}};var kb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Eb=new Set(["step_start","execution_start"]),Mb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Lb=new Set(["step_complete","agent_turn_complete"]),Ib=new Set(["flow_complete","agent_complete"]),$m=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),zm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pr=(e,t)=>{let n=e[t];return zm(n)?n:void 0};function Zl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function qi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Rb(e,t){return typeof t.type=="string"?t.type:e}function Pb(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 Wb(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 Um(e){var o,r,s,a,i;let t=Pr(e,"result"),n=[Pr(e,"tokens"),Pr(e,"totalTokens"),t?Pr(t,"tokens"):void 0,Pr(e,"usage"),t?Pr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Jn(d.output))!=null?o:Jn(d.outputTokens))!=null?r:Jn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Jn(e.outputTokens))!=null?s:Jn(e.completionTokens))!=null?i:t?(a=Jn(t.outputTokens))!=null?a:Jn(t.completionTokens):void 0}function Bb(e){var n,o,r,s,a;let t=Pr(e,"result");return(a=(r=(o=(n=Jn(e.executionTime))!=null?n:Jn(e.executionTimeMs))!=null?o:Jn(e.execution_time))!=null?r:Jn(e.duration))!=null?a:t?(s=Jn(t.executionTime))!=null?s:Jn(t.executionTimeMs):void 0}function Hb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ha=class{constructor(t=Hb){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:qi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!zm(n)){$m.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Rb(t,n),r=this.now();if(kb.has(o)){this.startRun(r);return}if(Eb.has(o)){this.run||this.startRun(r);return}if(Mb.has(o)){if(!Wb(o,n))return;let a=Pb(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Zl(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:qi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Lb.has(o)){if(!this.run)return;let a=this.run,i=Um(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Zl(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:qi(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Ib.has(o)){if(!this.run)return;let a=this.run,i=Um(n),d=i!=null?i:a.exactOutputTokens+Zl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:qi(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if($m.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Bb(n);return s!=null?s:o-t.startedAt}};function is(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Db={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)"}},Fb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ob=["flowName","stepName","reasoningText","text","name","tool","toolName"],Nb=100;function _b(e,t){let n={...Db,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Fb}function Vb(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function $b(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Ub(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function zb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{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),n()})}function qb(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 jb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Kb(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 Gb(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("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=b("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 ec(e,t,n,o,r,s,a,i){var f;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");is(l,(f=o.classNames)==null?void 0:f.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let g=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var U,j;let g=b("div",""),x=b("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=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),L=Ae(d?"chevron-down":"chevron-right","14px","currentColor",2);L&&C.appendChild(L);let B=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(U=o.timestampFormat)!=null?U:"relative";B.textContent=I==="relative"?Vb(e.timestamp,n):$b(e.timestamp);let D=null;o.showSequenceNumbers!==!1&&(D=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(t+1));let F=_b(e.type,o.badgeColors),H=b("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");H.style.backgroundColor=F.bg,H.style.color=F.text,H.style.borderColor=F.text+"50",H.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Ob,w=Ub(e.payload,v),M=null;w&&(M=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),M.textContent=w);let A=b("div","persona-flex-1 persona-min-w-0"),E=b("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"),O=Ae("clipboard","12px","currentColor",1.5);return O&&E.appendChild(O),E.addEventListener("click",async ge=>{ge.stopPropagation(),await zb(qb(e)),E.innerHTML="";let se=Ae("check","12px","currentColor",1.5);se&&E.appendChild(se),setTimeout(()=>{E.innerHTML="";let ye=Ae("clipboard","12px","currentColor",1.5);ye&&E.appendChild(ye)},1500)}),x.appendChild(C),x.appendChild(B),D&&x.appendChild(D),x.appendChild(H),M&&x.appendChild(M),x.appendChild(A),x.appendChild(E),g.appendChild(x),d&&g.appendChild(Gb(e,a,i)),g}}function qm(e){var x,C,L,B,I;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(x=r==null?void 0:r.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(L=i==null?void 0:i.label)!=null?L:"",p=(I=(B=r==null?void 0:r.features)==null?void 0:B.eventStream)!=null?I:{},f=s.find(D=>D.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let D=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(D)return{element:D,update:()=>{},destroy:()=>{}}}return g();function g(){let D=p.classNames,F=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");is(F,D==null?void 0:D.panel);let H=[],v="",w="",M=null,A=[],E={},O=0,U=Ti(),j=0,ge=0,se=!1,ye=null,le=!1,Ce=0,Be=new Set,ve=new Map,ee="",Me="",Q=null,Te,he,ce,me,Ke,K=null,re=null,Pe=null;function nt(){let ie=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),xe=b("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");is(xe,D==null?void 0:D.headerBar);let Ct=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ct.textContent="Events",Te=b("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"),Te.textContent="0",a){re=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),re.style.cursor="help";let On=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");On.textContent="Throughput",K=b("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"),K.textContent="-- tok/s",Pe=b("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"),Pe.style.display="none",Pe.style.pointerEvents="none";let eo=re,wn=Pe,Nn=()=>{if(!wn.textContent)return;let So=eo.getBoundingClientRect(),_n=ie.getBoundingClientRect();wn.style.left=`${So.left-_n.left}px`,wn.style.top=`${So.bottom-_n.top+4}px`,wn.style.display="block"},mt=()=>{wn.style.display="none"};re.addEventListener("mouseenter",Nn),re.addEventListener("mouseleave",mt),re.appendChild(On),re.appendChild(K)}let Vt=b("div","persona-flex-1");he=b("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=b("option","");Zt.value="",Zt.textContent="All events",he.appendChild(Zt),ce=b("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"),ce.type="button",ce.title="Copy All";let Mt=Ae("clipboard-copy","12px","currentColor",1.5);Mt&&ce.appendChild(Mt);let Tt=b("span","persona-text-xs");Tt.textContent="Copy All",ce.appendChild(Tt),xe.appendChild(Ct),xe.appendChild(Te),re&&xe.appendChild(re),xe.appendChild(Vt),xe.appendChild(he),xe.appendChild(ce);let bt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");is(bt,D==null?void 0:D.searchBar);let vt=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");vt&&zt.appendChild(vt),me=b("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"),is(me,D==null?void 0:D.searchInput),me.type="text",me.placeholder="Search event payloads...",Ke=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ke.type="button",Ke.style.display="none";let et=Ae("x","12px","currentColor",2);return et&&Ke.appendChild(et),bt.appendChild(zt),bt.appendChild(me),bt.appendChild(Ke),ie.appendChild(xe),ie.appendChild(bt),Pe&&ie.appendChild(Pe),ie}let fe,de=s.find(ie=>ie.renderEventStreamToolbar);if(de!=null&&de.renderEventStreamToolbar&&r){let ie=de.renderEventStreamToolbar({config:r,defaultRenderer:()=>nt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:xe=>{v=xe,Fn(),ae()},onSearchChange:xe=>{w=xe,Fn(),ae()}});fe=ie!=null?ie:nt()}else fe=nt();let Ve=b("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");Ve.style.display="none";function Ie(){if(!a||!K||!re)return;let ie=a();K.textContent=jb(ie);let xe=Kb(ie);Pe&&(Pe.textContent=xe,xe||(Pe.style.display="none")),xe?re.setAttribute("aria-label",xe):re.removeAttribute("aria-label")}let pe=b("div","persona-flex-1 persona-min-h-0 persona-relative"),X=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let $e=b("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");is($e,D==null?void 0:D.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let St=Ae(l,"14px","currentColor",2);St&&$e.appendChild(St);let J=b("span","");J.textContent=u,$e.appendChild(J);let Oe=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Oe.style.display="none",pe.appendChild(X),pe.appendChild(Oe),pe.appendChild($e),F.setAttribute("tabindex","0"),F.appendChild(fe),F.appendChild(Ve),F.appendChild(pe);function In(){let ie=t.getAll(),xe={};for(let Tt of ie)xe[Tt.type]=(xe[Tt.type]||0)+1;let Ct=Object.keys(xe).sort(),Vt=Ct.length!==A.length||!Ct.every((Tt,bt)=>Tt===A[bt]),Zt=!Vt&&Ct.some(Tt=>xe[Tt]!==E[Tt]),xn=ie.length!==Object.values(E).reduce((Tt,bt)=>Tt+bt,0);if(!Vt&&!Zt&&!xn||(A=Ct,E=xe,!he))return;let Mt=he.value;if(he.options[0].textContent="All events",Vt){for(;he.options.length>1;)he.remove(1);for(let Tt of Ct){let bt=b("option","");bt.value=Tt,bt.textContent=`${Tt} (${xe[Tt]||0})`,he.appendChild(bt)}Mt&&Ct.includes(Mt)?he.value=Mt:Mt&&(he.value="",v="")}else for(let Tt=1;Tt<he.options.length;Tt++){let bt=he.options[Tt];bt.textContent=`${bt.value} (${xe[bt.value]||0})`}}function Ot(){let ie=t.getAll();if(v&&(ie=ie.filter(xe=>xe.type===v)),w){let xe=w.toLowerCase();ie=ie.filter(Ct=>Ct.type.toLowerCase().includes(xe)||Ct.payload.toLowerCase().includes(xe))}return ie}function cn(){return v!==""||w!==""}function Fn(){O=0,j=0,U.resume(),$e.style.display="none"}function Zn(ie){Be.has(ie)?Be.delete(ie):Be.add(ie),Q=ie;let xe=X.scrollTop,Ct=U.isFollowing();le=!0,U.pause(),ae(),X.scrollTop=xe,Ct&&U.resume(),le=!1}function _(){return oa(X,50)}function ae(){ge=Date.now(),se=!1,Ie(),In();let ie=t.getEvictedCount();ie>0?(Ve.textContent=`${ie.toLocaleString()} older events truncated`,Ve.style.display=""):Ve.style.display="none",H=Ot();let xe=H.length,Ct=t.getSize()>0;Te&&(Te.textContent=String(t.getSize())),xe===0&&Ct&&cn()?(Oe.textContent=w?`No events matching '${w}'`:"No events matching filter",Oe.style.display="",X.style.display="none"):(Oe.style.display="none",X.style.display=""),ce&&(ce.title=cn()?`Copy Filtered (${xe})`:"Copy All"),d&&!U.isFollowing()&&xe>O&&(j+=xe-O,J.textContent=u?`${u}${j>0?` (${j})`:""}`:"",$e.style.display=""),O=xe;let Vt=t.getAll(),Zt=Vt.length>0?Vt[0].timestamp:0,xn=new Set(H.map(bt=>bt.id));for(let bt of Be)xn.has(bt)||Be.delete(bt);let Mt=v!==ee||w!==Me,Tt=ve.size===0&&H.length>0;if(Mt||Tt||H.length===0){X.innerHTML="",ve.clear();let bt=document.createDocumentFragment();for(let vt=0;vt<H.length;vt++){let zt=ec(H[vt],vt,Zt,p,Be,Zn,s,r);ve.set(H[vt].id,zt),bt.appendChild(zt)}X.appendChild(bt),ee=v,Me=w,Q=null}else{if(Q!==null){let vt=ve.get(Q);if(vt&&vt.parentNode===X){let zt=H.findIndex(et=>et.id===Q);if(zt>=0){let et=ec(H[zt],zt,Zt,p,Be,Zn,s,r);X.insertBefore(et,vt),vt.remove(),ve.set(Q,et)}}Q=null}let bt=new Set(H.map(vt=>vt.id));for(let[vt,zt]of ve)bt.has(vt)||(zt.remove(),ve.delete(vt));for(let vt=0;vt<H.length;vt++){let zt=H[vt];if(!ve.has(zt.id)){let et=ec(zt,vt,Zt,p,Be,Zn,s,r);ve.set(zt.id,et),X.appendChild(et)}}}U.isFollowing()&&(X.scrollTop=X.scrollHeight)}function De(){if(Date.now()-ge>=Nb){ye!==null&&(cancelAnimationFrame(ye),ye=null),ae();return}se||(se=!0,ye=requestAnimationFrame(()=>{ye=null,ae()}))}let Qe=(ie,xe)=>{if(!ce)return;ce.innerHTML="";let Ct=Ae(ie,"12px","currentColor",1.5);Ct&&ce.appendChild(Ct);let Vt=b("span","persona-text-xs");Vt.textContent="Copy All",ce.appendChild(Vt),setTimeout(()=>{ce.innerHTML="";let Zt=Ae("clipboard-copy","12px","currentColor",1.5);Zt&&ce.appendChild(Zt);let xn=b("span","persona-text-xs");xn.textContent="Copy All",ce.appendChild(xn),ce.disabled=!1},xe)},Ne=async()=>{if(ce){ce.disabled=!0;try{let ie;cn()?ie=H:n?(ie=await n(),ie.length===0&&(ie=t.getAll())):ie=t.getAll();let xe=ie.map(Ct=>{try{return JSON.parse(Ct.payload)}catch{return Ct.payload}});await navigator.clipboard.writeText(JSON.stringify(xe,null,2)),Qe("check",1500)}catch{Qe("x",1500)}}},_e=()=>{he&&(v=he.value,Fn(),ae())},rt=()=>{!me||!Ke||(Ke.style.display=me.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{w=me.value,Fn(),ae()},150))},At=()=>{!me||!Ke||(me.value="",w="",Ke.style.display="none",M&&clearTimeout(M),Fn(),ae())},_t=()=>{if(le)return;let ie=X.scrollTop,{action:xe,nextLastScrollTop:Ct}=ki({following:U.isFollowing(),currentScrollTop:ie,lastScrollTop:Ce,nearBottom:_(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ce=Ct,xe==="resume"?(U.resume(),j=0,$e.style.display="none"):xe==="pause"&&(U.pause(),d&&(J.textContent=u,$e.style.display=""))},Kt=ie=>{let xe=Ei({following:U.isFollowing(),deltaY:ie.deltaY,nearBottom:_(),resumeWhenNearBottom:!0});xe==="pause"?(U.pause(),d&&(J.textContent=u,$e.style.display="")):xe==="resume"&&(U.resume(),j=0,$e.style.display="none")},G=()=>{d&&(X.scrollTop=X.scrollHeight,U.resume(),j=0,$e.style.display="none")},ft=ie=>{let xe=ie.target;if(!xe||xe.closest("button"))return;let Ct=xe.closest("[data-event-id]");if(!Ct)return;let Vt=Ct.getAttribute("data-event-id");Vt&&Zn(Vt)},ot=ie=>{if((ie.metaKey||ie.ctrlKey)&&ie.key==="f"){ie.preventDefault(),me==null||me.focus(),me==null||me.select();return}ie.key==="Escape"&&(me&&document.activeElement===me?(At(),me.blur(),F.focus()):o&&o())};ce&&ce.addEventListener("click",Ne),he&&he.addEventListener("change",_e),me&&me.addEventListener("input",rt),Ke&&Ke.addEventListener("click",At),X.addEventListener("scroll",_t),X.addEventListener("wheel",Kt,{passive:!0}),X.addEventListener("click",ft),$e.addEventListener("click",G),F.addEventListener("keydown",ot);function Ut(){M&&clearTimeout(M),ye!==null&&(cancelAnimationFrame(ye),ye=null),se=!1,ve.clear(),ce&&ce.removeEventListener("click",Ne),he&&he.removeEventListener("change",_e),me&&me.removeEventListener("input",rt),Ke&&Ke.removeEventListener("click",At),X.removeEventListener("scroll",_t),X.removeEventListener("wheel",Kt),X.removeEventListener("click",ft),$e.removeEventListener("click",G),F.removeEventListener("keydown",ot)}return{element:F,update:De,destroy:Ut}}}function jm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),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=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(g)}else p.textContent=a;if(l.append(u,p),i.append(d,l),r==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",o),i.append(f)}return i}var Km=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>jm(e,t)});if(u)return u}return jm(e,t)};var tc=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Wr=new tc;Wr.register("PersonaArtifactCard",Km);function Yb(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function Gm(e,t){var he,ce,me,Ke;let n=(ce=(he=e.features)==null?void 0:he.artifacts)==null?void 0:ce.layout,r=((me=n==null?void 0:n.toolbarPreset)!=null?me:"default")==="document",s=(Ke=n==null?void 0:n.panePadding)==null?void 0:Ke.trim(),a=e.markdown?ii(e.markdown):null,i=li(e.sanitize),d=K=>{let re=a?a(K):Gs(K);return i?i(re):re},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=t.onDismiss)==null||K.call(t)});let p=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),r&&p.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&f.classList.add("persona-artifact-toolbar-document");let g=b("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=b("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 K;u(),(K=t.onDismiss)==null||K.call(t)});let C="rendered",L=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),B=r?vn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):vn({icon:"eye",label:"Rendered view"}),I=r?vn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):vn({icon:"code-2",label:"Source"}),D=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),F=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,H=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,w=!!(H&&v&&v.length>0),M=null,A,E=null,O=null;if(r&&(F||H)&&!w){if(A=F?Nl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H){let K=Ae("chevron-down",14,"currentColor",2);K&&A.appendChild(K)}}else r&&w?(M=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),A=F?Nl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=vn({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"}}),M.append(A,E)):r?A=vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):A=vn({icon:"copy",label:"Copy"});let U=r?vn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vn({icon:"refresh-cw",label:"Refresh"}),j=r?vn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):vn({icon:"x",label:"Close"}),ge=()=>{var fe,de,Ve;let K=(fe=ve.find(Ie=>Ie.id===ee))!=null?fe:ve[ve.length-1],re=(de=K==null?void 0:K.id)!=null?de:null,Pe=(K==null?void 0:K.artifactType)==="markdown"&&(Ve=K.markdown)!=null?Ve:"",nt=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Pe,jsonPayload:nt,id:re}},se=async()=>{var fe;let{markdown:K,jsonPayload:re}=ge(),Pe=(fe=ve.find(de=>de.id===ee))!=null?fe:ve[ve.length-1],nt=(Pe==null?void 0:Pe.artifactType)==="markdown"?K:Pe?re:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(A.addEventListener("click",async()=>{let K=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(K&&w){let{markdown:re,jsonPayload:Pe,id:nt}=ge();try{await K({actionId:"primary",artifactId:nt,markdown:re,jsonPayload:Pe})}catch{}return}await se()}),E&&(v!=null&&v.length)){let K=()=>{var Pe;return(Pe=p.closest("[data-persona-root]"))!=null?Pe:document.body},re=()=>{O=es({items:v.map(Pe=>({id:Pe.id,label:Pe.label})),onSelect:async Pe=>{let{markdown:nt,jsonPayload:fe,id:de}=ge(),Ve=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ve?await Ve({actionId:Pe,artifactId:de,markdown:nt,jsonPayload:fe}):Pe==="markdown"||Pe==="md"?await navigator.clipboard.writeText(nt):Pe==="json"||Pe==="source"?await navigator.clipboard.writeText(fe):await navigator.clipboard.writeText(nt||fe)}catch{}},anchor:M!=null?M:E,position:"bottom-right",portal:K()})};p.isConnected?re():requestAnimationFrame(re),E.addEventListener("click",Pe=>{Pe.stopPropagation(),O==null||O.toggle()})}U.addEventListener("click",async()=>{var K;try{await((K=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:K.call(n))}catch{}Q()}),j.addEventListener("click",()=>{var K;u(),(K=t.onDismiss)==null||K.call(t)});let ye=()=>{r&&(B.setAttribute("aria-pressed",C==="rendered"?"true":"false"),I.setAttribute("aria-pressed",C==="source"?"true":"false"))};B.addEventListener("click",()=>{C="rendered",ye(),Q()}),I.addEventListener("click",()=>{C="source",ye(),Q()});let le=b("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");r?(f.replaceChildren(),L.append(B,I),M?D.append(M,U,j):D.append(A,U,j),f.append(L,le,D),ye()):(f.appendChild(g),f.appendChild(x)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Ce=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Be=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ce.style.paddingLeft=s,Ce.style.paddingRight=s,Be.style.padding=s),p.appendChild(f),p.appendChild(Ce),p.appendChild(Be);let ve=[],ee=null,Me=!1,Q=()=>{var nt,fe,de,Ve;let K=r&&ve.length<=1;Ce.classList.toggle("persona-hidden",K),Ce.replaceChildren();for(let Ie of ve){let pe=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");pe.type="button",pe.textContent=Ie.title||Ie.id.slice(0,8),Ie.id===ee&&pe.classList.add("persona-bg-persona-container","persona-border-persona-border"),pe.addEventListener("click",()=>t.onSelect(Ie.id)),Ce.appendChild(pe)}Be.replaceChildren();let re=ee&&ve.find(Ie=>Ie.id===ee)||ve[ve.length-1];if(!re)return;if(r){let Ie=re.artifactType==="markdown"?"MD":(nt=re.component)!=null?nt:"Component",X=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${X} \xB7 ${Ie}`}else g.textContent="Artifacts";if(re.artifactType==="markdown"){if(r&&C==="source"){let pe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");pe.textContent=(fe=re.markdown)!=null?fe:"",Be.appendChild(pe);return}let Ie=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ie.innerHTML=d((de=re.markdown)!=null?de:""),Be.appendChild(Ie);return}let Pe=re.component?Wr.get(re.component):void 0;if(Pe){let pe={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=Pe((Ve=re.props)!=null?Ve:{},pe);if(X){Be.appendChild(X);return}}catch{}}Be.appendChild(Yb(re))},Te=()=>{var re;let K=ve.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Pe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,fe=((re=Pe==null?void 0:Pe.classList.contains("persona-artifact-narrow-host"))!=null?re:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&fe&&Me?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var re,Pe,nt;ve=K.artifacts,ee=(nt=(Pe=K.selectedId)!=null?Pe:(re=K.artifacts[K.artifacts.length-1])==null?void 0:re.id)!=null?nt:null,ve.length>0&&(Me=!0),Q(),Te()},setMobileOpen(K){Me=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):Te()}}}function po(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Ym(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!po(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Xb(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 ji(e,t){var d,l,u,p,f,g,x,C,L,B;if(!po(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"),Xb(e),Ym(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(C=n==null?void 0:n.documentToolbarIconColor)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(L=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:L.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(B=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:B.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ym(e,t)}var Xm=["panel","seamless"];function Ki(e,t){var i,d,l,u,p,f;for(let g of Xm)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!po(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=Xm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Qm(e,t){var n,o,r;return!t||!po(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function Qb(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Jb(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 Zb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ey(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Jm(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Zm(e,t,n,o,r,s){let a=Qb(r,200),i=ey(t,n,o,200);i=Math.max(a,i);let d=Jb(s);return d!==null&&(i=Math.min(i,d)),Zb(e,a,i)}var eg={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"}},nc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var x,C,L;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(C=eg[a])!=null?C:eg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let B=b("p","persona-text-sm persona-text-persona-muted");B.textContent=i.description,d.appendChild(B)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(B=>{var v,w;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${B.name}`;let D=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=B.label,I.appendChild(D);let F=(v=B.type)!=null?v:"text",H;F==="textarea"?(H=document.createElement("textarea"),H.rows=3):(H=document.createElement("input"),H.type=F),H.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",H.id=`${t.id}-${a}-${B.name}`,H.name=B.name,H.placeholder=(w=B.placeholder)!=null?w:"",B.required&&(H.required=!0),I.appendChild(H),u.appendChild(I)});let p=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(L=i.submitLabel)!=null?L:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),s.replaceChildren(d,u),u.addEventListener("submit",async B=>{var H,v;B.preventDefault();let I=(H=n.formEndpoint)!=null?H:"/form",D=new FormData(u),F={};D.forEach((w,M)=>{F[M]=w}),F.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let w=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!w.ok)throw new Error(`Form submission failed (${w.status})`);let M=await w.json();f.textContent=(v=M.message)!=null?v:"Thanks! We'll be in touch soon.",M.success&&M.nextPrompt&&await o.sendMessage(String(M.nextPrompt))}catch(w){f.textContent=w instanceof Error?w.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var oc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},rc=new oc;var tg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ty=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ny=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},ac=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=ty(e),n=ny(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},sc=e=>typeof e=="string"?e:e==null?"":String(e),ba={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:sc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=sc(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:sc(n.text)}}},ng=e=>Array.isArray(e)?e.map(t=>String(t)):[],ic=e=>{let t=new Set(ng(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ng(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var oy=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}},ry=e=>e.map(t=>({...t,streaming:!1})),sy=e=>e.map(t=>({...t,status:"complete"})),og=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?oy(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?ry(n.messages):void 0,artifacts:n.artifacts?sy(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var lc=require("partial-json");function rg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Wr.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function sg(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 ag(e){let t=sg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ig(e){let t=sg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var ay=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function lg(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=ay}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,g.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),f.appendChild(g);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let v=1;v<=5;v++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),w.title=l[v-1],w.dataset.rating=String(v),w.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
29
29
  </svg>
30
- `,C.addEventListener("click",()=>{p=v,W.forEach((M,A)=>{let E=A<v;M.classList.toggle("selected",E),M.setAttribute("aria-checked",A===v-1?"true":"false")})}),W.push(C),L.appendChild(C)}g.appendChild(L);let B=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),v.appendChild(B),g.appendChild(v)}let D=document.createElement("div");D.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=i,V.addEventListener("click",()=>{n==null||n(),u.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(p===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let v=(B==null?void 0:B.value.trim())||void 0;await t(p,v),u.remove()}catch(v){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),D.appendChild(V),D.appendChild(H),g.appendChild(D),u.appendChild(g),u}function lf(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,w.appendChild(x);let L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=r,w.appendChild(L),m.appendChild(w);let W=document.createElement("div");W.className="persona-feedback-rating persona-feedback-rating-nps",W.setAttribute("role","radiogroup"),W.setAttribute("aria-label","Likelihood rating from 0 to 10");let B=document.createElement("div");B.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=l;let V=document.createElement("span");V.className="persona-feedback-label-high",V.textContent=u,B.appendChild(D),B.appendChild(V);let H=document.createElement("div");H.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${F} out of 10`),U.textContent=String(F),U.dataset.rating=String(F),F<=6?U.classList.add("persona-feedback-detractor"):F<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{g=F,v.forEach((j,fe)=>{j.classList.toggle("selected",fe===F),j.setAttribute("aria-checked",fe===F?"true":"false")})}),v.push(U),H.appendChild(U)}W.appendChild(B),W.appendChild(H),m.appendChild(W);let C=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",C=document.createElement("textarea"),C.className="persona-feedback-comment",C.placeholder=s,C.rows=3,C.setAttribute("aria-label","Additional comments"),F.appendChild(C),m.appendChild(F)}let M=document.createElement("div");M.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{n==null||n(),p.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=a,E.addEventListener("click",async()=>{if(g===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let F=(C==null?void 0:C.value.trim())||void 0;await t(g,F),p.remove()}catch(F){E.disabled=!1,E.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),M.appendChild(A),M.appendChild(E),m.appendChild(M),p.appendChild(m),p}var ls="persona-chat-history",ry=30*1e3,sy={"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 ay(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=sy[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Gi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function iy(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function ly(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var cc=e=>!e||typeof e!="object"?{}:{...e},cf=e=>e.map(t=>({...t,streaming:!1})),df=(e,t,n)=>{let o=e!=null&&e.markdown?ii(e.markdown):null,r=li(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,u,p;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):o?d=o(a):d=Gs(a),r?r(d):d}};function pf(e){var i,d,l,u;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=Ae(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let p=b("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var uf=(e,t,n)=>{var Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,fd,gd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td;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=ku(t),r=rc.getForInstance(o.plugins);o.components&&Wr.registerAll(o.components);let s=Zm(),i=o.persistState===!1?null:(Pc=o.storageAdapter)!=null?Pc:tf(),d={},l=null,u=!1,p=c=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:y}=f;return y&&(u=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return p(h)});else{let f=c!=null?c:{messages:[],metadata:{}},h=p(f);h.metadata&&(d=cc(h.metadata)),(Wc=h.messages)!=null&&Wc.length&&(o={...o,initialMessages:h.messages}),(Bc=h.artifacts)!=null&&Bc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Hc=h.selectedArtifactId)!=null?Hc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=p({messages:[],metadata:{}});(Dc=c.messages)!=null&&Dc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,m=c=>{var h;d=(h=c({...d}))!=null?h:{},Nr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ac],x=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ba.message,ba.messageAndClick],L=ic({parsers:w,handlers:x,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let W=(Oc=(Fc=o.launcher)==null?void 0:Fc.enabled)!=null?Oc:!0,B=(_c=(Nc=o.launcher)==null?void 0:Nc.autoExpand)!=null?_c:!1,D=(Vc=o.autoFocusInput)!=null?Vc:!1,V=B,H=W,v=(Uc=($c=o.layout)==null?void 0:$c.header)==null?void 0:Uc.layout,C=!1,M=()=>ca(o),A=()=>W||M(),E=M()?!1:W?B:!0,F=!1,U=null,j=()=>{F=!0,U&&clearTimeout(U),U=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},fe=df(o,L,j),se=(qc=(zc=o.features)==null?void 0:zc.showReasoning)!=null?qc:!0,ye=(Kc=(jc=o.features)==null?void 0:jc.showToolCalls)!=null?Kc:!0,le=(Yc=(Gc=o.features)==null?void 0:Gc.showEventStreamToggle)!=null?Yc:!1,Ce=(Qc=(Xc=o.features)==null?void 0:Xc.scrollToBottom)!=null?Qc:{},ve=`${(Zc=typeof o.persistState=="object"?(Jc=o.persistState)==null?void 0:Jc.keyPrefix:void 0)!=null?Zc:"persona-"}event-stream`,ee=le?new ga(ve):null,Me=(nd=(td=(ed=o.features)==null?void 0:ed.eventStream)==null?void 0:td.maxEvents)!=null?nd:2e3,Q=le?new fa(Me,ee):null,Te=le?new ha:null,he=null,ce=!1,me=null,Ke=0;ee==null||ee.open().then(()=>Q==null?void 0:Q.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let K={onCopy:c=>{var f,h;s.emit("message:copy",c),k!=null&&k.isClientTokenMode()&&k.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,c)},onFeedback:c=>{var f,h;s.emit("message:feedback",c),k!=null&&k.isClientTokenMode()&&k.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,c)}},re=(od=o.statusIndicator)!=null?od:{},Pe=c=>{var f,h,y,P;return c==="idle"?(f=re.idleText)!=null?f:bn.idle:c==="connecting"?(h=re.connectingText)!=null?h:bn.connecting:c==="connected"?(y=re.connectedText)!=null?y:bn.connected:c==="error"?(P=re.errorText)!=null?P:bn.error:bn[c]};function nt(c,f,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let P=document.createElement("a");P.href=h.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=f,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=f}let{wrapper:ge,panel:de,pillRoot:Ve}=Cm(o),Ie=Sm(o,A()),{container:pe,body:X,messagesWrapper:$e,suggestions:St,textarea:J,sendButton:Oe,sendButtonWrapper:In,composerForm:Ot,statusText:cn,introTitle:Fn,introSubtitle:Zn,closeButton:N,iconHolder:ae,headerTitle:De,headerSubtitle:Qe,header:Ne,footer:_e,actionsRow:rt,leftActions:At,rightActions:_t}=Ie,Kt=Ie.setSendButtonMode,G=Ie.micButton,gt=Ie.micButtonWrapper,ot=Ie.attachmentButton,Ut=Ie.attachmentButtonWrapper,ie=Ie.attachmentInput,xe=Ie.attachmentPreviewsContainer;pe.classList.add("persona-relative"),X.classList.add("persona-relative");let Ct=12,Vt=()=>{var c;return(c=Ce.label)!=null?c:""},Zt=()=>{var c;return(c=Ce.iconName)!=null?c:"arrow-down"},xn=()=>Ce.enabled!==!1,Mt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Mt.type="button",Mt.style.display="none",Mt.setAttribute("data-persona-scroll-to-bottom","true");let Tt=b("span","persona-flex persona-items-center"),bt=b("span","");Mt.append(Tt,bt),pe.appendChild(Mt);let vt=()=>{let f=_e.style.display==="none"?0:_e.offsetHeight;Mt.style.bottom=`${f+Ct}px`};vt();let zt=()=>{let c=!!Vt();Mt.setAttribute("aria-label",Vt()||"Jump to latest"),Mt.title=Vt(),Mt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Tt.innerHTML="";let f=Ae(Zt(),"14px","currentColor",2);f?(Tt.appendChild(f),Tt.style.display=""):Tt.style.display="none",bt.textContent=Vt(),bt.style.display=c?"":"none"};zt();let et=null,On=null,eo=r.find(c=>c.renderHeader);if(eo!=null&&eo.renderHeader){let c=eo.renderHeader({config:o,defaultRenderer:()=>{let f=Lr({config:o,showClose:A()});return pa(pe,f,o),f.header},onClose:()=>Ht(!1,"user")});if(c){let f=pe.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Ne=c)}}let wn=()=>{var f,h,y,P;if(!Q)return;if(ce=!0,!he&&Q&&(he=Um({buffer:Q,getFullHistory:()=>Q.getAllFromStore(),onClose:()=>Nn(),config:o,plugins:r,getThroughput:()=>{var _;return(_=Te==null?void 0:Te.getMetric())!=null?_:{status:"idle"}}})),he&&(X.style.display="none",(f=_e.parentNode)==null||f.insertBefore(he.element,_e),he.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let _=(P=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:P.toggleButtonActive;_&&_.split(/\s+/).forEach($=>$&&mt.classList.add($))}let c=()=>{if(!ce)return;let _=Date.now();_-Ke>=200&&(he==null||he.update(),Ke=_),me=requestAnimationFrame(c)};Ke=0,me=requestAnimationFrame(c),Fo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,f,h;if(ce){if(ce=!1,he&&he.element.remove(),X.style.display="",mt){mt.style.boxShadow="";let y=(h=(f=(c=o.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&mt.classList.remove(P))}me!==null&&(cancelAnimationFrame(me),me=null),Fo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(le){let c=(sd=(rd=o.features)==null?void 0:rd.eventStream)==null?void 0:sd.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=b("button",f),mt.style.width="28px",mt.style.height="28px",mt.style.color=Ln.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let h=Ae("activity","18px","currentColor",1.5);h&&mt.appendChild(h);let y=Ie.clearChatButtonWrapper,P=Ie.closeButtonWrapper,_=y||P;_&&_.parentNode===Ne?Ne.insertBefore(mt,_):Ne.appendChild(mt),mt.addEventListener("click",()=>{ce?Nn():wn()})}let So=c=>{var y,P,_;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let $=c.querySelector("[data-persona-composer-form]");$!=null&&$.parentNode?$.parentNode.insertBefore(h,$):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let $=b("input");$.type="file",$.accept=((y=f.allowedTypes)!=null?y:$o).join(","),$.multiple=((P=f.maxFiles)!=null?P:4)>1,$.style.display="none",$.setAttribute("aria-label",(_=f.buttonTooltipText)!=null?_:"Attach files"),c.appendChild($)}},_n=r.find(c=>c.renderComposer);if(_n!=null&&_n.renderComposer){let c=o.composer,f=_n.renderComposer({config:o,defaultRenderer:()=>Vi({config:o}).footer,onSubmit:h=>{var $;if(!k||k.isStreaming())return;let y=h.trim(),P=($=et==null?void 0:et.hasAttachments())!=null?$:!1;if(!y&&!P)return;Cs();let _;P&&(_=[],_.push(...et.getContentParts()),y&&_.push(Pl(y))),k.sendMessage(y,{contentParts:_}),P&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ie==null||ie.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((ad=o.voiceRecognition)==null?void 0:ad.enabled)===!0?()=>{On==null||On()}:void 0});f&&(_e.replaceWith(f),_e=f)}let pr=c=>{let f=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),P=c.querySelector("[data-persona-composer-mic]"),_=c.querySelector("[data-persona-composer-status]");f&&(Ot=f),h&&(J=h),y&&(Oe=y),P&&(G=P,gt=P.parentElement),_&&(cn=_);let $=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(St=$);let q=c.querySelector(".persona-attachment-button");q&&(ot=q,Ut=q.parentElement),ie=c.querySelector('input[type="file"]'),xe=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(rt=O)};So(_e),pr(_e);let Rn=(pd=(id=o.layout)==null?void 0:id.contentMaxWidth)!=null?pd:M()?(dd=(cd=(ld=o.launcher)==null?void 0:ld.composerBar)==null?void 0:cd.contentMaxWidth)!=null?dd:"720px":void 0;if(Rn&&($e.style.maxWidth=Rn,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),Rn&&Ot&&!M()&&(Ot.style.maxWidth=Rn,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Rn&&St&&!M()&&(St.style.maxWidth=Rn,St.style.marginLeft="auto",St.style.marginRight="auto"),Rn&&xe&&!M()&&(xe.style.maxWidth=Rn,xe.style.marginLeft="auto",xe.style.marginRight="auto"),(ud=o.attachments)!=null&&ud.enabled&&ie&&xe){et=ta.fromConfig(o.attachments),et.setPreviewsContainer(xe),ie.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,f=pf(c);pe.appendChild(f)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},f=_=>{switch(_){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return St;case"composer":return Ot;case"footer-bottom":return cn;default:return null}},h=(_,$)=>{var q;switch(_){case"header-left":case"header-center":case"header-right":if(_==="header-left")Ne.insertBefore($,Ne.firstChild);else if(_==="header-right")Ne.appendChild($);else{let O=Ne.querySelector(".persona-flex-col");O?(q=O.parentNode)==null||q.insertBefore($,O.nextSibling):Ne.appendChild($)}break;case"body-top":{let O=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith($):X.insertBefore($,X.firstChild);break}case"body-bottom":X.appendChild($);break;case"footer-top":St.replaceWith($);break;case"footer-bottom":cn.replaceWith($);break;default:break}};for(let[_,$]of Object.entries(c))if($)try{let q=$({config:o,defaultContent:()=>f(_)});q&&h(_,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${_}":`,q)}})();let Uo=c=>{let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let _=h.getAttribute("data-bubble-type");_==="reasoning"?(ts.has(P)?ts.delete(P):ts.add(P),km(P,y)):_==="tool"&&(ns.has(P)?ns.delete(P):ns.add(P),Em(P,y,o)),fo.delete(P)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Uo(c))}),$e.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Uo(c))});let Ro=new Map;$e.addEventListener("click",c=>{var $;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let P=y.getAttribute("data-actions-for");if(!P)return;let _=h.getAttribute("data-action");if(_==="copy"){let O=k.getMessages().find(Se=>Se.id===P);if(O&&K.onCopy){let Se=O.content||"";navigator.clipboard.writeText(Se).then(()=>{h.classList.add("persona-message-action-success");let ue=Ae("check",14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let oe=Ae("copy",14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),K.onCopy(O)}}else if(_==="upvote"||_==="downvote"){let O=(($=Ro.get(P))!=null?$:null)===_,Se=_==="upvote"?"thumbs-up":"thumbs-down";if(O){Ro.delete(P),h.classList.remove("persona-message-action-active");let ue=Ae(Se,14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue))}else{let ue=_==="upvote"?"downvote":"upvote",oe=y.querySelector(`[data-action="${ue}"]`);if(oe){oe.classList.remove("persona-message-action-active");let Xe=Ae(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(oe.innerHTML="",oe.appendChild(Xe))}Ro.set(P,_),h.classList.add("persona-message-action-active");let be=Ae(Se,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let He=k.getMessages().find(tt=>tt.id===P);He&&K.onFeedback&&K.onFeedback({type:_,messageId:He.id,message:He})}}}),$e.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let _=h.getAttribute("data-approval-action");if(!_)return;let $=_==="approve"?"approved":"denied",O=k.getMessages().find(ue=>ue.id===P);if(!(O!=null&&O.approval))return;let Se=y.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?k.resolveWebMcpApproval(P,$):k.resolveApproval(O.approval,$)});let xt=null,Vn=null,$n={artifacts:[],selectedId:null},Cn=!1,Pt={current:null};$e.addEventListener("click",c=>{var oe,be,ke,He,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((ke=(be=(oe=o.features)==null?void 0:oe.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:ke.call(be,{type:"download",artifactId:y}))===!0)return;let _=k.getArtifactById(y),$=_==null?void 0:_.markdown,q=(_==null?void 0:_.title)||"artifact";if(!$){let Xe=h.closest("[data-open-artifact]"),lt=Xe==null?void 0:Xe.closest("[data-message-id]"),ct=lt==null?void 0:lt.getAttribute("data-message-id");if(ct){let Le=k.getMessages().find(Ue=>Ue.id===ct);if(Le!=null&&Le.rawContent)try{let Ue=JSON.parse(Le.rawContent);$=(He=Ue==null?void 0:Ue.props)==null?void 0:He.markdown,q=((tt=Ue==null?void 0:Ue.props)==null?void 0:tt.title)||q}catch{}}}if(!$)return;let O=new Blob([$],{type:"text/markdown"}),Se=URL.createObjectURL(O),ue=document.createElement("a");ue.href=Se,ue.download=`${q}.md`,ue.click(),URL.revokeObjectURL(Se)}),$e.addEventListener("click",c=>{var _,$,q;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((q=($=(_=o.features)==null?void 0:_.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:q.call($,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Cn=!1,k.selectArtifact(y),qn())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let to=Ie.composerOverlay,no=(c,f,h)=>{var q,O,Se,ue;let y=f.trim();if(!y||!Pt.current)return;let P=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",_=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:_,source:h.source},bubbles:!0,composed:!0})),as(to,P);let $=Pt.current.getMessages().find(oe=>{var be;return((be=oe.toolCall)==null?void 0:be.id)===P});(Se=$==null?void 0:$.agentMetadata)!=null&&Se.awaitingLocalTool?Pt.current.resolveAskUserQuestion($,(ue=h.structured)!=null?ue:y):Pt.current.sendMessage(y)},Un=c=>{var P;let f=Pt.current;if(!f)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=f.getMessages().find(_=>{var $;return(($=_.toolCall)==null?void 0:$.id)===h});y&&f.persistAskUserQuestionProgress(y,{answers:$i(c,y),currentIndex:co(c)})},zo=c=>Object.entries(c).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Po=c=>{var P,_,$;if(((_=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:_.groupedAutoAdvance)===!1)return;let f=co(c),h=ss(c);if(f>=h-1)return;let y=($=Pt.current)==null?void 0:$.getMessages().find(q=>{var O;return((O=q.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(zi(c,y,o,f+1),Un(c))};to.addEventListener("click",c=>{var _,$,q,O,Se,ue,oe,be,ke,He,tt,Xe,lt,ct;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let P=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),P==="dismiss"){let Re=(_=y.getAttribute("data-tool-call-id"))!=null?_:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),as(to,Re);let Le=($=Pt.current)==null?void 0:$.getMessages().find(Ue=>{var I;return((I=Ue.toolCall)==null?void 0:I.id)===Re});(q=Le==null?void 0:Le.agentMetadata)!=null&&q.awaitingLocalTool&&((O=Pt.current)==null||O.markAskUserQuestionResolved(Le),(Se=Pt.current)==null||Se.resolveAskUserQuestion(Le,"(dismissed)"));return}if(P==="pick"){let Re=h.getAttribute("data-option-label");if(!Re)return;let Le=y.getAttribute("data-multi-select")==="true",Ue=ir(y);if(Ue&&Le){let I=Rr(y)[co(y)],Ee=new Set(Array.isArray(I)?I:[]);Ee.has(Re)?Ee.delete(Re):Ee.add(Re),lr(y,Array.from(Ee)),Un(y);return}if(Ue){lr(y,Re),Un(y),Po(y);return}if(Le){let I=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",I?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!I);let Ee=y.querySelector('[data-ask-user-action="submit-multi"]');Ee&&(Ee.disabled=Ql(y).length===0);return}no(y,Re,{source:"pick",values:[Re]});return}if(P==="submit-multi"){let Re=Ql(y);if(Re.length===0)return;no(y,Re.join(", "),{source:"multi",values:Re});return}if(P==="open-free-text"){let Re=y.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Le=Re.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(P==="focus-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(P==="submit-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]'),Le=(ue=Re==null?void 0:Re.value)!=null?ue:"";if(!Le.trim())return;if(ir(y)){lr(y,Le.trim()),Un(y),Po(y);return}no(y,Le,{source:"free-text"});return}if(P==="next"||P==="back"){if(!Pt.current)return;let Re=(oe=y.getAttribute("data-tool-call-id"))!=null?oe:"",Le=Pt.current.getMessages().find(je=>{var we;return((we=je.toolCall)==null?void 0:we.id)===Re});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),I=(ke=(be=Ue==null?void 0:Ue.value)==null?void 0:be.trim())!=null?ke:"";if(I){let je=Rr(y)[co(y)];(typeof je!="string"||je!==I)&&lr(y,I)}let Ee=P==="next"?1:-1,We=co(y)+Ee;zi(y,Le,o,We),Un(y);return}if(P==="submit-all"){if(!Pt.current)return;let Re=(He=y.getAttribute("data-tool-call-id"))!=null?He:"",Le=Pt.current.getMessages().find(je=>{var we;return((we=je.toolCall)==null?void 0:we.id)===Re});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),I=(Xe=(tt=Ue==null?void 0:Ue.value)==null?void 0:tt.trim())!=null?Xe:"";I&&lr(y,I);let Ee=$i(y,Le);Pt.current.persistAskUserQuestionProgress(Le,{answers:Ee,currentIndex:co(y)});let We=zo(Ee);no(y,We||"(submitted)",{source:"submit-all",structured:Ee});return}if(P==="skip"){if(!Pt.current)return;let Re=(lt=y.getAttribute("data-tool-call-id"))!=null?lt:"",Le=Pt.current.getMessages().find(we=>{var Rt;return((Rt=we.toolCall)==null?void 0:Rt.id)===Re});if(!Le)return;let Ue=ir(y),I=co(y),Ee=ss(y),We=I>=Ee-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),as(to,Re),(ct=Le.agentMetadata)!=null&&ct.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(Le),Pt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}lr(y,"");let je=y.querySelector('[data-ask-free-text-input="true"]');if(je&&(je.value=""),We){let we=$i(y,Le),Rt=zo(we);no(y,Rt||"(skipped)",{source:"submit-all",structured:we});return}zi(y,Le,o,I+1),Un(y);return}}),to.addEventListener("keydown",c=>{var _;if(c.key!=="Enter")return;let h=c.target;if(!((_=h.matches)!=null&&_.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let P=h.value;if(P.trim()){if(ir(y)){lr(y,P.trim()),Un(y),Po(y);return}no(y,P,{source:"free-text"})}});let qo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=to.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),_=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];_&&(c.preventDefault(),_.click())};document.addEventListener("keydown",qo);let zn=null,Bt=null,Sn=null,oo=null,jo=()=>{};function Wo(){oo==null||oo(),oo=null}let Ko=()=>{var $;if(!zn||!Bt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let y=zn.firstElementChild;if(!y||y===Bt)return;let P=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${P}px`,Bt.style.zIndex="5";let _=y.offsetWidth-P/2;Bt.style.left=`${Math.max(0,_)}px`},Ao=()=>{},qn=()=>{var h,y,P,_,$;if(!xt||!po(o))return;ji(e,o),Ki(e,o),Ao();let c=(_=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?_:520,f=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),xt.update($n),Cn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),($=xt.backdrop)==null||$.classList.add("persona-hidden")):$n.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),jo()};if(po(o)){de.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(pe),xt=jm(o,{onSelect:h=>{var y;return(y=Pt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Cn=!0,qn()}}),xt.element.classList.add("persona-hidden"),zn=f,f.appendChild(c),f.appendChild(xt.element),xt.backdrop&&de.appendChild(xt.backdrop),de.appendChild(f),jo=()=>{var y,P,_,$;if(!zn||!xt)return;if(!(((_=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:_.resizable)===!0)){Sn==null||Sn(),Sn=null,Wo(),Bt&&(Bt.remove(),Bt=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!Bt){let q=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let O=e.ownerDocument,Se=($=O.defaultView)!=null?$:window,ue=oe=>{var lt,ct;if(!xt||oe.button!==0||e.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;oe.preventDefault(),Wo();let be=oe.clientX,ke=xt.element.getBoundingClientRect().width,He=(ct=(lt=o.features)==null?void 0:lt.artifacts)==null?void 0:ct.layout,tt=Re=>{let Le=zn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),I=Ue?0:Xm(zn,Se),Ee=Ue?0:q.getBoundingClientRect().width||6,We=ke-(Re.clientX-be),je=Qm(We,Le,I,Ee,He==null?void 0:He.resizableMinWidth,He==null?void 0:He.resizableMaxWidth);xt.element.style.width=`${je}px`,xt.element.style.maxWidth="none",Ko()},Xe=()=>{O.removeEventListener("pointermove",tt),O.removeEventListener("pointerup",Xe),O.removeEventListener("pointercancel",Xe),oo=null;try{q.releasePointerCapture(oe.pointerId)}catch{}};oo=Xe,O.addEventListener("pointermove",tt),O.addEventListener("pointerup",Xe),O.addEventListener("pointercancel",Xe);try{q.setPointerCapture(oe.pointerId)}catch{}};q.addEventListener("pointerdown",ue),Bt=q,zn.insertBefore(q,xt.element),Sn=()=>{q.removeEventListener("pointerdown",ue)}}if(Bt){let q=$n.artifacts.length>0&&!Cn;Bt.classList.toggle("persona-hidden",!q),Ko()}},Ao=()=>{var Se,ue,oe,be,ke,He,tt,Xe,lt,ct,Re,Le,Ue,I;if(!W||!xt||((ue=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?ue:!1)||mn(o)&&Lo(o).reveal==="emerge")return;let y=(oe=e.ownerDocument.defaultView)!=null?oe:window,P=(ke=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?ke:!0,_=(tt=(He=o.launcher)==null?void 0:He.mobileBreakpoint)!=null?tt:640;if(P&&y.innerWidth<=_||!Ym(o,W))return;let $=(ct=(lt=(Xe=o.launcher)==null?void 0:Xe.width)!=null?lt:o.launcherWidth)!=null?ct:lo,q=(I=(Ue=(Le=(Re=o.features)==null?void 0:Re.artifacts)==null?void 0:Le.layout)==null?void 0:Ue.expandedPanelWidth)!=null?I:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!Cn?(de.style.width=q,de.style.maxWidth=q):(de.style.width=$,de.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{qn()}),Vn.observe(de))}else de.appendChild(pe),M()&&Ve&&(Ie.peekBanner&&Ve.appendChild(Ie.peekBanner),Ve.appendChild(_e));e.appendChild(ge),Ve&&e.appendChild(Ve);let uo=()=>{var je,we,Rt,at,Qt,pn,Wt,Tn,un,Ze,dt,kn,gn,br,yr,vr,jr,Kr,qt,xr,nr,yt,Wn,_o,En,Bn,Dt,$t;if(M()){de.style.width="100%",de.style.maxWidth="100%";let Ft=(we=(je=o.launcher)==null?void 0:je.composerBar)!=null?we:{},jt=ge.dataset.state==="expanded",Hn=(Rt=Ft.expandedSize)!=null?Rt:"anchored";if(!(jt&&Hn!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let nn=(Qt=(at=o.theme)==null?void 0:at.components)==null?void 0:Qt.panel,Eo=Xa(o),Vo=(wr,Ka)=>{var Is;return wr==null||wr===""?Ka:(Is=Gr(Eo,wr))!=null?Is:wr},za="1px solid var(--persona-border)",qa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ja="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Vo(nn==null?void 0:nn.border,za),pe.style.borderRadius=Vo(nn==null?void 0:nn.borderRadius,ja),pe.style.boxShadow=Vo(nn==null?void 0:nn.shadow,qa),pe.style.overflow="hidden";return}let c=mn(o),f=(Wt=(pn=o.launcher)==null?void 0:pn.sidebarMode)!=null?Wt:!1,h=c||f||((un=(Tn=o.launcher)==null?void 0:Tn.fullHeight)!=null?un:!1),y=((Ze=o.launcher)==null?void 0:Ze.enabled)===!1,P=(kn=(dt=o.theme)==null?void 0:dt.components)==null?void 0:kn.panel,_=Xa(o),$=(Ft,jt)=>{var Hn;return Ft==null||Ft===""?jt:(Hn=Gr(_,Ft))!=null?Hn:Ft},q=(gn=e.ownerDocument.defaultView)!=null?gn:window,O=(yr=(br=o.launcher)==null?void 0:br.mobileFullscreen)!=null?yr:!0,Se=(jr=(vr=o.launcher)==null?void 0:vr.mobileBreakpoint)!=null?jr:640,ue=q.innerWidth<=Se,oe=O&&ue&&W,be=(qt=(Kr=o.launcher)==null?void 0:Kr.position)!=null?qt:"bottom-left",ke=be==="bottom-left"||be==="top-left",He=(nr=(xr=o.launcher)==null?void 0:xr.zIndex)!=null?nr:yn,tt=f||oe?"none":"1px solid var(--persona-border)",Xe=oe?"none":f?ke?"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&&!oe&&(Xe="none",tt="none");let lt=f||oe?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=$(P==null?void 0:P.border,tt),Re=$(P==null?void 0:P.shadow,Xe),Le=$(P==null?void 0:P.borderRadius,lt),Ue=X.scrollTop;e.style.cssText="",ge.style.cssText="",de.style.cssText="",pe.style.cssText="",X.style.cssText="",_e.style.cssText="";let I=()=>{var jt;if(Ue<=0)return;((jt=X.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(X.scrollTop===Ue)return;let Hn=X.scrollHeight-X.clientHeight;Hn<=0||(X.scrollTop=Math.min(Ue,Hn))})};if(oe){ge.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"),ge.style.cssText=`
30
+ `,w.addEventListener("click",()=>{p=v,B.forEach((M,A)=>{let E=A<v;M.classList.toggle("selected",E),M.setAttribute("aria-checked",A===v-1?"true":"false")})}),B.push(w),L.appendChild(w)}f.appendChild(L);let I=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),v.appendChild(I),f.appendChild(v)}let D=document.createElement("div");D.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=i,F.addEventListener("click",()=>{n==null||n(),u.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(p===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let v=(I==null?void 0:I.value.trim())||void 0;await t(p,v),u.remove()}catch(v){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),D.appendChild(F),D.appendChild(H),f.appendChild(D),u.appendChild(f),u}function cg(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let 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 L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=r,x.appendChild(L),g.appendChild(x);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=l;let F=document.createElement("span");F.className="persona-feedback-label-high",F.textContent=u,I.appendChild(D),I.appendChild(F);let H=document.createElement("div");H.className="persona-feedback-numbers";let v=[];for(let O=0;O<=10;O++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${O} out of 10`),U.textContent=String(O),U.dataset.rating=String(O),O<=6?U.classList.add("persona-feedback-detractor"):O<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{f=O,v.forEach((j,ge)=>{j.classList.toggle("selected",ge===O),j.setAttribute("aria-checked",ge===O?"true":"false")})}),v.push(U),H.appendChild(U)}B.appendChild(I),B.appendChild(H),g.appendChild(B);let w=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),O.appendChild(w),g.appendChild(O)}let M=document.createElement("div");M.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{n==null||n(),p.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=a,E.addEventListener("click",async()=>{if(f===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let O=(w==null?void 0:w.value.trim())||void 0;await t(f,O),p.remove()}catch(O){E.disabled=!1,E.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),M.appendChild(A),M.appendChild(E),g.appendChild(M),p.appendChild(g),p}var ls="persona-chat-history",iy=30*1e3,ly={"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 cy(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=ly[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Gi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function dy(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function py(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var cc=e=>!e||typeof e!="object"?{}:{...e},dg=e=>e.map(t=>({...t,streaming:!1})),pg=(e,t,n)=>{let o=e!=null&&e.markdown?ii(e.markdown):null,r=li(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,u,p;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):o?d=o(a):d=Gs(a),r?r(d):d}};function ug(e){var i,d,l,u;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=Ae(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let p=b("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var mg=(e,t,n)=>{var Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td;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=ku(t),r=rc.getForInstance(o.plugins);o.components&&Wr.registerAll(o.components);let s=tg(),i=o.persistState===!1?null:(Pc=o.storageAdapter)!=null?Pc:og(),d={},l=null,u=!1,p=c=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:y}=m;return y&&(u=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return p(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=p(m);h.metadata&&(d=cc(h.metadata)),(Wc=h.messages)!=null&&Wc.length&&(o={...o,initialMessages:h.messages}),(Bc=h.artifacts)!=null&&Bc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Hc=h.selectedArtifactId)!=null?Hc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=p({messages:[],metadata:{}});(Dc=c.messages)!=null&&Dc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,g=c=>{var h;d=(h=c({...d}))!=null?h:{},Nr()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ac],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ba.message,ba.messageAndClick],L=ic({parsers:x,handlers:C,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let B=(Oc=(Fc=o.launcher)==null?void 0:Fc.enabled)!=null?Oc:!0,I=(_c=(Nc=o.launcher)==null?void 0:Nc.autoExpand)!=null?_c:!1,D=(Vc=o.autoFocusInput)!=null?Vc:!1,F=I,H=B,v=(Uc=($c=o.layout)==null?void 0:$c.header)==null?void 0:Uc.layout,w=!1,M=()=>ca(o),A=()=>B||M(),E=M()?!1:B?I:!0,O=!1,U=null,j=()=>{O=!0,U&&clearTimeout(U),U=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},ge=pg(o,L,j),se=(qc=(zc=o.features)==null?void 0:zc.showReasoning)!=null?qc:!0,ye=(Kc=(jc=o.features)==null?void 0:jc.showToolCalls)!=null?Kc:!0,le=(Yc=(Gc=o.features)==null?void 0:Gc.showEventStreamToggle)!=null?Yc:!1,Ce=(Qc=(Xc=o.features)==null?void 0:Xc.scrollToBottom)!=null?Qc:{},ve=`${(Zc=typeof o.persistState=="object"?(Jc=o.persistState)==null?void 0:Jc.keyPrefix:void 0)!=null?Zc:"persona-"}event-stream`,ee=le?new fa(ve):null,Me=(nd=(td=(ed=o.features)==null?void 0:ed.eventStream)==null?void 0:td.maxEvents)!=null?nd:2e3,Q=le?new ga(Me,ee):null,Te=le?new ha:null,he=null,ce=!1,me=null,Ke=0;ee==null||ee.open().then(()=>Q==null?void 0:Q.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let K={onCopy:c=>{var m,h;s.emit("message:copy",c),k!=null&&k.isClientTokenMode()&&k.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(m=o.messageActions)==null?void 0:m.onCopy)==null||h.call(m,c)},onFeedback:c=>{var m,h;s.emit("message:feedback",c),k!=null&&k.isClientTokenMode()&&k.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(m=o.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,c)}},re=(od=o.statusIndicator)!=null?od:{},Pe=c=>{var m,h,y,W;return c==="idle"?(m=re.idleText)!=null?m:bn.idle:c==="connecting"?(h=re.connectingText)!=null?h:bn.connecting:c==="connected"?(y=re.connectedText)!=null?y:bn.connected:c==="error"?(W=re.errorText)!=null?W:bn.error:bn[c]};function nt(c,m,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let W=document.createElement("a");W.href=h.idleLink,W.target="_blank",W.rel="noopener noreferrer",W.textContent=m,W.style.color="inherit",W.style.textDecoration="none",c.appendChild(W)}else c.textContent=m}let{wrapper:fe,panel:de,pillRoot:Ve}=Am(o),Ie=Tm(o,A()),{container:pe,body:X,messagesWrapper:$e,suggestions:St,textarea:J,sendButton:Oe,sendButtonWrapper:In,composerForm:Ot,statusText:cn,introTitle:Fn,introSubtitle:Zn,closeButton:_,iconHolder:ae,headerTitle:De,headerSubtitle:Qe,header:Ne,footer:_e,actionsRow:rt,leftActions:At,rightActions:_t}=Ie,Kt=Ie.setSendButtonMode,G=Ie.micButton,ft=Ie.micButtonWrapper,ot=Ie.attachmentButton,Ut=Ie.attachmentButtonWrapper,ie=Ie.attachmentInput,xe=Ie.attachmentPreviewsContainer;pe.classList.add("persona-relative"),X.classList.add("persona-relative");let Ct=12,Vt=()=>{var c;return(c=Ce.label)!=null?c:""},Zt=()=>{var c;return(c=Ce.iconName)!=null?c:"arrow-down"},xn=()=>Ce.enabled!==!1,Mt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Mt.type="button",Mt.style.display="none",Mt.setAttribute("data-persona-scroll-to-bottom","true");let Tt=b("span","persona-flex persona-items-center"),bt=b("span","");Mt.append(Tt,bt),pe.appendChild(Mt);let vt=()=>{let m=_e.style.display==="none"?0:_e.offsetHeight;Mt.style.bottom=`${m+Ct}px`};vt();let zt=()=>{let c=!!Vt();Mt.setAttribute("aria-label",Vt()||"Jump to latest"),Mt.title=Vt(),Mt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Tt.innerHTML="";let m=Ae(Zt(),"14px","currentColor",2);m?(Tt.appendChild(m),Tt.style.display=""):Tt.style.display="none",bt.textContent=Vt(),bt.style.display=c?"":"none"};zt();let et=null,On=null,eo=r.find(c=>c.renderHeader);if(eo!=null&&eo.renderHeader){let c=eo.renderHeader({config:o,defaultRenderer:()=>{let m=Lr({config:o,showClose:A()});return pa(pe,m,o),m.header},onClose:()=>Ht(!1,"user")});if(c){let m=pe.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Ne=c)}}let wn=()=>{var m,h,y,W;if(!Q)return;if(ce=!0,!he&&Q&&(he=qm({buffer:Q,getFullHistory:()=>Q.getAllFromStore(),onClose:()=>Nn(),config:o,plugins:r,getThroughput:()=>{var V;return(V=Te==null?void 0:Te.getMetric())!=null?V:{status:"idle"}}})),he&&(X.style.display="none",(m=_e.parentNode)==null||m.insertBefore(he.element,_e),he.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let V=(W=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:W.toggleButtonActive;V&&V.split(/\s+/).forEach($=>$&&mt.classList.add($))}let c=()=>{if(!ce)return;let V=Date.now();V-Ke>=200&&(he==null||he.update(),Ke=V),me=requestAnimationFrame(c)};Ke=0,me=requestAnimationFrame(c),Fo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,m,h;if(ce){if(ce=!1,he&&he.element.remove(),X.style.display="",mt){mt.style.boxShadow="";let y=(h=(m=(c=o.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(W=>W&&mt.classList.remove(W))}me!==null&&(cancelAnimationFrame(me),me=null),Fo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(le){let c=(sd=(rd=o.features)==null?void 0:rd.eventStream)==null?void 0:sd.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=b("button",m),mt.style.width="28px",mt.style.height="28px",mt.style.color=Ln.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let h=Ae("activity","18px","currentColor",1.5);h&&mt.appendChild(h);let y=Ie.clearChatButtonWrapper,W=Ie.closeButtonWrapper,V=y||W;V&&V.parentNode===Ne?Ne.insertBefore(mt,V):Ne.appendChild(mt),mt.addEventListener("click",()=>{ce?Nn():wn()})}let So=c=>{var y,W,V;let m=o.attachments;if(!(m!=null&&m.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let $=c.querySelector("[data-persona-composer-form]");$!=null&&$.parentNode?$.parentNode.insertBefore(h,$):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let $=b("input");$.type="file",$.accept=((y=m.allowedTypes)!=null?y:$o).join(","),$.multiple=((W=m.maxFiles)!=null?W:4)>1,$.style.display="none",$.setAttribute("aria-label",(V=m.buttonTooltipText)!=null?V:"Attach files"),c.appendChild($)}},_n=r.find(c=>c.renderComposer);if(_n!=null&&_n.renderComposer){let c=o.composer,m=_n.renderComposer({config:o,defaultRenderer:()=>Vi({config:o}).footer,onSubmit:h=>{var $;if(!k||k.isStreaming())return;let y=h.trim(),W=($=et==null?void 0:et.hasAttachments())!=null?$:!1;if(!y&&!W)return;Cs();let V;W&&(V=[],V.push(...et.getContentParts()),y&&V.push(Pl(y))),k.sendMessage(y,{contentParts:V}),W&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ie==null||ie.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((ad=o.voiceRecognition)==null?void 0:ad.enabled)===!0?()=>{On==null||On()}:void 0});m&&(_e.replaceWith(m),_e=m)}let pr=c=>{let m=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),W=c.querySelector("[data-persona-composer-mic]"),V=c.querySelector("[data-persona-composer-status]");m&&(Ot=m),h&&(J=h),y&&(Oe=y),W&&(G=W,ft=W.parentElement),V&&(cn=V);let $=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(St=$);let q=c.querySelector(".persona-attachment-button");q&&(ot=q,Ut=q.parentElement),ie=c.querySelector('input[type="file"]'),xe=c.querySelector(".persona-attachment-previews");let N=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(rt=N)};So(_e),pr(_e);let Rn=(pd=(id=o.layout)==null?void 0:id.contentMaxWidth)!=null?pd:M()?(dd=(cd=(ld=o.launcher)==null?void 0:ld.composerBar)==null?void 0:cd.contentMaxWidth)!=null?dd:"720px":void 0;if(Rn&&($e.style.maxWidth=Rn,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),Rn&&Ot&&!M()&&(Ot.style.maxWidth=Rn,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Rn&&St&&!M()&&(St.style.maxWidth=Rn,St.style.marginLeft="auto",St.style.marginRight="auto"),Rn&&xe&&!M()&&(xe.style.maxWidth=Rn,xe.style.marginLeft="auto",xe.style.marginRight="auto"),(ud=o.attachments)!=null&&ud.enabled&&ie&&xe){et=ta.fromConfig(o.attachments),et.setPreviewsContainer(xe),ie.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,m=ug(c);pe.appendChild(m)}(()=>{var y,W;let c=(W=(y=o.layout)==null?void 0:y.slots)!=null?W:{},m=V=>{switch(V){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return St;case"composer":return Ot;case"footer-bottom":return cn;default:return null}},h=(V,$)=>{var q;switch(V){case"header-left":case"header-center":case"header-right":if(V==="header-left")Ne.insertBefore($,Ne.firstChild);else if(V==="header-right")Ne.appendChild($);else{let N=Ne.querySelector(".persona-flex-col");N?(q=N.parentNode)==null||q.insertBefore($,N.nextSibling):Ne.appendChild($)}break;case"body-top":{let N=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith($):X.insertBefore($,X.firstChild);break}case"body-bottom":X.appendChild($);break;case"footer-top":St.replaceWith($);break;case"footer-bottom":cn.replaceWith($);break;default:break}};for(let[V,$]of Object.entries(c))if($)try{let q=$({config:o,defaultContent:()=>m(V)});q&&h(V,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${V}":`,q)}})();let Uo=c=>{let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let W=y.getAttribute("data-message-id");if(!W)return;let V=h.getAttribute("data-bubble-type");V==="reasoning"?(ts.has(W)?ts.delete(W):ts.add(W),Mm(W,y)):V==="tool"&&(ns.has(W)?ns.delete(W):ns.add(W),Lm(W,y,o)),go.delete(W)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Uo(c))}),$e.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Uo(c))});let Ro=new Map;$e.addEventListener("click",c=>{var $;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let W=y.getAttribute("data-actions-for");if(!W)return;let V=h.getAttribute("data-action");if(V==="copy"){let N=k.getMessages().find(Se=>Se.id===W);if(N&&K.onCopy){let Se=N.content||"";navigator.clipboard.writeText(Se).then(()=>{h.classList.add("persona-message-action-success");let ue=Ae("check",14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let oe=Ae("copy",14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),K.onCopy(N)}}else if(V==="upvote"||V==="downvote"){let N=(($=Ro.get(W))!=null?$:null)===V,Se=V==="upvote"?"thumbs-up":"thumbs-down";if(N){Ro.delete(W),h.classList.remove("persona-message-action-active");let ue=Ae(Se,14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue))}else{let ue=V==="upvote"?"downvote":"upvote",oe=y.querySelector(`[data-action="${ue}"]`);if(oe){oe.classList.remove("persona-message-action-active");let Xe=Ae(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(oe.innerHTML="",oe.appendChild(Xe))}Ro.set(W,V),h.classList.add("persona-message-action-active");let be=Ae(Se,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let He=k.getMessages().find(tt=>tt.id===W);He&&K.onFeedback&&K.onFeedback({type:V,messageId:He.id,message:He})}}}),$e.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let W=y.getAttribute("data-message-id");if(!W)return;let V=h.getAttribute("data-approval-action");if(!V)return;let $=V==="approve"?"approved":"denied",N=k.getMessages().find(ue=>ue.id===W);if(!(N!=null&&N.approval))return;let Se=y.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?k.resolveWebMcpApproval(W,$):k.resolveApproval(N.approval,$)});let xt=null,Vn=null,$n={artifacts:[],selectedId:null},Cn=!1,Pt={current:null};$e.addEventListener("click",c=>{var oe,be,ke,He,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((ke=(be=(oe=o.features)==null?void 0:oe.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:ke.call(be,{type:"download",artifactId:y}))===!0)return;let V=k.getArtifactById(y),$=V==null?void 0:V.markdown,q=(V==null?void 0:V.title)||"artifact";if(!$){let Xe=h.closest("[data-open-artifact]"),lt=Xe==null?void 0:Xe.closest("[data-message-id]"),ct=lt==null?void 0:lt.getAttribute("data-message-id");if(ct){let Le=k.getMessages().find(Ue=>Ue.id===ct);if(Le!=null&&Le.rawContent)try{let Ue=JSON.parse(Le.rawContent);$=(He=Ue==null?void 0:Ue.props)==null?void 0:He.markdown,q=((tt=Ue==null?void 0:Ue.props)==null?void 0:tt.title)||q}catch{}}}if(!$)return;let N=new Blob([$],{type:"text/markdown"}),Se=URL.createObjectURL(N),ue=document.createElement("a");ue.href=Se,ue.download=`${q}.md`,ue.click(),URL.revokeObjectURL(Se)}),$e.addEventListener("click",c=>{var V,$,q;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((q=($=(V=o.features)==null?void 0:V.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:q.call($,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Cn=!1,k.selectArtifact(y),qn())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let to=Ie.composerOverlay,no=(c,m,h)=>{var q,N,Se,ue;let y=m.trim();if(!y||!Pt.current)return;let W=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",V=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:W,answer:y,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?y.split(", "):[y],isFreeText:V,source:h.source},bubbles:!0,composed:!0})),as(to,W);let $=Pt.current.getMessages().find(oe=>{var be;return((be=oe.toolCall)==null?void 0:be.id)===W});(Se=$==null?void 0:$.agentMetadata)!=null&&Se.awaitingLocalTool?Pt.current.resolveAskUserQuestion($,(ue=h.structured)!=null?ue:y):Pt.current.sendMessage(y)},Un=c=>{var W;let m=Pt.current;if(!m)return;let h=(W=c.getAttribute("data-tool-call-id"))!=null?W:"",y=m.getMessages().find(V=>{var $;return(($=V.toolCall)==null?void 0:$.id)===h});y&&m.persistAskUserQuestionProgress(y,{answers:$i(c,y),currentIndex:co(c)})},zo=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Po=c=>{var W,V,$;if(((V=(W=o.features)==null?void 0:W.askUserQuestion)==null?void 0:V.groupedAutoAdvance)===!1)return;let m=co(c),h=ss(c);if(m>=h-1)return;let y=($=Pt.current)==null?void 0:$.getMessages().find(q=>{var N;return((N=q.toolCall)==null?void 0:N.id)===c.getAttribute("data-tool-call-id")});y&&(zi(c,y,o,m+1),Un(c))};to.addEventListener("click",c=>{var V,$,q,N,Se,ue,oe,be,ke,He,tt,Xe,lt,ct;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let W=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),W==="dismiss"){let Re=(V=y.getAttribute("data-tool-call-id"))!=null?V:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),as(to,Re);let Le=($=Pt.current)==null?void 0:$.getMessages().find(Ue=>{var R;return((R=Ue.toolCall)==null?void 0:R.id)===Re});(q=Le==null?void 0:Le.agentMetadata)!=null&&q.awaitingLocalTool&&((N=Pt.current)==null||N.markAskUserQuestionResolved(Le),(Se=Pt.current)==null||Se.resolveAskUserQuestion(Le,"(dismissed)"));return}if(W==="pick"){let Re=h.getAttribute("data-option-label");if(!Re)return;let Le=y.getAttribute("data-multi-select")==="true",Ue=ir(y);if(Ue&&Le){let R=Rr(y)[co(y)],Ee=new Set(Array.isArray(R)?R:[]);Ee.has(Re)?Ee.delete(Re):Ee.add(Re),lr(y,Array.from(Ee)),Un(y);return}if(Ue){lr(y,Re),Un(y),Po(y);return}if(Le){let R=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",R?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!R);let Ee=y.querySelector('[data-ask-user-action="submit-multi"]');Ee&&(Ee.disabled=Ql(y).length===0);return}no(y,Re,{source:"pick",values:[Re]});return}if(W==="submit-multi"){let Re=Ql(y);if(Re.length===0)return;no(y,Re.join(", "),{source:"multi",values:Re});return}if(W==="open-free-text"){let Re=y.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Le=Re.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(W==="focus-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(W==="submit-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]'),Le=(ue=Re==null?void 0:Re.value)!=null?ue:"";if(!Le.trim())return;if(ir(y)){lr(y,Le.trim()),Un(y),Po(y);return}no(y,Le,{source:"free-text"});return}if(W==="next"||W==="back"){if(!Pt.current)return;let Re=(oe=y.getAttribute("data-tool-call-id"))!=null?oe:"",Le=Pt.current.getMessages().find(je=>{var we;return((we=je.toolCall)==null?void 0:we.id)===Re});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),R=(ke=(be=Ue==null?void 0:Ue.value)==null?void 0:be.trim())!=null?ke:"";if(R){let je=Rr(y)[co(y)];(typeof je!="string"||je!==R)&&lr(y,R)}let Ee=W==="next"?1:-1,We=co(y)+Ee;zi(y,Le,o,We),Un(y);return}if(W==="submit-all"){if(!Pt.current)return;let Re=(He=y.getAttribute("data-tool-call-id"))!=null?He:"",Le=Pt.current.getMessages().find(je=>{var we;return((we=je.toolCall)==null?void 0:we.id)===Re});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),R=(Xe=(tt=Ue==null?void 0:Ue.value)==null?void 0:tt.trim())!=null?Xe:"";R&&lr(y,R);let Ee=$i(y,Le);Pt.current.persistAskUserQuestionProgress(Le,{answers:Ee,currentIndex:co(y)});let We=zo(Ee);no(y,We||"(submitted)",{source:"submit-all",structured:Ee});return}if(W==="skip"){if(!Pt.current)return;let Re=(lt=y.getAttribute("data-tool-call-id"))!=null?lt:"",Le=Pt.current.getMessages().find(we=>{var Rt;return((Rt=we.toolCall)==null?void 0:Rt.id)===Re});if(!Le)return;let Ue=ir(y),R=co(y),Ee=ss(y),We=R>=Ee-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),as(to,Re),(ct=Le.agentMetadata)!=null&&ct.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(Le),Pt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}lr(y,"");let je=y.querySelector('[data-ask-free-text-input="true"]');if(je&&(je.value=""),We){let we=$i(y,Le),Rt=zo(we);no(y,Rt||"(skipped)",{source:"submit-all",structured:we});return}zi(y,Le,o,R+1),Un(y);return}}),to.addEventListener("keydown",c=>{var V;if(c.key!=="Enter")return;let h=c.target;if(!((V=h.matches)!=null&&V.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let W=h.value;if(W.trim()){if(ir(y)){lr(y,W.trim()),Un(y),Po(y);return}no(y,W,{source:"free-text"})}});let qo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=to.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),V=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];V&&(c.preventDefault(),V.click())};document.addEventListener("keydown",qo);let zn=null,Bt=null,Sn=null,oo=null,jo=()=>{};function Wo(){oo==null||oo(),oo=null}let Ko=()=>{var $;if(!zn||!Bt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let y=zn.firstElementChild;if(!y||y===Bt)return;let W=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${W}px`,Bt.style.zIndex="5";let V=y.offsetWidth-W/2;Bt.style.left=`${Math.max(0,V)}px`},Ao=()=>{},qn=()=>{var h,y,W,V,$;if(!xt||!po(o))return;ji(e,o),Ki(e,o),Ao();let c=(V=(W=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:W.narrowHostMaxWidth)!=null?V:520,m=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),xt.update($n),Cn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),($=xt.backdrop)==null||$.classList.add("persona-hidden")):$n.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),jo()};if(po(o)){de.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(pe),xt=Gm(o,{onSelect:h=>{var y;return(y=Pt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Cn=!0,qn()}}),xt.element.classList.add("persona-hidden"),zn=m,m.appendChild(c),m.appendChild(xt.element),xt.backdrop&&de.appendChild(xt.backdrop),de.appendChild(m),jo=()=>{var y,W,V,$;if(!zn||!xt)return;if(!(((V=(W=(y=o.features)==null?void 0:y.artifacts)==null?void 0:W.layout)==null?void 0:V.resizable)===!0)){Sn==null||Sn(),Sn=null,Wo(),Bt&&(Bt.remove(),Bt=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!Bt){let q=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let N=e.ownerDocument,Se=($=N.defaultView)!=null?$:window,ue=oe=>{var lt,ct;if(!xt||oe.button!==0||e.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;oe.preventDefault(),Wo();let be=oe.clientX,ke=xt.element.getBoundingClientRect().width,He=(ct=(lt=o.features)==null?void 0:lt.artifacts)==null?void 0:ct.layout,tt=Re=>{let Le=zn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),R=Ue?0:Jm(zn,Se),Ee=Ue?0:q.getBoundingClientRect().width||6,We=ke-(Re.clientX-be),je=Zm(We,Le,R,Ee,He==null?void 0:He.resizableMinWidth,He==null?void 0:He.resizableMaxWidth);xt.element.style.width=`${je}px`,xt.element.style.maxWidth="none",Ko()},Xe=()=>{N.removeEventListener("pointermove",tt),N.removeEventListener("pointerup",Xe),N.removeEventListener("pointercancel",Xe),oo=null;try{q.releasePointerCapture(oe.pointerId)}catch{}};oo=Xe,N.addEventListener("pointermove",tt),N.addEventListener("pointerup",Xe),N.addEventListener("pointercancel",Xe);try{q.setPointerCapture(oe.pointerId)}catch{}};q.addEventListener("pointerdown",ue),Bt=q,zn.insertBefore(q,xt.element),Sn=()=>{q.removeEventListener("pointerdown",ue)}}if(Bt){let q=$n.artifacts.length>0&&!Cn;Bt.classList.toggle("persona-hidden",!q),Ko()}},Ao=()=>{var Se,ue,oe,be,ke,He,tt,Xe,lt,ct,Re,Le,Ue,R;if(!B||!xt||((ue=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?ue:!1)||mn(o)&&Lo(o).reveal==="emerge")return;let y=(oe=e.ownerDocument.defaultView)!=null?oe:window,W=(ke=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?ke:!0,V=(tt=(He=o.launcher)==null?void 0:He.mobileBreakpoint)!=null?tt:640;if(W&&y.innerWidth<=V||!Qm(o,B))return;let $=(ct=(lt=(Xe=o.launcher)==null?void 0:Xe.width)!=null?lt:o.launcherWidth)!=null?ct:lo,q=(R=(Ue=(Le=(Re=o.features)==null?void 0:Re.artifacts)==null?void 0:Le.layout)==null?void 0:Ue.expandedPanelWidth)!=null?R:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!Cn?(de.style.width=q,de.style.maxWidth=q):(de.style.width=$,de.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{qn()}),Vn.observe(de))}else de.appendChild(pe),M()&&Ve&&(Ie.peekBanner&&Ve.appendChild(Ie.peekBanner),Ve.appendChild(_e));e.appendChild(fe),Ve&&e.appendChild(Ve);let uo=()=>{var je,we,Rt,at,Qt,pn,Wt,Tn,un,Ze,dt,kn,fn,br,yr,vr,jr,Kr,qt,xr,nr,yt,Wn,_o,En,Bn,Dt,$t;if(M()){de.style.width="100%",de.style.maxWidth="100%";let Ft=(we=(je=o.launcher)==null?void 0:je.composerBar)!=null?we:{},jt=fe.dataset.state==="expanded",Hn=(Rt=Ft.expandedSize)!=null?Rt:"anchored";if(!(jt&&Hn!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let nn=(Qt=(at=o.theme)==null?void 0:at.components)==null?void 0:Qt.panel,Eo=Xa(o),Vo=(wr,Ka)=>{var Is;return wr==null||wr===""?Ka:(Is=Gr(Eo,wr))!=null?Is:wr},za="1px solid var(--persona-border)",qa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ja="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Vo(nn==null?void 0:nn.border,za),pe.style.borderRadius=Vo(nn==null?void 0:nn.borderRadius,ja),pe.style.boxShadow=Vo(nn==null?void 0:nn.shadow,qa),pe.style.overflow="hidden";return}let c=mn(o),m=(Wt=(pn=o.launcher)==null?void 0:pn.sidebarMode)!=null?Wt:!1,h=c||m||((un=(Tn=o.launcher)==null?void 0:Tn.fullHeight)!=null?un:!1),y=((Ze=o.launcher)==null?void 0:Ze.enabled)===!1,W=(kn=(dt=o.theme)==null?void 0:dt.components)==null?void 0:kn.panel,V=Xa(o),$=(Ft,jt)=>{var Hn;return Ft==null||Ft===""?jt:(Hn=Gr(V,Ft))!=null?Hn:Ft},q=(fn=e.ownerDocument.defaultView)!=null?fn:window,N=(yr=(br=o.launcher)==null?void 0:br.mobileFullscreen)!=null?yr:!0,Se=(jr=(vr=o.launcher)==null?void 0:vr.mobileBreakpoint)!=null?jr:640,ue=q.innerWidth<=Se,oe=N&&ue&&B,be=(qt=(Kr=o.launcher)==null?void 0:Kr.position)!=null?qt:"bottom-left",ke=be==="bottom-left"||be==="top-left",He=(nr=(xr=o.launcher)==null?void 0:xr.zIndex)!=null?nr:yn,tt=m||oe?"none":"1px solid var(--persona-border)",Xe=oe?"none":m?ke?"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&&!oe&&(Xe="none",tt="none");let lt=m||oe?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=$(W==null?void 0:W.border,tt),Re=$(W==null?void 0:W.shadow,Xe),Le=$(W==null?void 0:W.borderRadius,lt),Ue=X.scrollTop;e.style.cssText="",fe.style.cssText="",de.style.cssText="",pe.style.cssText="",X.style.cssText="",_e.style.cssText="";let R=()=>{var jt;if(Ue<=0)return;((jt=X.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(X.scrollTop===Ue)return;let Hn=X.scrollHeight-X.clientHeight;Hn<=0||(X.scrollTop=Math.min(Ue,Hn))})};if(oe){fe.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"),fe.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:o}var wi=class e{constructor(t={},n){this.config=t;this
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0",C=!0,I();return}let Ee=(Wn=(yt=o==null?void 0:o.launcher)==null?void 0:yt.width)!=null?Wn:o==null?void 0:o.launcherWidth,We=Ee!=null?Ee:lo;if(!f&&!c)y&&h?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=We,de.style.maxWidth=We);else if(c)if(Lo(o).reveal==="emerge"){let jt=Lo(o).width;de.style.width=jt,de.style.maxWidth=jt}else de.style.width="100%",de.style.maxWidth="100%";if(Ao(),de.style.boxShadow=Re,de.style.borderRadius=Le,pe.style.border=ct,pe.style.borderRadius=Le,c&&!oe&&(P==null?void 0:P.border)===void 0&&(pe.style.border="none",Lo(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",y&&(e.style.width="100%"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",y&&(ge.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",de.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",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0"),ge.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&&!y&&!c&&((_o=Co[be])!=null?_o:Co["bottom-right"]).split(" ").forEach(jt=>ge.classList.add(jt)),f){let Ft=(Bn=(En=o.launcher)==null?void 0:En.sidebarWidth)!=null?Bn:"420px";ge.style.cssText=`
66
+ `,X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0",w=!0,R();return}let Ee=(Wn=(yt=o==null?void 0:o.launcher)==null?void 0:yt.width)!=null?Wn:o==null?void 0:o.launcherWidth,We=Ee!=null?Ee:lo;if(!m&&!c)y&&h?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=We,de.style.maxWidth=We);else if(c)if(Lo(o).reveal==="emerge"){let jt=Lo(o).width;de.style.width=jt,de.style.maxWidth=jt}else de.style.width="100%",de.style.maxWidth="100%";if(Ao(),de.style.boxShadow=Re,de.style.borderRadius=Le,pe.style.border=ct,pe.style.borderRadius=Le,c&&!oe&&(W==null?void 0:W.border)===void 0&&(pe.style.border="none",Lo(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",y&&(e.style.width="100%"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",y&&(fe.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",de.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",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0"),fe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!y&&!c&&((_o=Co[be])!=null?_o:Co["bottom-right"]).split(" ").forEach(jt=>fe.classList.add(jt)),m){let Ft=(Bn=(En=o.launcher)==null?void 0:En.sidebarWidth)!=null?Bn:"420px";fe.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
@@ -104,7 +104,7 @@ _Details: ${n.message}_`:o}var wi=class e{constructor(t={},n){this.config=t;this
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!y&&!c){let Ft="max-height: -moz-available !important; max-height: stretch !important;",jt=f?"":"padding-top: 1.25em !important;",Hn=f?"":`z-index: ${($t=(Dt=o.launcher)==null?void 0:Dt.zIndex)!=null?$t:yn} !important;`;ge.style.cssText+=Ft+jt+Hn}I()};uo(),Yr(e,o),ji(e,o),Ki(e,o);let ht=[];ht.push(()=>{document.removeEventListener("keydown",qo)});let Gt=null,Yt=null;ht.push(()=>{Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null}),Vn&&ht.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),ht.push(()=>{Sn==null||Sn(),Sn=null,Wo(),Bt&&(Bt.remove(),Bt=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),le&&ht.push(()=>{me!==null&&(cancelAnimationFrame(me),me=null),he==null||he.destroy(),he=null,Q==null||Q.destroy(),Q=null,ee=null});let jn=null,Go=()=>{jn&&(jn(),jn=null),o.colorScheme==="auto"&&(jn=Ru(()=>{Yr(e,o)}))};Go(),ht.push(()=>{jn&&(jn(),jn=null)});let ro=(md=o.features)==null?void 0:md.streamAnimation;if(ro!=null&&ro.type&&ro.type!=="none"){let c=sa(ro.type,ro.plugins);c&&(Dl(c,e),ht.push(()=>bm(e)))}let mo=Nm(St),Kn=null,k,Gn=!1,fo=pm(),Bo=new Map,To=new Map,ms=0,go=Ti(),ho=0,bo=null,Ho=!1,ur=!1,Ma=4,fs=24,La=80,Or=new Map,ft={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},gs=(gd=(fd=o.voiceRecognition)==null?void 0:fd.autoResume)!=null?gd:!1,so=c=>{s.emit("voice:state",{active:ft.active,source:c,timestamp:Date.now()})},Pn=()=>{m(c=>({...c,voiceState:{active:ft.active,timestamp:Date.now(),manuallyDeactivated:ft.manuallyDeactivated}}))},Ia=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=cc(d.voiceState),f=!!c.active,h=Number((P=c.timestamp)!=null?P:0);ft.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-h<ry&&setTimeout(()=>{var _,$;ft.active||(ft.manuallyDeactivated=!1,(($=(_=o.voiceRecognition)==null?void 0:_.provider)==null?void 0:$.type)==="runtype"?k.toggleVoice().then(()=>{ft.active=k.isVoiceActive(),so("restore"),k.isVoiceActive()&&R()}):hr("restore"))},1e3)},Ra=()=>k?cf(k.getMessages()).filter(c=>!c.__skipPersist):[];function Nr(c){if(!(i!=null&&i.save))return;let h={messages:c?cf(c):k?Ra():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Do=null,Pa=()=>ge.querySelector("#persona-scroll-container")||X,mr=()=>{Do!==null&&(cancelAnimationFrame(Do),Do=null),Ho=!1},hs=()=>{bo!==null&&(cancelAnimationFrame(bo),bo=null),ur=!1,mr()},Fo=()=>{if(!xn()||ce){Mt.parentNode&&Mt.remove(),Mt.style.display="none";return}Mt.parentNode!==pe&&pe.appendChild(Mt),vt();let c=na(X)>0;Mt.style.display=go.isFollowing()||!c?"none":""},bs=()=>{go.pause()&&(hs(),Fo())},Yo=()=>{go.resume(),Fo()},Xo=(c=!1)=>{go.isFollowing()&&(!c&&!Gn||(bo!==null&&(cancelAnimationFrame(bo),bo=null),ur=!0,bo=requestAnimationFrame(()=>{bo=null,ur=!1,go.isFollowing()&&Wa(Pa(),c?220:140)})))},Wa=(c,f=500)=>{let h=c.scrollTop,y=na(c),P=y-h;if(Math.abs(P)<1){ho=c.scrollTop;return}if(Math.abs(P)>=La){mr(),Ho=!0,c.scrollTop=y,ho=c.scrollTop,Ho=!1;return}mr();let _=performance.now();Ho=!0;let $=O=>1-Math.pow(1-O,3),q=O=>{if(!go.isFollowing()){mr();return}let Se=na(c);Se!==y&&(y=Se,P=y-h);let ue=O-_,oe=Math.min(ue/f,1),be=$(oe),ke=h+P*be;c.scrollTop=ke,ho=c.scrollTop,oe<1?Do=requestAnimationFrame(q):(c.scrollTop=y,ho=c.scrollTop,Do=null,Ho=!1)};Do=requestAnimationFrame(q)},Ba=c=>{let f=new Map;c.forEach(h=>{let y=Or.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Or.clear(),f.forEach((h,y)=>{Or.set(y,h)})},fr=(c,f,h)=>{var Xe,lt,ct,Re,Le,Ue;let y=document.createElement("div"),_=(()=>{var Ee;let I=r.find(We=>We.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((Ee=o.loadingIndicator)!=null&&Ee.render)return o.loadingIndicator.render})(),$=(I,Ee)=>Ee==null?!1:typeof Ee=="string"?(I.textContent=Ee,!0):(I.appendChild(Ee),!0),q=new Set,O=new Set,Se=r.some(I=>I.renderAskUserQuestion),ue=[],oe=[],be=o.enableComponentStreaming!==!1;if(f.forEach(I=>{var Tn,un,Ze,dt,kn,gn,br,yr,vr,jr,Kr,qt,xr,nr;q.add(I.id);let Ee=Se&&Ir(I),We=!Ee&&I.role==="assistant"&&!I.variant&&be&&rf(I);if(!We&&To.has(I.id)){let yt=c.querySelector(`#wrapper-${I.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),To.delete(I.id)}let je=Ir(I)?`:${(Tn=I.agentMetadata)!=null&&Tn.askUserQuestionAnswered?"a":"u"}:${(un=I.agentMetadata)!=null&&un.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",we=dm(I,ms)+je,Rt=Ee||We?null:um(fo,I.id,we);if(Rt){y.appendChild(Rt.cloneNode(!0)),Ir(I)&&((Ze=I.toolCall)!=null&&Ze.id)&&((dt=I.agentMetadata)==null?void 0:dt.awaitingLocalTool)===!0&&!((kn=I.agentMetadata)!=null&&kn.askUserQuestionAnswered)&&(O.add(I.toolCall.id),Ui(I,o,Ie.composerOverlay));return}let at=null,Qt=r.find(yt=>!!(I.variant==="reasoning"&&yt.renderReasoning||I.variant==="tool"&&yt.renderToolCall||I.variant==="approval"&&yt.renderApproval||!I.variant&&yt.renderMessage)),pn=(gn=o.layout)==null?void 0:gn.messages;if(Ir(I)&&((br=I.agentMetadata)==null?void 0:br.askUserQuestionAnswered)===!0){Bo.delete(I.id);let yt=c.querySelector(`#wrapper-${I.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if(Ir(I)&&((vr=(yr=o.features)==null?void 0:yr.askUserQuestion)==null?void 0:vr.enabled)!==!1){let yt=r.find(Wn=>typeof Wn.renderAskUserQuestion=="function");if(yt&&Pt.current){let Wn=Bo.get(I.id),_o=Wn!==we,En=null;if(_o){let{payload:$t,complete:Ft}=rs(I),jt=I.id,Hn=()=>{var Xn;return(Xn=Pt.current)==null?void 0:Xn.getMessages().find(nn=>nn.id===jt)};En=yt.renderAskUserQuestion({message:I,payload:$t,complete:Ft,resolve:Xn=>{var Eo;let nn=Hn();nn&&((Eo=Pt.current)==null||Eo.resolveAskUserQuestion(nn,Xn))},dismiss:()=>{var nn,Eo,Vo;let Xn=Hn();(nn=Xn==null?void 0:Xn.agentMetadata)!=null&&nn.awaitingLocalTool&&((Eo=Pt.current)==null||Eo.markAskUserQuestionResolved(Xn),(Vo=Pt.current)==null||Vo.resolveAskUserQuestion(Xn,"(dismissed)"))},config:o})}let Bn=Wn!=null;if(_o&&En===null&&!Bn){((jr=I.agentMetadata)==null?void 0:jr.awaitingLocalTool)===!0&&!((Kr=I.agentMetadata)!=null&&Kr.askUserQuestionAnswered)&&(O.add(I.toolCall.id),Ui(I,o,Ie.composerOverlay));return}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${I.id}`,Dt.setAttribute("data-wrapper-id",I.id),Dt.setAttribute("data-ask-plugin-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),y.appendChild(Dt),ue.push({messageId:I.id,fingerprint:we,bubble:En});return}else{((qt=I.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((xr=I.agentMetadata)!=null&&xr.askUserQuestionAnswered)&&(O.add(I.toolCall.id),Ui(I,o,Ie.composerOverlay));return}}else if(Qt)if(I.variant==="reasoning"&&I.reasoning&&Qt.renderReasoning){if(!se)return;at=Qt.renderReasoning({message:I,defaultRenderer:()=>Ul(I,o),config:o})}else if(I.variant==="tool"&&I.toolCall&&Qt.renderToolCall){if(!ye)return;at=Qt.renderToolCall({message:I,defaultRenderer:()=>zl(I,o),config:o})}else if(I.variant==="approval"&&I.approval&&Qt.renderApproval){if(o.approval===!1)return;at=Qt.renderApproval({message:I,defaultRenderer:()=>Jl(I,o),config:o})}else Qt.renderMessage&&(at=Qt.renderMessage({message:I,defaultRenderer:()=>{let yt=$l(I,h,pn,o.messageActions,K,{loadingIndicatorRenderer:_,widgetConfig:o});return I.role!=="user"&&nc(yt,I,o,k),yt},config:o}));if(!at&&We){let yt=sf(I);if(yt){let Wn=To.get(I.id),_o=Wn!==we,En=o.wrapComponentDirectiveInBubble!==!1,Bn=null;if(_o){let Dt=nf(yt,{config:o,message:I,transform:h});if(Dt)if(En){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-${I.id}`,$t.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let Ft=document.createElement("div");Ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ft.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(Ft)}$t.appendChild(Dt),Bn=$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-${I.id}`,$t.setAttribute("data-message-id",I.id),$t.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let Ft=document.createElement("div");Ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ft.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(Ft)}$t.appendChild(Dt),Bn=$t}}if(Bn||Wn!=null){let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${I.id}`,Dt.setAttribute("data-wrapper-id",I.id),Dt.setAttribute("data-component-directive-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),En||Dt.classList.add("persona-w-full"),y.appendChild(Dt),oe.push({messageId:I.id,fingerprint:we,bubble:Bn});return}}}if(!at)if(I.variant==="reasoning"&&I.reasoning){if(!se)return;at=Ul(I,o)}else if(I.variant==="tool"&&I.toolCall){if(!ye)return;at=zl(I,o)}else if(I.variant==="approval"&&I.approval){if(o.approval===!1)return;at=Jl(I,o)}else{let yt=(nr=o.layout)==null?void 0:nr.messages;yt!=null&&yt.renderUserMessage&&I.role==="user"?at=yt.renderUserMessage({message:I,config:o,streaming:!!I.streaming}):yt!=null&&yt.renderAssistantMessage&&I.role==="assistant"?at=yt.renderAssistantMessage({message:I,config:o,streaming:!!I.streaming}):at=$l(I,h,yt,o.messageActions,K,{loadingIndicatorRenderer:_,widgetConfig:o}),I.role!=="user"&&at&&nc(at,I,o,k)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${I.id}`,Wt.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Wt.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(at),mm(fo,I.id,we,Wt),y.appendChild(Wt)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let We=Ee.getAttribute("data-persona-ask-sheet-for");We&&!O.has(We)&&as(Ie.composerOverlay,We)}),(lt=(Xe=o.features)==null?void 0:Xe.toolCallDisplay)!=null&&lt.grouped){let I=[],Ee=[];f.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&ye){Ee.push(We);return}Ee.length>1&&I.push(Ee),Ee=[]}),Ee.length>1&&I.push(Ee),I.forEach((We,je)=>{var un,Ze;let we=We.map(dt=>Array.from(y.children).find(kn=>kn instanceof HTMLElement&&kn.getAttribute("data-wrapper-id")===dt.id)).filter(dt=>!!dt);if(we.length<2)return;let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id=`wrapper-tool-group-${je}-${We[0].id}`,Rt.setAttribute("data-wrapper-id",`tool-group-${je}-${We[0].id}`);let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Qt=document.createElement("div");Qt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let pn=`Called ${We.length} tools`,Wt=(Ze=(un=o.toolCall)==null?void 0:un.renderGroupedSummary)==null?void 0:Ze.call(un,{messages:We,toolCalls:We.map(dt=>dt.toolCall).filter(dt=>!!dt),defaultSummary:pn,config:o});$(Qt,Wt)||(Qt.textContent=pn);let Tn=document.createElement("div");Tn.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Qt,Tn),Rt.appendChild(at),we[0].before(Rt),we.forEach((dt,kn)=>{let gn=document.createElement("div");gn.className="persona-tool-group-item persona-relative",gn.setAttribute("data-persona-tool-group-item","true"),kn<we.length-1&&gn.setAttribute("data-persona-tool-group-connector","true"),gn.appendChild(dt),Tn.appendChild(gn)})})}fm(fo,q);let ke=f.some(I=>I.role==="assistant"&&I.streaming),He=f[f.length-1],tt=(He==null?void 0:He.role)==="assistant"&&!He.streaming&&He.variant!=="approval";if(Gn&&f.some(I=>I.role==="user")&&!ke&&!tt){let I={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},Ee=r.find(je=>je.renderLoadingIndicator),We=null;if(Ee!=null&&Ee.renderLoadingIndicator&&(We=Ee.renderLoadingIndicator(I)),We===null&&((ct=o.loadingIndicator)!=null&&ct.render)&&(We=o.loadingIndicator.render(I)),We===null&&(We=ua()),We){let je=document.createElement("div"),we=((Re=o.loadingIndicator)==null?void 0:Re.showBubble)!==!1;je.className=we?["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(" "),je.setAttribute("data-typing-indicator","true"),je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",je.appendChild(We);let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id="wrapper-typing-indicator",Rt.setAttribute("data-wrapper-id","typing-indicator"),Rt.appendChild(je),y.appendChild(Rt)}}if(!Gn&&f.length>0){let I=f[f.length-1],Ee={config:o,lastMessage:I,messageCount:f.length},We=r.find(we=>we.renderIdleIndicator),je=null;if(We!=null&&We.renderIdleIndicator&&(je=We.renderIdleIndicator(Ee)),je===null&&((Le=o.loadingIndicator)!=null&&Le.renderIdle)&&(je=o.loadingIndicator.renderIdle(Ee)),je){let we=document.createElement("div"),Rt=((Ue=o.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;we.className=Rt?["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(" "),we.setAttribute("data-idle-indicator","true"),we.appendChild(je);let at=document.createElement("div");at.className="persona-flex",at.id="wrapper-idle-indicator",at.setAttribute("data-wrapper-id","idle-indicator"),at.appendChild(we),y.appendChild(at)}}if(Si(c,y),ue.length>0)for(let{messageId:I,fingerprint:Ee,bubble:We}of ue){let je=c.querySelector(`#wrapper-${I}`);je&&We!==null&&(je.replaceChildren(We),je.setAttribute("data-bubble-fp",Ee),Bo.set(I,Ee))}if(Bo.size>0)for(let I of Bo.keys())q.has(I)||Bo.delete(I);if(oe.length>0)for(let{messageId:I,fingerprint:Ee,bubble:We}of oe){let je=c.querySelector(`#wrapper-${I}`);je&&We!==null&&(je.replaceChildren(We),je.setAttribute("data-bubble-fp",Ee),To.set(I,Ee))}if(To.size>0)for(let I of To.keys())q.has(I)||To.delete(I)},Qo=null,Ha=()=>{var h;if(Qo)return;let c=y=>{let P=y.composedPath();P.includes(ge)||Ve&&P.includes(Ve)||Ht(!1,"user")};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ys=()=>{var f;if(!Qo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Qo,!0),Qo=null};ht.push(()=>ys());let Jo=null,Da=()=>{var h;if(Jo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ht(!1,"user"))};Jo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},vs=()=>{var f;if(!Jo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Jo,!0),Jo=null};ht.push(()=>vs());let Zo=!1,xs=new Set,Fa=()=>{var f,h,y,P;let c=(y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Oo=()=>{var lt,ct,Re,Le;if(!M())return;let c=Ie.peekBanner,f=Ie.peekTextNode;if(!c||!f)return;if(E){c.classList.remove("persona-pill-peek--visible");return}let h=(lt=k==null?void 0:k.getMessages())!=null?lt:[],y;for(let Ue=h.length-1;Ue>=0;Ue--){let I=h[Ue];if(I.role==="assistant"&&I.content){y=I;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,_=!!y.streaming,$=Fa(),q=Mi($),O=q.type!=="none"?sa(q.type,$==null?void 0:$.plugins):null,Se=((ct=O==null?void 0:O.isAnimating)==null?void 0:ct.call(O,y))===!0,ue=O!==null&&(_||Se);ue&&O&&!xs.has(O.name)&&(Dl(O,e),xs.add(O.name));let oe=ue&&(O!=null&&O.containerClass)?O.containerClass:null,be=(Re=f.dataset.personaPeekStreamClass)!=null?Re:null;be&&be!==oe&&(f.classList.remove(be),delete f.dataset.personaPeekStreamClass),oe&&be!==oe&&(f.classList.add(oe),f.dataset.personaPeekStreamClass=oe),ue?(f.style.setProperty("--persona-stream-step",`${q.speed}ms`),f.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let ke=ue?Li(P,q.buffer,O,y,_):P;if(ue&&q.placeholder==="skeleton"&&_&&(!ke||!ke.trim())){let Ue=document.createElement("div"),I=ia();I.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(I),Si(f,Ue)}else{let Ue=Math.max(0,ke.length-100),I=ke.length>100?ke.slice(-100):ke,Ee=Gs(I);if(!ue||!O){let We=ke.length>100?`\u2026${I}`:I;f.textContent!==We&&(f.textContent=We)}else{let We=Ee;(O.wrap==="char"||O.wrap==="word")&&(We=aa(Ee,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:Ue}));let je=document.createElement("div");if(je.innerHTML=We,O.useCaret&&I.length>0){let we=Ii(),Rt=je.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=Rt[Rt.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(we,at.nextSibling):je.appendChild(we)}Si(f,je),(Le=O.onAfterRender)==null||Le.call(O,{container:f,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Xe=Gn||Zo;c.classList.toggle("persona-pill-peek--visible",Xe)};if(M()){let c=Ie.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",y),ht.push(()=>{c.removeEventListener("pointerdown",y)})}let f=()=>{Zo||(Zo=!0,Oo())},h=()=>{Zo&&(Zo=!1,Oo())};de.addEventListener("pointerenter",f),de.addEventListener("pointerleave",h),ht.push(()=>{de.removeEventListener("pointerenter",f),de.removeEventListener("pointerleave",h)}),Ve&&(Ve.addEventListener("pointerenter",f),Ve.addEventListener("pointerleave",h),ht.push(()=>{Ve.removeEventListener("pointerenter",f),Ve.removeEventListener("pointerleave",h)}))}let Oa=c=>{var be,ke,He,tt,Xe,lt,ct,Re;let f=(ke=(be=o.launcher)==null?void 0:be.composerBar)!=null?ke:{},h=(He=f.expandedSize)!=null?He:"anchored",y=(tt=f.bottomOffset)!=null?tt:"16px",P=f.collapsedMaxWidth,_=(Xe=f.expandedMaxWidth)!=null?Xe:"880px",$=(lt=f.expandedTopOffset)!=null?lt:"5vh",q=(ct=f.modalMaxWidth)!=null?ct:"880px",O=(Re=f.modalMaxHeight)!=null?Re:"min(90vh, 800px)",Se="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",oe=ge.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",Ve){let Le=Ve.style;Le.bottom=y,Le.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=q,oe.maxWidth=Se,oe.maxHeight=O,oe.height=O;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${y} + ${ue})`,oe.top=$,oe.width=_,oe.maxWidth=Se}},er=()=>{var O,Se,ue,oe,be,ke,He,tt;if(!A())return;if(M()){let lt=(ue=((Se=(O=o.launcher)==null?void 0:O.composerBar)!=null?Se:{}).expandedSize)!=null?ue:"anchored",ct=E?"expanded":"collapsed";ge.dataset.state=ct,ge.dataset.expandedSize=lt,Ve&&(Ve.dataset.state=ct,Ve.dataset.expandedSize=lt),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Oa(E),pe.style.display=E?"flex":"none",uo(),E?(Ha(),Da()):(ys(),vs()),Oo();return}let c=mn(o),f=(oe=e.ownerDocument.defaultView)!=null?oe:window,h=(ke=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?ke:640,y=(tt=(He=o.launcher)==null?void 0:He.mobileFullscreen)!=null?tt:!0,P=f.innerWidth<=h,_=y&&P&&W,$=Lo(o).reveal;E?(ge.style.removeProperty("display"),ge.style.display=c?"flex":"",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Ye?Ye.element.style.display="none":Je&&(Je.style.display="none")):(c?c&&($==="overlay"||$==="push")&&!_?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.setProperty("display","none","important"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.display="",ge.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Ye?Ye.element.style.display=c?"none":"":Je&&(Je.style.display=c?"none":""))},Ht=(c,f="user")=>{var _,$;if(!A()||E===c)return;let h=E;E=c,er();let y=(()=>{var He,tt,Xe,lt,ct,Re,Le,Ue,I,Ee;let q=(tt=(He=o.launcher)==null?void 0:He.sidebarMode)!=null?tt:!1,O=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,Se=(ct=(lt=o.launcher)==null?void 0:lt.mobileFullscreen)!=null?ct:!0,ue=(Le=(Re=o.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Le:640,oe=O.innerWidth<=ue,be=mn(o)&&Se&&oe,ke=M()&&((Ee=(I=(Ue=o.launcher)==null?void 0:Ue.composerBar)==null?void 0:I.expandedSize)!=null?Ee:"fullscreen")==="fullscreen";return q||Se&&oe&&W||be||ke})();if(E&&y){if(!Gt){let q=e.getRootNode(),O=q instanceof ShadowRoot?q.host:e.closest(".persona-host");O&&(Gt=Fl(O,($=(_=o.launcher)==null?void 0:_.zIndex)!=null?$:yn))}Yt||(Yt=Ol(e.ownerDocument))}else E||(Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null);E&&(Xt(),Xo(!0));let P={open:E,source:f,timestamp:Date.now()};E&&!h?s.emit("widget:opened",P):!E&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:E,launcherEnabled:W,voiceActive:ft.active,streaming:k.isStreaming()})},_r=c=>{Kt(c?"stop":"send"),G&&(G.disabled=c),mo.buttons.forEach(f=>{f.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Vr=()=>{ft.active||J&&J.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Vr(),200)});let ws=()=>{var h,y,P,_,$,q,O,Se,ue,oe,be;Fn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Zn.textContent=(_=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",J.placeholder=(q=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?q:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let ke=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=ke?"":"none",ke?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((ue=(Se=o.sendButton)==null?void 0:Se.useIcon)!=null&&ue)&&!(k!=null&&k.isStreaming())&&(Oe.textContent=(be=(oe=o.copy)==null?void 0:oe.sendButtonLabel)!=null?be:"Send"),J.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',J.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(f=>({...f,sessionId:c}))}});let ko=null,Na=()=>{ko==null&&(ko=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(ko),ko=null;return}let f=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=pi(f-y))})},100))};if(k=new wi(o,{onMessagesChanged(c){fr($e,c,fe),Na(),k&&(c.some(P=>P.role==="user")?mo.render([],k,J,c):mo.render(o.suggestionChips,k,J,c,o.suggestionChipsConfig)),Xo(!Gn),Ba(c);let f=[...c].reverse().find(y=>y.role==="user"),h=ft.lastUserMessageId;f&&f.id!==h&&(ft.lastUserMessageId=f.id,s.emit("user:message",f)),ft.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Nr(c),Oo()},onStatusChanged(c){var y;let f=(y=o.statusIndicator)!=null?y:{};nt(cn,(P=>{var _,$,q,O;return P==="idle"?(_=f.idleText)!=null?_:bn.idle:P==="connecting"?($=f.connectingText)!=null?$:bn.connecting:P==="connected"?(q=f.connectedText)!=null?q:bn.connected:P==="error"?(O=f.errorText)!=null?O:bn.error:bn[P]})(c),f,c)},onStreamingChanged(c){Gn=c,_r(c),k&&fr($e,k.getMessages(),fe),c||Xo(!0),Oo()},onVoiceStatusChanged(c){var f,h;if(((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":Y(),te();break;case"speaking":Y(),ne();break;default:c==="idle"&&k.isBargeInActive()?(Y(),R(),G==null||G.setAttribute("aria-label","End voice session")):(ft.active=!1,Y(),so("system"),Pn());break}},onArtifactsState(c){$n=c,qn(),Nr()}}),Pt.current=k,((bd=(hd=o.voiceRecognition)==null?void 0:hd.provider)==null?void 0:bd.type)==="runtype")try{k.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&k.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Q||o.onSSEEvent)&&k.setSSEEventCallback((c,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,f),Te==null||Te.processEvent(c,f),Q==null||Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,h,y;c&&(c.metadata&&(d=cc(c.metadata),L.syncFromMetadata()),(f=c.messages)!=null&&f.length&&k.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&k.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Cs=()=>{var f,h,y;!M()||E||!((y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ht(!0,"auto")},Ss=c=>{var P;if(c.preventDefault(),k.isStreaming()){k.cancel(),Te==null||Te.reset(),he==null||he.update();return}let f=J.value.trim(),h=(P=et==null?void 0:et.hasAttachments())!=null?P:!1;if(!f&&!h)return;Cs();let y;h&&(y=[],y.push(...et.getContentParts()),f&&y.push(Pl(f))),J.value="",J.style.height="auto",gr(),k.sendMessage(f,{contentParts:y}),h&&et.clearAttachments()},_a=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},$r={...Ai},Ur=!1,gr=()=>{$r={...Ai}},Va=()=>k.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),$a=c=>{if(!J)return;Ur=!0,J.value=c,J.dispatchEvent(new Event("input",{bubbles:!0})),Ur=!1;let f=J.value.length;J.setSelectionRange(f,f)},As=()=>{Ur||gr()},Ts=c=>{if(J){if(_a()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=J.selectionStart===0&&J.selectionEnd===0,h=cm({direction:c.key==="ArrowUp"?"up":"down",history:Va(),currentValue:J.value,atStart:f,state:$r});if($r=h.state,h.handled){c.preventDefault(),h.value!==void 0&&$a(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(k.isStreaming()){c.preventDefault();return}gr(),c.preventDefault(),Oe.click()}}},ks=c=>{c.key!=="Escape"||c.isComposing||k.isStreaming()&&c.composedPath().includes(pe)&&(k.cancel(),Te==null||Te.reset(),he==null||he.update(),gr(),c.preventDefault(),c.stopImmediatePropagation())},Es=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let f=ay(c.clipboardData);f.length!==0&&(c.preventDefault(),await et.handleFiles(f))},An=null,Yn=!1,No=null,st=null,Ms=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,hr=(c="user")=>{var _,$,q,O,Se,ue,oe;if(Yn||k.isStreaming())return;let f=Ms();if(!f)return;An=new f;let y=($=((_=o.voiceRecognition)!=null?_:{}).pauseDuration)!=null?$:2e3;An.continuous=!0,An.interimResults=!0,An.lang="en-US";let P=J.value;An.onresult=be=>{let ke="",He="";for(let Xe=0;Xe<be.results.length;Xe++){let lt=be.results[Xe],ct=lt[0].transcript;lt.isFinal?ke+=ct+" ":He=ct}let tt=P+ke+He;J.value=tt,No&&clearTimeout(No),(ke||He)&&(No=window.setTimeout(()=>{let Xe=J.value.trim();Xe&&An&&Yn&&(yo(),J.value="",J.style.height="auto",k.sendMessage(Xe,{viaVoice:!0}))},y))},An.onerror=be=>{be.error!=="no-speech"&&yo()},An.onend=()=>{if(Yn){let be=J.value.trim();be&&be!==P.trim()&&(J.value="",J.style.height="auto",k.sendMessage(be,{viaVoice:!0})),yo()}};try{if(An.start(),Yn=!0,ft.active=!0,c!=="system"&&(ft.manuallyDeactivated=!1),so(c),Pn(),G){let be=(q=o.voiceRecognition)!=null?q:{};st={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(O=be.iconName)!=null?O:"mic",iconSize:parseFloat((oe=(ue=be.iconSize)!=null?ue:(Se=o.sendButton)==null?void 0:Se.size)!=null?oe:"40")||24};let ke=be.recordingBackgroundColor,He=be.recordingIconColor,tt=be.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=ke!=null?ke:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=He!=null?He:"var(--persona-voice-recording-indicator, #ffffff)",He){let Xe=G.querySelector("svg");Xe&&Xe.setAttribute("stroke",He)}tt&&(G.style.borderColor=tt),G.setAttribute("aria-label","Stop voice recognition")}}catch{yo("system")}},yo=(c="user")=>{if(Yn){if(Yn=!1,No&&(clearTimeout(No),No=null),An){try{An.stop()}catch{}An=null}if(ft.active=!1,so(c),Pn(),G){if(G.classList.remove("persona-voice-recording"),st){G.style.backgroundColor=st.backgroundColor,G.style.color=st.color,G.style.borderColor=st.borderColor;let f=G.querySelector("svg");f&&f.setAttribute("stroke",st.color||"currentColor"),st=null}G.setAttribute("aria-label","Start voice recognition")}}},zr=(c,f)=>{var lt,ct,Re,Le,Ue,I,Ee,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((lt=c==null?void 0:c.provider)==null?void 0:lt.type)==="runtype";if(!(h||y))return null;let _=b("div","persona-send-button-wrapper"),$=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button",$.setAttribute("aria-label","Start voice recognition");let q=(ct=c==null?void 0:c.iconName)!=null?ct:"mic",O=(Re=f==null?void 0:f.size)!=null?Re:"40px",Se=(Le=c==null?void 0:c.iconSize)!=null?Le:O,ue=parseFloat(Se)||24,oe=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:f==null?void 0:f.backgroundColor,be=(I=c==null?void 0:c.iconColor)!=null?I:f==null?void 0:f.textColor;$.style.width=Se,$.style.height=Se,$.style.minWidth=Se,$.style.minHeight=Se,$.style.fontSize="18px",$.style.lineHeight="1",be?$.style.color=be:$.style.color="var(--persona-text, #111827)";let He=Ae(q,ue,be||"currentColor",1.5);He?$.appendChild(He):$.textContent="\u{1F3A4}",oe?$.style.backgroundColor=oe:$.style.backgroundColor="",c!=null&&c.borderWidth&&($.style.borderWidth=c.borderWidth,$.style.borderStyle="solid"),c!=null&&c.borderColor&&($.style.borderColor=c.borderColor),c!=null&&c.paddingX&&($.style.paddingLeft=c.paddingX,$.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&($.style.paddingTop=c.paddingY,$.style.paddingBottom=c.paddingY),_.appendChild($);let tt=(Ee=c==null?void 0:c.tooltipText)!=null?Ee:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&tt){let je=b("div","persona-send-button-tooltip");je.textContent=tt,_.appendChild(je)}return{micButton:$,micButtonWrapper:_}},ze=()=>{var f,h,y,P,_;if(!G||st)return;let c=(f=o.voiceRecognition)!=null?f:{};st={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((_=(P=c.iconSize)!=null?P:(y=o.sendButton)==null?void 0:y.size)!=null?_:"40")||24}},T=(c,f)=>{var _,$,q,O,Se;if(!G)return;let h=G.querySelector("svg");h&&h.remove();let y=(Se=st==null?void 0:st.iconSize)!=null?Se:parseFloat((O=(q=(_=o.voiceRecognition)==null?void 0:_.iconSize)!=null?q:($=o.sendButton)==null?void 0:$.size)!=null?O:"40")||24,P=Ae(c,y,f,1.5);P&&G.appendChild(P)},z=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},R=()=>{var P;if(!G)return;ze();let c=(P=o.voiceRecognition)!=null?P:{},f=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(z(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let _=G.querySelector("svg");_&&_.setAttribute("stroke",h)}y&&(G.style.borderColor=y),G.setAttribute("aria-label","Stop voice recognition")},te=()=>{var q,O,Se,ue,oe,be,ke,He;if(!G)return;ze();let c=(q=o.voiceRecognition)!=null?q:{},f=k.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ue=(Se=c.processingIconColor)!=null?Se:st==null?void 0:st.color)!=null?ue:"",P=(be=(oe=c.processingBackgroundColor)!=null?oe:st==null?void 0:st.backgroundColor)!=null?be:"",_=(He=(ke=c.processingBorderColor)!=null?ke:st==null?void 0:st.borderColor)!=null?He:"";z(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=P,G.style.borderColor=_;let $=y||"currentColor";G.style.color=$,T(h,$),G.setAttribute("aria-label","Processing voice input"),f==="none"&&(G.style.cursor="default")},ne=()=>{var Se,ue,oe,be,ke,He,tt,Xe,lt,ct,Re,Le;if(!G)return;ze();let c=(Se=o.voiceRecognition)!=null?Se:{},f=k.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,P=(He=c.speakingIconColor)!=null?He:f==="barge-in"?(be=(oe=c.recordingIconColor)!=null?oe:st==null?void 0:st.color)!=null?be:"":(ke=st==null?void 0:st.color)!=null?ke:"",_=(lt=c.speakingBackgroundColor)!=null?lt:f==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=st==null?void 0:st.backgroundColor)!=null?Xe:"",$=(Le=c.speakingBorderColor)!=null?Le:f==="barge-in"?(ct=c.recordingBorderColor)!=null?ct:"":(Re=st==null?void 0:st.borderColor)!=null?Re:"";z(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=_,G.style.borderColor=$;let q=P||"currentColor";G.style.color=q,T(y,q);let O=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",O),f==="none"&&(G.style.cursor="default"),f==="barge-in"&&G.classList.add("persona-voice-recording")},Y=()=>{var c,f,h;G&&(z(),st&&(G.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",G.style.color=(f=st.color)!=null?f:"",G.style.borderColor=(h=st.borderColor)!=null?h:"",T(st.iconName,st.color||"currentColor"),st=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},qe=()=>{var c,f;if(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let h=k.getVoiceStatus(),y=k.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){k.stopVoicePlayback();return}if(k.isBargeInActive()){k.stopVoicePlayback(),k.deactivateBargeIn().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Pn(),so("user"),Y()});return}k.toggleVoice().then(()=>{ft.active=k.isVoiceActive(),ft.manuallyDeactivated=!k.isVoiceActive(),Pn(),so("user"),k.isVoiceActive()?R():Y()});return}if(Yn){let h=J.value.trim();ft.manuallyDeactivated=!0,Pn(),yo("user"),h&&(J.value="",J.style.height="auto",k.sendMessage(h))}else ft.manuallyDeactivated=!1,Pn(),hr("user")};On=qe,G&&(G.addEventListener("click",qe),ht.push(()=>{var c,f;((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(k.isVoiceActive()&&k.toggleVoice(),Y()):yo("system"),G&&G.removeEventListener("click",qe)}));let Fe=s.on("assistant:complete",()=>{gs&&(ft.active||ft.manuallyDeactivated||gs==="assistant"&&!ft.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!ft.active&&!ft.manuallyDeactivated&&(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?k.toggleVoice().then(()=>{ft.active=k.isVoiceActive(),so("auto"),k.isVoiceActive()&&R()}):hr("auto"))},600))});ht.push(Fe);let it=s.on("action:resubmit",()=>{setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)});ht.push(it);let Ge=()=>{Ht(!E,"user")},Ye=null,Je=null;if(W&&!M()){let c=r.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:o,defaultRenderer:()=>da(o,Ge).element,onToggle:Ge});f&&(Je=f)}Je||(Ye=da(o,Ge))}Ye?e.appendChild(Ye.element):Je&&e.appendChild(Je),er(),mo.render(o.suggestionChips,k,J,void 0,o.suggestionChipsConfig),ws(),_r(k.isStreaming()),Xo(!0),Ia(),D&&(!W||M()?setTimeout(()=>Vr(),0):E&&setTimeout(()=>Vr(),200));let Xt=()=>{var O,Se,ue,oe,be,ke,He,tt,Xe,lt,ct,Re,Le,Ue,I,Ee,We,je,we,Rt,at,Qt;if(M()){vt(),er();return}let c=mn(o),f=(Se=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Se:!1,h=c||f||((oe=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?oe:!1),y=(be=e.ownerDocument.defaultView)!=null?be:window,P=(He=(ke=o.launcher)==null?void 0:ke.mobileFullscreen)!=null?He:!0,_=(Xe=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Xe:640,$=y.innerWidth<=_,q=P&&$&&W;try{if(q){uo(),Yr(e,o);return}if(C&&(C=!1,uo(),Yr(e,o)),!W&&!c){de.style.height="",de.style.width="";return}if(!f&&!c){let pn=(ct=(lt=o==null?void 0:o.launcher)==null?void 0:lt.width)!=null?ct:o==null?void 0:o.launcherWidth,Wt=pn!=null?pn:lo;de.style.width=Wt,de.style.maxWidth=Wt}if(Ao(),!h){let pn=y.innerHeight,Wt=64,Tn=(Le=(Re=o.launcher)==null?void 0:Re.heightOffset)!=null?Le:0,un=Math.max(200,pn-Wt),Ze=Math.min(640,un),dt=Math.max(200,Ze-Tn);de.style.height=`${dt}px`}}finally{if(vt(),er(),E&&W){let Wt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((Ee=(I=o.launcher)==null?void 0:I.mobileBreakpoint)!=null?Ee:640),Tn=(je=(We=o.launcher)==null?void 0:We.sidebarMode)!=null?je:!1,un=(Rt=(we=o.launcher)==null?void 0:we.mobileFullscreen)!=null?Rt:!0,Ze=mn(o)&&un&&Wt,dt=Tn||un&&Wt&&W||Ze;if(dt&&!Yt){let kn=e.getRootNode(),gn=kn instanceof ShadowRoot?kn.host:e.closest(".persona-host");gn&&!Gt&&(Gt=Fl(gn,(Qt=(at=o.launcher)==null?void 0:at.zIndex)!=null?Qt:yn)),Yt=Ol(e.ownerDocument)}else dt||(Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null)}}};Xt();let kt=(yd=e.ownerDocument.defaultView)!=null?yd:window;if(kt.addEventListener("resize",Xt),ht.push(()=>kt.removeEventListener("resize",Xt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{vt()});c.observe(_e),ht.push(()=>c.disconnect())}ho=X.scrollTop;let It=X.scrollHeight,rn=()=>{let c=X.scrollTop,f=X.scrollHeight,h=f<It;It=f;let{action:y,nextLastScrollTop:P}=ki({following:go.isFollowing(),currentScrollTop:c,lastScrollTop:ho,nearBottom:oa(X,fs),userScrollThreshold:Ma,isAutoScrolling:Ho||ur||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ho=P,y==="resume"){Yo();return}y==="pause"&&bs()};X.addEventListener("scroll",rn,{passive:!0}),ht.push(()=>X.removeEventListener("scroll",rn));let fn=c=>{let f=Ei({following:go.isFollowing(),deltaY:c.deltaY,nearBottom:oa(X,fs),resumeWhenNearBottom:!0});f==="pause"?bs():f==="resume"&&Yo()};X.addEventListener("wheel",fn,{passive:!0}),ht.push(()=>X.removeEventListener("wheel",fn)),Mt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,ho=X.scrollTop,Yo(),Xo(!0)}),ht.push(()=>Mt.remove()),ht.push(()=>{hs()});let dn=()=>{N&&(Kn&&(N.removeEventListener("click",Kn),Kn=null),A()?(N.style.display="",Kn=()=>{Ht(!1,"user")},N.addEventListener("click",Kn)):N.style.display="none")};dn(),(()=>{let{clearChatButton:c}=Ie;c&&c.addEventListener("click",()=>{k.clearMessages(),fo.clear(),Yo(),as(Ie.composerOverlay);try{localStorage.removeItem(ls),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ls}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ls)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(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},L.syncFromMetadata(),Q==null||Q.clear(),Te==null||Te.reset(),he==null||he.update()})})(),Ot&&Ot.addEventListener("submit",Ss),J==null||J.addEventListener("keydown",Ts),J==null||J.addEventListener("input",As),J==null||J.addEventListener("paste",Es);let ao=(vd=e.ownerDocument)!=null?vd:document;ao.addEventListener("keydown",ks,!0);let Tc="persona-attachment-drop-active",Ls=0,cl=()=>{Ls=0,pe.classList.remove(Tc)},qr=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},kc=c=>{!Gi(c.dataTransfer)||!qr()||(Ls++,Ls===1&&pe.classList.add(Tc))},Ec=c=>{!Gi(c.dataTransfer)||!qr()||(Ls--,Ls<=0&&cl())},Mc=c=>{!Gi(c.dataTransfer)||!qr()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Lc=c=>{var h;if(!Gi(c.dataTransfer)||!qr())return;c.preventDefault(),c.stopPropagation(),cl();let f=Array.from((h=c.dataTransfer.files)!=null?h:[]);f.length!==0&&et.handleFiles(f)},tr=!0;pe.addEventListener("dragenter",kc,tr),pe.addEventListener("dragleave",Ec,tr),e.addEventListener("dragover",Mc,tr),e.addEventListener("drop",Lc,tr);let Ua=e.ownerDocument,Ic=c=>{qr()&&c.preventDefault()},Rc=c=>{qr()&&c.preventDefault()};Ua.addEventListener("dragover",Ic),Ua.addEventListener("drop",Rc),ht.push(()=>{Ot&&Ot.removeEventListener("submit",Ss),J==null||J.removeEventListener("keydown",Ts),J==null||J.removeEventListener("input",As),J==null||J.removeEventListener("paste",Es),ao.removeEventListener("keydown",ks,!0)}),ht.push(()=>{pe.removeEventListener("dragenter",kc,tr),pe.removeEventListener("dragleave",Ec,tr),e.removeEventListener("dragover",Mc,tr),e.removeEventListener("drop",Lc,tr),Ua.removeEventListener("dragover",Ic),Ua.removeEventListener("drop",Rc),cl()}),ht.push(()=>{k.cancel()}),Ye?ht.push(()=>{Ye==null||Ye.destroy()}):Je&&ht.push(()=>{Je==null||Je.remove()});let tn={update(c){var nn,Eo,Vo,za,qa,ja,wr,Ka,Is,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,fp,gp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Qp,Jp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,fu,gu,hu,bu,yu,vu,xu,wu;let f=o.toolCall,h=o.messageActions,y=(nn=o.layout)==null?void 0:nn.messages,P=o.colorScheme,_=o.loadingIndicator,$=o.iterationDisplay,q=(Eo=o.features)==null?void 0:Eo.showReasoning,O=(Vo=o.features)==null?void 0:Vo.showToolCalls,Se=(za=o.features)==null?void 0:za.toolCallDisplay,ue=(qa=o.features)==null?void 0:qa.reasoningDisplay;o={...o,...c},uo(),Yr(e,o),ji(e,o),Ki(e,o),qn(),o.colorScheme!==P&&Go();let oe=rc.getForInstance(o.plugins);r.length=0,r.push(...oe),W=(wr=(ja=o.launcher)==null?void 0:ja.enabled)!=null?wr:!0,B=(Is=(Ka=o.launcher)==null?void 0:Ka.autoExpand)!=null?Is:!1,se=(Ed=(kd=o.features)==null?void 0:kd.showReasoning)!=null?Ed:!0,ye=(Ld=(Md=o.features)==null?void 0:Md.showToolCalls)!=null?Ld:!0,Ce=(Rd=(Id=o.features)==null?void 0:Id.scrollToBottom)!=null?Rd:{},zt(),Fo();let be=le;if(le=(Wd=(Pd=o.features)==null?void 0:Pd.showEventStreamToggle)!=null?Wd:!1,le&&!be){if(Q||(ee=new ga(ve),Q=new fa(Me,ee),Te=Te!=null?Te:new ha,ee.open().then(()=>Q==null?void 0:Q.restore()).catch(()=>{}),k.setSSEEventCallback((Z,wt)=>{var Nt;(Nt=o.onSSEEvent)==null||Nt.call(o,Z,wt),Te==null||Te.processEvent(Z,wt),Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(wt)})})),!mt&&Ne){let Z=(Hd=(Bd=o.features)==null?void 0:Bd.eventStream)==null?void 0:Hd.classNames,wt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Z!=null&&Z.toggleButton?" "+Z.toggleButton:"");mt=b("button",wt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Ln.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Nt=Ae("activity","18px","currentColor",1.5);Nt&&mt.appendChild(Nt);let pt=Ie.clearChatButtonWrapper,Lt=Ie.closeButtonWrapper,sn=pt||Lt;sn&&sn.parentNode===Ne?Ne.insertBefore(mt,sn):Ne.appendChild(mt),mt.addEventListener("click",()=>{ce?Nn():wn()})}}else!le&&be&&(Nn(),mt&&(mt.remove(),mt=null),Q==null||Q.clear(),ee==null||ee.destroy(),Q=null,ee=null,Te==null||Te.reset(),Te=null);if(((Dd=o.launcher)==null?void 0:Dd.enabled)===!1&&Ye&&(Ye.destroy(),Ye=null),((Fd=o.launcher)==null?void 0:Fd.enabled)===!1&&Je&&(Je.remove(),Je=null),((Od=o.launcher)==null?void 0:Od.enabled)!==!1&&!Ye&&!Je){let Z=r.find(wt=>wt.renderLauncher);if(Z!=null&&Z.renderLauncher){let wt=Z.renderLauncher({config:o,defaultRenderer:()=>da(o,Ge).element,onToggle:Ge});wt&&(Je=wt,e.appendChild(Je))}Je||(Ye=da(o,Ge),e.appendChild(Ye.element))}Ye&&Ye.update(o),De&&((Nd=o.launcher)==null?void 0:Nd.title)!==void 0&&(De.textContent=o.launcher.title),Qe&&((_d=o.launcher)==null?void 0:_d.subtitle)!==void 0&&(Qe.textContent=o.launcher.subtitle);let ke=(Vd=o.layout)==null?void 0:Vd.header;if((ke==null?void 0:ke.layout)!==v&&Ne){let Z=ke?Bi(o,ke,{showClose:A(),onClose:()=>Ht(!1,"user")}):Lr({config:o,showClose:A(),onClose:()=>Ht(!1,"user")});Ne.replaceWith(Z.header),Ne=Z.header,ae=Z.iconHolder,De=Z.headerTitle,Qe=Z.headerSubtitle,N=Z.closeButton,v=ke==null?void 0:ke.layout}else if(ke&&(ae&&(ae.style.display=ke.showIcon===!1?"none":""),De&&(De.style.display=ke.showTitle===!1?"none":""),Qe&&(Qe.style.display=ke.showSubtitle===!1?"none":""),N&&(N.style.display=ke.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let Z=ke.showClearChat;if(Z!==void 0){Ie.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:wt}=Ie;wt&&!wt.classList.contains("persona-absolute")&&(Z?wt.classList.remove("persona-ml-auto"):wt.classList.add("persona-ml-auto"))}}let tt=(($d=o.layout)==null?void 0:$d.showHeader)!==!1;Ne&&(Ne.style.display=tt?"":"none");let Xe=((Ud=o.layout)==null?void 0:Ud.showFooter)!==!1;_e&&(_e.style.display=Xe?"":"none"),vt(),Fo(),W!==H?W?Ht(B,"auto"):(E=!0,er()):B!==V&&Ht(B,"auto"),V=B,H=W,Xt(),dn();let Re=JSON.stringify(c.toolCall)!==JSON.stringify(f),Le=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ue=JSON.stringify((zd=o.layout)==null?void 0:zd.messages)!==JSON.stringify(y),I=((qd=o.loadingIndicator)==null?void 0:qd.render)!==(_==null?void 0:_.render)||((jd=o.loadingIndicator)==null?void 0:jd.renderIdle)!==(_==null?void 0:_.renderIdle)||((Kd=o.loadingIndicator)==null?void 0:Kd.showBubble)!==(_==null?void 0:_.showBubble),Ee=o.iterationDisplay!==$,We=((Yd=(Gd=o.features)==null?void 0:Gd.showReasoning)!=null?Yd:!0)!==(q!=null?q:!0)||((Qd=(Xd=o.features)==null?void 0:Xd.showToolCalls)!=null?Qd:!0)!==(O!=null?O:!0)||JSON.stringify((Jd=o.features)==null?void 0:Jd.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((Zd=o.features)==null?void 0:Zd.reasoningDisplay)!==JSON.stringify(ue);(Re||Le||Ue||I||Ee||We)&&k&&(ms++,fr($e,k.getMessages(),fe));let we=(ep=o.launcher)!=null?ep:{},Rt=(tp=we.headerIconHidden)!=null?tp:!1,at=(op=(np=o.layout)==null?void 0:np.header)==null?void 0:op.showIcon,Qt=Rt||at===!1,pn=we.headerIconName,Wt=(rp=we.headerIconSize)!=null?rp:"48px";if(ae){let Z=pe.querySelector(".persona-border-b-persona-divider"),wt=Z==null?void 0:Z.querySelector(".persona-flex-col");if(Qt)ae.style.display="none",Z&&wt&&!Z.contains(wt)&&Z.insertBefore(wt,Z.firstChild);else{if(ae.style.display="",ae.style.height=Wt,ae.style.width=Wt,Z&&wt&&(Z.contains(ae)?ae.nextSibling!==wt&&(ae.remove(),Z.insertBefore(ae,wt)):Z.insertBefore(ae,wt)),pn){let pt=parseFloat(Wt)||24,Lt=Ae(pn,pt*.6,"#ffffff",2);Lt?ae.replaceChildren(Lt):ae.textContent=(sp=we.agentIconText)!=null?sp:"\u{1F4AC}"}else if(we.iconUrl){let pt=ae.querySelector("img");if(pt)pt.src=we.iconUrl,pt.style.height=Wt,pt.style.width=Wt;else{let Lt=document.createElement("img");Lt.src=we.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Wt,Lt.style.width=Wt,ae.replaceChildren(Lt)}}else{let pt=ae.querySelector("svg"),Lt=ae.querySelector("img");(pt||Lt)&&ae.replaceChildren(),ae.textContent=(ap=we.agentIconText)!=null?ap:"\u{1F4AC}"}let Nt=ae.querySelector("img");Nt&&(Nt.style.height=Wt,Nt.style.width=Wt)}}let Tn=(lp=(ip=o.layout)==null?void 0:ip.header)==null?void 0:lp.showTitle,un=(dp=(cp=o.layout)==null?void 0:cp.header)==null?void 0:dp.showSubtitle;if(De&&(De.style.display=Tn===!1?"none":""),Qe&&(Qe.style.display=un===!1?"none":""),N){((up=(pp=o.layout)==null?void 0:pp.header)==null?void 0:up.showCloseButton)===!1?N.style.display="none":N.style.display="";let wt=(mp=we.closeButtonSize)!=null?mp:"32px",Nt=(fp=we.closeButtonPlacement)!=null?fp:"inline";N.style.height=wt,N.style.width=wt;let{closeButtonWrapper:pt}=Ie,Lt=Nt==="top-right",sn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&Lt!==sn)if(pt.remove(),Lt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(pt);else{let ut=(hp=(gp=we.clearChat)==null?void 0:gp.placement)!=null?hp:"inline",an=(yp=(bp=we.clearChat)==null?void 0:bp.enabled)!=null?yp:!0;pt.className=an&&ut==="inline"?"":"persona-ml-auto";let Dn=pe.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(pt)}if(N.style.color=we.closeButtonColor||Ln.actionIconColor,we.closeButtonBackgroundColor?(N.style.backgroundColor=we.closeButtonBackgroundColor,N.classList.remove("hover:persona-bg-gray-100")):(N.style.backgroundColor="",N.classList.add("hover:persona-bg-gray-100")),we.closeButtonBorderWidth||we.closeButtonBorderColor){let ut=we.closeButtonBorderWidth||"0px",an=we.closeButtonBorderColor||"transparent";N.style.border=`${ut} solid ${an}`,N.classList.remove("persona-border-none")}else N.style.border="",N.classList.add("persona-border-none");we.closeButtonBorderRadius?(N.style.borderRadius=we.closeButtonBorderRadius,N.classList.remove("persona-rounded-full")):(N.style.borderRadius="",N.classList.add("persona-rounded-full")),we.closeButtonPaddingX?(N.style.paddingLeft=we.closeButtonPaddingX,N.style.paddingRight=we.closeButtonPaddingX):(N.style.paddingLeft="",N.style.paddingRight=""),we.closeButtonPaddingY?(N.style.paddingTop=we.closeButtonPaddingY,N.style.paddingBottom=we.closeButtonPaddingY):(N.style.paddingTop="",N.style.paddingBottom="");let hn=(vp=we.closeButtonIconName)!=null?vp:"x",vo=(xp=we.closeButtonIconText)!=null?xp:"\xD7";N.innerHTML="";let Mn=Ae(hn,"28px","currentColor",1);Mn?N.appendChild(Mn):N.textContent=vo;let Jt=(wp=we.closeButtonTooltipText)!=null?wp:"Close chat",Qn=(Cp=we.closeButtonShowTooltip)!=null?Cp:!0;if(N.setAttribute("aria-label",Jt),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),Qn&&Jt)){let ut=null,an=()=>{if(ut||!N)return;let Cr=N.ownerDocument,Rs=Cr.body;if(!Rs)return;ut=Mo(Cr,"div","persona-clear-chat-tooltip"),ut.textContent=Jt;let Ps=Mo(Cr,"div");Ps.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Ps);let Sr=N.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(rr),ut.style.left=`${Sr.left+Sr.width/2}px`,ut.style.top=`${Sr.top-8}px`,ut.style.transform="translate(-50%, -100%)",Rs.appendChild(ut)},Dn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};pt.addEventListener("mouseenter",an),pt.addEventListener("mouseleave",Dn),N.addEventListener("focus",an),N.addEventListener("blur",Dn),pt._cleanupTooltip=()=>{Dn(),pt&&(pt.removeEventListener("mouseenter",an),pt.removeEventListener("mouseleave",Dn)),N&&(N.removeEventListener("focus",an),N.removeEventListener("blur",Dn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:dt}=Ie;if(Ze){let Z=(Sp=we.clearChat)!=null?Sp:{},wt=(Ap=Z.enabled)!=null?Ap:!0,Nt=(kp=(Tp=o.layout)==null?void 0:Tp.header)==null?void 0:kp.showClearChat,pt=Nt!==void 0?Nt:wt,Lt=(Ep=Z.placement)!=null?Ep:"inline";if(dt){dt.style.display=pt?"":"none";let{closeButtonWrapper:sn}=Ie;!M()&&sn&&!sn.classList.contains("persona-absolute")&&(pt?sn.classList.remove("persona-ml-auto"):sn.classList.add("persona-ml-auto"));let hn=Lt==="top-right",vo=dt.classList.contains("persona-absolute");if(!M()&&hn!==vo&&pt){if(dt.remove(),hn)dt.className="persona-absolute persona-top-4 persona-z-50",dt.style.right="48px",pe.style.position="relative",pe.appendChild(dt);else{dt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",dt.style.right="";let Jt=pe.querySelector(".persona-border-b-persona-divider"),Qn=Ie.closeButtonWrapper;Jt&&Qn&&Qn.parentElement===Jt?Jt.insertBefore(dt,Qn):Jt&&Jt.appendChild(dt)}let Mn=Ie.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(hn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(pt){if(!M()){let ut=(Mp=Z.size)!=null?Mp:"32px";Ze.style.height=ut,Ze.style.width=ut}let sn=(Lp=Z.iconName)!=null?Lp:"refresh-cw",hn=(Ip=Z.iconColor)!=null?Ip:"";Ze.style.color=hn||Ln.actionIconColor,Ze.innerHTML="";let vo=M()?"14px":"20px",Mn=Ae(sn,vo,"currentColor",2);if(Mn&&Ze.appendChild(Mn),Z.backgroundColor?(Ze.style.backgroundColor=Z.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let ut=Z.borderWidth||"0px",an=Z.borderColor||"transparent";Ze.style.border=`${ut} solid ${an}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");Z.borderRadius?(Ze.style.borderRadius=Z.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),Z.paddingX?(Ze.style.paddingLeft=Z.paddingX,Ze.style.paddingRight=Z.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),Z.paddingY?(Ze.style.paddingTop=Z.paddingY,Ze.style.paddingBottom=Z.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let Jt=(Rp=Z.tooltipText)!=null?Rp:"Clear chat",Qn=(Pp=Z.showTooltip)!=null?Pp:!0;if(Ze.setAttribute("aria-label",Jt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Qn&&Jt)){let ut=null,an=()=>{if(ut||!Ze)return;let Cr=Ze.ownerDocument,Rs=Cr.body;if(!Rs)return;ut=Mo(Cr,"div","persona-clear-chat-tooltip"),ut.textContent=Jt;let Ps=Mo(Cr,"div");Ps.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Ps);let Sr=Ze.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(rr),ut.style.left=`${Sr.left+Sr.width/2}px`,ut.style.top=`${Sr.top-8}px`,ut.style.transform="translate(-50%, -100%)",Rs.appendChild(ut)},Dn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",an),dt.addEventListener("mouseleave",Dn),Ze.addEventListener("focus",an),Ze.addEventListener("blur",Dn),dt._cleanupTooltip=()=>{Dn(),dt&&(dt.removeEventListener("mouseenter",an),dt.removeEventListener("mouseleave",Dn)),Ze&&(Ze.removeEventListener("focus",an),Ze.removeEventListener("blur",Dn))}}}}let kn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ac],gn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ba.message,ba.messageAndClick];L=ic({parsers:kn,handlers:gn,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),fe=df(o,L,j),k.updateConfig(o),fr($e,k.getMessages(),fe),mo.render(o.suggestionChips,k,J,void 0,o.suggestionChipsConfig),ws(),_r(k.isStreaming());let br=((Wp=o.voiceRecognition)==null?void 0:Wp.enabled)===!0,yr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),vr=((Hp=(Bp=o.voiceRecognition)==null?void 0:Bp.provider)==null?void 0:Hp.type)==="runtype";if(br&&(yr||vr))if(!G||!gt){let Z=zr(o.voiceRecognition,o.sendButton);Z&&(G=Z.micButton,gt=Z.micButtonWrapper,_t.insertBefore(gt,In),G.addEventListener("click",qe),G.disabled=k.isStreaming())}else{let Z=(Dp=o.voiceRecognition)!=null?Dp:{},wt=(Fp=o.sendButton)!=null?Fp:{},Nt=(Op=Z.iconName)!=null?Op:"mic",pt=(Np=wt.size)!=null?Np:"40px",Lt=(_p=Z.iconSize)!=null?_p:pt,sn=parseFloat(Lt)||24;G.style.width=Lt,G.style.height=Lt,G.style.minWidth=Lt,G.style.minHeight=Lt;let hn=($p=(Vp=Z.iconColor)!=null?Vp:wt.textColor)!=null?$p:"currentColor";G.innerHTML="";let vo=Ae(Nt,sn,hn,2);vo?G.appendChild(vo):G.textContent="\u{1F3A4}";let Mn=(Up=Z.backgroundColor)!=null?Up:wt.backgroundColor;Mn?G.style.backgroundColor=Mn:G.style.backgroundColor="",hn?G.style.color=hn:G.style.color="var(--persona-text, #111827)",Z.borderWidth?(G.style.borderWidth=Z.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Z.borderColor?G.style.borderColor=Z.borderColor:G.style.borderColor="",Z.paddingX?(G.style.paddingLeft=Z.paddingX,G.style.paddingRight=Z.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Z.paddingY?(G.style.paddingTop=Z.paddingY,G.style.paddingBottom=Z.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Jt=gt==null?void 0:gt.querySelector(".persona-send-button-tooltip"),Qn=(zp=Z.tooltipText)!=null?zp:"Start voice recognition";if(((qp=Z.showTooltip)!=null?qp:!1)&&Qn)if(Jt)Jt.textContent=Qn,Jt.style.display="";else{let an=document.createElement("div");an.className="persona-send-button-tooltip",an.textContent=Qn,gt==null||gt.insertBefore(an,G)}else Jt&&(Jt.style.display="none");gt.style.display="",G.disabled=k.isStreaming()}else G&&gt&&(gt.style.display="none",((Kp=(jp=o.voiceRecognition)==null?void 0:jp.provider)==null?void 0:Kp.type)==="runtype"?k.isVoiceActive()&&k.toggleVoice():Yn&&yo());if(((Gp=o.attachments)==null?void 0:Gp.enabled)===!0)if(!Ut||!ot){let Z=(Yp=o.attachments)!=null?Yp:{},Nt=(Qp=((Xp=o.sendButton)!=null?Xp:{}).size)!=null?Qp:"40px";xe||(xe=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xe.style.display="none",Ot.insertBefore(xe,J)),ie||(ie=document.createElement("input"),ie.type="file",ie.accept=((Jp=Z.allowedTypes)!=null?Jp:$o).join(","),ie.multiple=((Zp=Z.maxFiles)!=null?Zp:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Ot.insertBefore(ie,J)),Ut=b("div","persona-send-button-wrapper"),ot=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ot.type="button",ot.setAttribute("aria-label",(eu=Z.buttonTooltipText)!=null?eu:"Attach file");let pt=(tu=Z.buttonIconName)!=null?tu:"paperclip",Lt=Nt,sn=parseFloat(Lt)||40,hn=Math.round(sn*.6);ot.style.width=Lt,ot.style.height=Lt,ot.style.minWidth=Lt,ot.style.minHeight=Lt,ot.style.fontSize="18px",ot.style.lineHeight="1",ot.style.backgroundColor="transparent",ot.style.color="var(--persona-primary, #111827)",ot.style.border="none",ot.style.borderRadius="6px",ot.style.transition="background-color 0.15s ease",ot.addEventListener("mouseenter",()=>{ot.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ot.addEventListener("mouseleave",()=>{ot.style.backgroundColor="transparent"});let vo=Ae(pt,hn,"currentColor",1.5);vo?ot.appendChild(vo):ot.textContent="\u{1F4CE}",ot.addEventListener("click",Qn=>{Qn.preventDefault(),ie==null||ie.click()}),Ut.appendChild(ot);let Mn=(nu=Z.buttonTooltipText)!=null?nu:"Attach file",Jt=b("div","persona-send-button-tooltip");Jt.textContent=Mn,Ut.appendChild(Jt),At.append(Ut),!et&&ie&&xe&&(et=ta.fromConfig(Z),et.setPreviewsContainer(xe),ie.addEventListener("change",async()=>{et&&(ie!=null&&ie.files)&&(await et.handleFileSelect(ie.files),ie.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(pf(Z.dropOverlay))}else{Ut.style.display="";let Z=(ou=o.attachments)!=null?ou:{};ie&&(ie.accept=((ru=Z.allowedTypes)!=null?ru:$o).join(","),ie.multiple=((su=Z.maxFiles)!=null?su:4)>1),et&&et.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}else Ut&&(Ut.style.display="none"),et&&et.clearAttachments(),(au=pe.querySelector(".persona-attachment-drop-overlay"))==null||au.remove();let qt=(iu=o.sendButton)!=null?iu:{},xr=(lu=qt.useIcon)!=null?lu:!1,nr=(cu=qt.iconText)!=null?cu:"\u2191",yt=qt.iconName,Wn=(du=qt.tooltipText)!=null?du:"Send message",_o=(pu=qt.showTooltip)!=null?pu:!1,En=(uu=qt.size)!=null?uu:"40px",Bn=qt.backgroundColor,Dt=qt.textColor;if(xr){if(Oe.style.width=En,Oe.style.height=En,Oe.style.minWidth=En,Oe.style.minHeight=En,Oe.style.fontSize="18px",Oe.style.lineHeight="1",Oe.innerHTML="",Dt?Oe.style.color=Dt:Oe.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Z=parseFloat(En)||24,wt=(Dt==null?void 0:Dt.trim())||"currentColor",Nt=Ae(yt,Z,wt,2);Nt?Oe.appendChild(Nt):Oe.textContent=nr}else Oe.textContent=nr;Oe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Bn?(Oe.style.backgroundColor=Bn,Oe.classList.remove("persona-bg-persona-primary")):(Oe.style.backgroundColor="",Oe.classList.add("persona-bg-persona-primary"))}else Oe.textContent=(fu=(mu=o.copy)==null?void 0:mu.sendButtonLabel)!=null?fu:"Send",Oe.style.width="",Oe.style.height="",Oe.style.minWidth="",Oe.style.minHeight="",Oe.style.fontSize="",Oe.style.lineHeight="",Oe.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",Bn?(Oe.style.backgroundColor=Bn,Oe.classList.remove("persona-bg-persona-accent")):Oe.classList.add("persona-bg-persona-accent"),Dt?Oe.style.color=Dt:Oe.classList.add("persona-text-white");qt.borderWidth?(Oe.style.borderWidth=qt.borderWidth,Oe.style.borderStyle="solid"):(Oe.style.borderWidth="",Oe.style.borderStyle=""),qt.borderColor?Oe.style.borderColor=qt.borderColor:Oe.style.borderColor="",qt.paddingX?(Oe.style.paddingLeft=qt.paddingX,Oe.style.paddingRight=qt.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),qt.paddingY?(Oe.style.paddingTop=qt.paddingY,Oe.style.paddingBottom=qt.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let $t=In==null?void 0:In.querySelector(".persona-send-button-tooltip");if(_o&&Wn)if($t)$t.textContent=Wn,$t.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=Wn,In==null||In.insertBefore(Z,Oe)}else $t&&($t.style.display="none");let Ft=(vu=(gu=o.layout)==null?void 0:gu.contentMaxWidth)!=null?vu:M()?(yu=(bu=(hu=o.launcher)==null?void 0:hu.composerBar)==null?void 0:bu.contentMaxWidth)!=null?yu:"720px":void 0;Ft?($e.style.maxWidth=Ft,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ot&&(Ot.style.maxWidth=Ft,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),St&&(St.style.maxWidth=Ft,St.style.marginLeft="auto",St.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),St&&(St.style.maxWidth="",St.style.marginLeft="",St.style.marginRight=""));let jt=(xu=o.statusIndicator)!=null?xu:{},Hn=(wu=jt.visible)!=null?wu:!0;if(cn.style.display=Hn?"":"none",k){let Z=k.getStatus();nt(cn,(Nt=>{var pt,Lt,sn,hn;return Nt==="idle"?(pt=jt.idleText)!=null?pt:bn.idle:Nt==="connecting"?(Lt=jt.connectingText)!=null?Lt:bn.connecting:Nt==="connected"?(sn=jt.connectedText)!=null?sn:bn.connected:Nt==="error"?(hn=jt.errorText)!=null?hn:bn.error:bn[Nt]})(Z),jt,Z)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Xn=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Xn)},open(){A()&&Ht(!0,"api")},close(){A()&&Ht(!1,"api")},toggle(){A()&&Ht(!E,"api")},clearChat(){Cn=!1,k.clearMessages(),fo.clear(),Yo();try{localStorage.removeItem(ls),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ls}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ls)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 c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(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)}d={},L.syncFromMetadata(),Q==null||Q.clear(),Te==null||Te.reset(),he==null||he.update()},setMessage(c){return!J||k.isStreaming()?!1:(!E&&A()&&Ht(!0,"system"),J.value=c,J.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(k.isStreaming())return!1;let f=(c==null?void 0:c.trim())||J.value.trim();return f?(!E&&A()&&Ht(!0,"system"),J.value="",J.style.height="auto",k.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return k.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(k.isVoiceActive()||(!E&&A()&&Ht(!0,"system"),ft.manuallyDeactivated=!1,Pn(),k.toggleVoice().then(()=>{ft.active=k.isVoiceActive(),so("user"),k.isVoiceActive()&&R()})),!0):Yn?!0:Ms()?(!E&&A()&&Ht(!0,"system"),ft.manuallyDeactivated=!1,Pn(),hr("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?k.isVoiceActive()?(k.toggleVoice().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Pn(),so("user"),Y()}),!0):!1:Yn?(ft.manuallyDeactivated=!0,Pn(),yo("user"),!0):!1},injectMessage(c){return!E&&A()&&Ht(!0,"system"),k.injectMessage(c)},injectAssistantMessage(c){!E&&A()&&Ht(!0,"system");let f=k.injectAssistantMessage(c);return F&&(F=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)),f},injectUserMessage(c){return!E&&A()&&Ht(!0,"system"),k.injectUserMessage(c)},injectSystemMessage(c){return!E&&A()&&Ht(!0,"system"),k.injectSystemMessage(c)},injectMessageBatch(c){return!E&&A()&&Ht(!0,"system"),k.injectMessageBatch(c)},injectComponentDirective(c){return!E&&A()&&Ht(!0,"system"),k.injectComponentDirective(c)},injectTestMessage(c){!E&&A()&&Ht(!0,"system"),k.injectTestEvent(c)},async connectStream(c,f){return k.connectStream(c,f)},__pushEventStreamEvent(c){Q&&(Te==null||Te.processEvent(c.type,c.payload),Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!le||!Q||wn()},hideEventStream(){ce&&Nn()},isEventStreamVisible(){return ce},showArtifacts(){po(o)&&(Cn=!1,qn(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){po(o)&&(Cn=!0,qn())},upsertArtifact(c){return po(o)?(Cn=!1,k.upsertArtifact(c)):null},selectArtifact(c){po(o)&&k.selectArtifact(c)},clearArtifacts(){po(o)&&k.clearArtifacts()},getArtifacts(){var c;return(c=k==null?void 0:k.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=k==null?void 0:k.getSelectedArtifactId())!=null?c:null},focusInput(){return W&&!E&&!M()||!J?!1:(J.focus(),!0)},async resolveApproval(c,f){let y=k.getMessages().find(P=>{var _;return P.variant==="approval"&&((_=P.approval)==null?void 0:_.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){k.resolveWebMcpApproval(y.id,f);return}return k.resolveApproval(y.approval,f)},getMessages(){return k.getMessages()},getStatus(){return k.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,f){return s.on(c,f)},off(c,f){s.off(c,f)},isOpen(){return A()&&E},isVoiceActive(){return ft.active},getState(){return{open:A()&&E,launcherEnabled:W,voiceActive:ft.active,streaming:k.isStreaming()}},showCSATFeedback(c){!E&&A()&&Ht(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let h=af({onSubmit:async(y,P)=>{var _;k.isClientTokenMode()&&await k.submitCSATFeedback(y,P),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!E&&A()&&Ht(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let h=lf({onSubmit:async(y,P)=>{var _;k.isClientTokenMode()&&await k.submitNPSFeedback(y,P),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return k.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return k.submitNPSFeedback(c,f)},destroy(){ko!=null&&(clearInterval(ko),ko=null),ht.forEach(c=>c()),ge.remove(),Ve==null||Ve.remove(),Ye==null||Ye.destroy(),Je==null||Je.remove(),Kn&&N.removeEventListener("click",Kn)}};if((((xd=n==null?void 0:n.debugTools)!=null?xd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=f,ht.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",f),ht.push(()=>{window.removeEventListener("persona:focusInput",f)}),le){let q=Se=>{let ue=Se.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.showEventStream()},O=Se=>{let ue=Se.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",O),ht.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",O)})}let h=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&tn.showArtifacts()},y=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&tn.hideArtifacts()},P=q=>{let O=q.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&tn.upsertArtifact(O.artifact)},_=q=>{let O=q.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&tn.selectArtifact(O.id)},$=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",_),window.addEventListener("persona:clearArtifacts",$),ht.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",_),window.removeEventListener("persona:clearArtifacts",$)})}let io=iy(o.persistState);if(io&&A()){let c=ly(io.storage),f=`${io.keyPrefix}widget-open`,h=`${io.keyPrefix}widget-voice`,y=`${io.keyPrefix}widget-voice-mode`;if(c){let P=((wd=io.persist)==null?void 0:wd.openState)&&c.getItem(f)==="true",_=((Cd=io.persist)==null?void 0:Cd.voiceState)&&c.getItem(h)==="true",$=((Sd=io.persist)==null?void 0:Sd.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{tn.open(),setTimeout(()=>{var q;if(_||$)tn.startVoiceRecognition();else if((q=io.persist)!=null&&q.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Ad=io.persist)!=null&&Ad.openState&&(s.on("widget:opened",()=>{c.setItem(f,"true")}),s.on("widget:closed",()=>{c.setItem(f,"false")})),(Td=io.persist)!=null&&Td.voiceState&&(s.on("voice:state",q=>{c.setItem(h,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),io.clearOnChatClear){let q=()=>{c.removeItem(f),c.removeItem(h),c.removeItem(y)},O=()=>q();window.addEventListener("persona:clear-chat",O),ht.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return u&&A()&&setTimeout(()=>{tn.open()},0),Oo(),tn};var cy=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},mf=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},mc=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=""},ff=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",mc(e)},dc=e=>{e.style.transition=""},pc=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=""},uc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Yi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},dy=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},py=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},gf=(e,t,n,o,r,s,a)=>{var w,x,L,W,B,D;let i=Lo(s),d=i.reveal==="push";dy(e,t,n,o,d),py(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?x:!0,p=(W=(L=s==null?void 0:s.launcher)==null?void 0:L.mobileBreakpoint)!=null?W:640,g=l!=null?l.innerWidth<=p:!1;if(u&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),pc(t),dc(o),ff(o),uc(n),Yi(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",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((D=(B=s==null?void 0:s.launcher)==null?void 0:B.zIndex)!=null?D:yn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),ff(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",pc(t),dc(o),uc(n),Yi(r,o);let V=i.animate?"transform 180ms ease":"none",H=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":H;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=V,o.style.transform=v,o.style.pointerEvents=a?"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",dc(o),mc(o),Yi(r,o);let V=cy(i.width,e.clientWidth),H=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",C=i.side==="right"?a?`translateX(-${V}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${V}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${H+V}px`,t.style.transition=v,t.style.transform=C,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${H}px`,n.style.maxWidth=`${H}px`,n.style.minWidth=`${H}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.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",pc(t),mc(o),uc(n),Yi(r,o);let V=i.reveal==="emerge";V?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let H=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",C=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${H}`,o.style.width=H,o.style.maxWidth=H,o.style.minWidth=H,o.style.minHeight="0",o.style.position="relative",o.style.overflow=V||C?"hidden":"visible",o.style.transition=v,V&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},uy=(e,t)=>{let n=e.ownerDocument.createElement("div");return mf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){mf(n,o)},destroy(){n.remove()}}},my=(e,t)=>{var B,D,V,H;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),u=n.createElement("div"),p=(D=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||D?(H=(V=t==null?void 0:t.launcher)==null?void 0:V.autoExpand)!=null?H:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let g=null,m=()=>{g==null||g.disconnect(),g=null},w=()=>{m(),Lo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{gf(a,i,d,l,u,t,p)}),g.observe(a))},x=()=>{gf(a,i,d,l,u,t,p),w()},L=a.ownerDocument.defaultView,W=()=>{x()};return L==null||L.addEventListener("resize",W),Lo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(v){let C=v.launcherEnabled?v.open:!0;p!==C&&(p=C,x())},updateConfig(v){var C,M;t=v,((M=(C=t==null?void 0:t.launcher)==null?void 0:C.enabled)!=null?M:!0)===!1&&(p=!0),x()},destroy(){L==null||L.removeEventListener("resize",W),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},hf=(e,t)=>mn(t)?my(e,t):uy(e,t);var Br={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Xi=.15,Qi=1.5,ya="persona-preview-shell-theme",fc={load:()=>null,save:()=>{},clear:()=>{}},gc=["How do I get started?","Pricing & plans","Talk to support"];function va(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function hc(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Ji(e){let t=hc(e);return`* { box-sizing: border-box; }
107
+ `}if(!y&&!c){let Ft="max-height: -moz-available !important; max-height: stretch !important;",jt=m?"":"padding-top: 1.25em !important;",Hn=m?"":`z-index: ${($t=(Dt=o.launcher)==null?void 0:Dt.zIndex)!=null?$t:yn} !important;`;fe.style.cssText+=Ft+jt+Hn}R()};uo(),Yr(e,o),ji(e,o),Ki(e,o);let ht=[];ht.push(()=>{document.removeEventListener("keydown",qo)});let Gt=null,Yt=null;ht.push(()=>{Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null}),Vn&&ht.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),ht.push(()=>{Sn==null||Sn(),Sn=null,Wo(),Bt&&(Bt.remove(),Bt=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),le&&ht.push(()=>{me!==null&&(cancelAnimationFrame(me),me=null),he==null||he.destroy(),he=null,Q==null||Q.destroy(),Q=null,ee=null});let jn=null,Go=()=>{jn&&(jn(),jn=null),o.colorScheme==="auto"&&(jn=Ru(()=>{Yr(e,o)}))};Go(),ht.push(()=>{jn&&(jn(),jn=null)});let ro=(md=o.features)==null?void 0:md.streamAnimation;if(ro!=null&&ro.type&&ro.type!=="none"){let c=sa(ro.type,ro.plugins);c&&(Dl(c,e),ht.push(()=>vm(e)))}let mo=Vm(St),Kn=null,k,Gn=!1,go=mm(),Bo=new Map,To=new Map,ms=0,fo=Ti(),ho=0,bo=null,Ho=!1,ur=!1,Ma=4,gs=24,La=80,Or=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},fs=(fd=(gd=o.voiceRecognition)==null?void 0:gd.autoResume)!=null?fd:!1,so=c=>{s.emit("voice:state",{active:gt.active,source:c,timestamp:Date.now()})},Pn=()=>{g(c=>({...c,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},Ia=()=>{var y,W;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=cc(d.voiceState),m=!!c.active,h=Number((W=c.timestamp)!=null?W:0);gt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<iy&&setTimeout(()=>{var V,$;gt.active||(gt.manuallyDeactivated=!1,(($=(V=o.voiceRecognition)==null?void 0:V.provider)==null?void 0:$.type)==="runtype"?k.toggleVoice().then(()=>{gt.active=k.isVoiceActive(),so("restore"),k.isVoiceActive()&&P()}):hr("restore"))},1e3)},Ra=()=>k?dg(k.getMessages()).filter(c=>!c.__skipPersist):[];function Nr(c){if(!(i!=null&&i.save))return;let h={messages:c?dg(c):k?Ra():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Do=null,Pa=()=>fe.querySelector("#persona-scroll-container")||X,mr=()=>{Do!==null&&(cancelAnimationFrame(Do),Do=null),Ho=!1},hs=()=>{bo!==null&&(cancelAnimationFrame(bo),bo=null),ur=!1,mr()},Fo=()=>{if(!xn()||ce){Mt.parentNode&&Mt.remove(),Mt.style.display="none";return}Mt.parentNode!==pe&&pe.appendChild(Mt),vt();let c=na(X)>0;Mt.style.display=fo.isFollowing()||!c?"none":""},bs=()=>{fo.pause()&&(hs(),Fo())},Yo=()=>{fo.resume(),Fo()},Xo=(c=!1)=>{fo.isFollowing()&&(!c&&!Gn||(bo!==null&&(cancelAnimationFrame(bo),bo=null),ur=!0,bo=requestAnimationFrame(()=>{bo=null,ur=!1,fo.isFollowing()&&Wa(Pa(),c?220:140)})))},Wa=(c,m=500)=>{let h=c.scrollTop,y=na(c),W=y-h;if(Math.abs(W)<1){ho=c.scrollTop;return}if(Math.abs(W)>=La){mr(),Ho=!0,c.scrollTop=y,ho=c.scrollTop,Ho=!1;return}mr();let V=performance.now();Ho=!0;let $=N=>1-Math.pow(1-N,3),q=N=>{if(!fo.isFollowing()){mr();return}let Se=na(c);Se!==y&&(y=Se,W=y-h);let ue=N-V,oe=Math.min(ue/m,1),be=$(oe),ke=h+W*be;c.scrollTop=ke,ho=c.scrollTop,oe<1?Do=requestAnimationFrame(q):(c.scrollTop=y,ho=c.scrollTop,Do=null,Ho=!1)};Do=requestAnimationFrame(q)},Ba=c=>{let m=new Map;c.forEach(h=>{let y=Or.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Or.clear(),m.forEach((h,y)=>{Or.set(y,h)})},gr=(c,m,h)=>{var Xe,lt,ct,Re,Le,Ue;let y=document.createElement("div"),V=(()=>{var Ee;let R=r.find(We=>We.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Ee=o.loadingIndicator)!=null&&Ee.render)return o.loadingIndicator.render})(),$=(R,Ee)=>Ee==null?!1:typeof Ee=="string"?(R.textContent=Ee,!0):(R.appendChild(Ee),!0),q=new Set,N=new Set,Se=r.some(R=>R.renderAskUserQuestion),ue=[],oe=[],be=o.enableComponentStreaming!==!1;if(m.forEach(R=>{var Tn,un,Ze,dt,kn,fn,br,yr,vr,jr,Kr,qt,xr,nr;q.add(R.id);let Ee=Se&&Ir(R),We=!Ee&&R.role==="assistant"&&!R.variant&&be&&ag(R);if(!We&&To.has(R.id)){let yt=c.querySelector(`#wrapper-${R.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),To.delete(R.id)}let je=Ir(R)?`:${(Tn=R.agentMetadata)!=null&&Tn.askUserQuestionAnswered?"a":"u"}:${(un=R.agentMetadata)!=null&&un.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",we=um(R,ms)+je,Rt=Ee||We?null:gm(go,R.id,we);if(Rt){y.appendChild(Rt.cloneNode(!0)),Ir(R)&&((Ze=R.toolCall)!=null&&Ze.id)&&((dt=R.agentMetadata)==null?void 0:dt.awaitingLocalTool)===!0&&!((kn=R.agentMetadata)!=null&&kn.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ui(R,o,Ie.composerOverlay));return}let at=null,Qt=r.find(yt=>!!(R.variant==="reasoning"&&yt.renderReasoning||R.variant==="tool"&&yt.renderToolCall||R.variant==="approval"&&yt.renderApproval||!R.variant&&yt.renderMessage)),pn=(fn=o.layout)==null?void 0:fn.messages;if(Ir(R)&&((br=R.agentMetadata)==null?void 0:br.askUserQuestionAnswered)===!0){Bo.delete(R.id);let yt=c.querySelector(`#wrapper-${R.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if(Ir(R)&&((vr=(yr=o.features)==null?void 0:yr.askUserQuestion)==null?void 0:vr.enabled)!==!1){let yt=r.find(Wn=>typeof Wn.renderAskUserQuestion=="function");if(yt&&Pt.current){let Wn=Bo.get(R.id),_o=Wn!==we,En=null;if(_o){let{payload:$t,complete:Ft}=rs(R),jt=R.id,Hn=()=>{var Xn;return(Xn=Pt.current)==null?void 0:Xn.getMessages().find(nn=>nn.id===jt)};En=yt.renderAskUserQuestion({message:R,payload:$t,complete:Ft,resolve:Xn=>{var Eo;let nn=Hn();nn&&((Eo=Pt.current)==null||Eo.resolveAskUserQuestion(nn,Xn))},dismiss:()=>{var nn,Eo,Vo;let Xn=Hn();(nn=Xn==null?void 0:Xn.agentMetadata)!=null&&nn.awaitingLocalTool&&((Eo=Pt.current)==null||Eo.markAskUserQuestionResolved(Xn),(Vo=Pt.current)==null||Vo.resolveAskUserQuestion(Xn,"(dismissed)"))},config:o})}let Bn=Wn!=null;if(_o&&En===null&&!Bn){((jr=R.agentMetadata)==null?void 0:jr.awaitingLocalTool)===!0&&!((Kr=R.agentMetadata)!=null&&Kr.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ui(R,o,Ie.composerOverlay));return}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${R.id}`,Dt.setAttribute("data-wrapper-id",R.id),Dt.setAttribute("data-ask-plugin-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),y.appendChild(Dt),ue.push({messageId:R.id,fingerprint:we,bubble:En});return}else{((qt=R.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((xr=R.agentMetadata)!=null&&xr.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ui(R,o,Ie.composerOverlay));return}}else if(Qt)if(R.variant==="reasoning"&&R.reasoning&&Qt.renderReasoning){if(!se)return;at=Qt.renderReasoning({message:R,defaultRenderer:()=>Ul(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&Qt.renderToolCall){if(!ye)return;at=Qt.renderToolCall({message:R,defaultRenderer:()=>zl(R,o),config:o})}else if(R.variant==="approval"&&R.approval&&Qt.renderApproval){if(o.approval===!1)return;at=Qt.renderApproval({message:R,defaultRenderer:()=>Jl(R,o),config:o})}else Qt.renderMessage&&(at=Qt.renderMessage({message:R,defaultRenderer:()=>{let yt=$l(R,h,pn,o.messageActions,K,{loadingIndicatorRenderer:V,widgetConfig:o});return R.role!=="user"&&nc(yt,R,o,k),yt},config:o}));if(!at&&We){let yt=ig(R);if(yt){let Wn=To.get(R.id),_o=Wn!==we,En=o.wrapComponentDirectiveInBubble!==!1,Bn=null;if(_o){let Dt=rg(yt,{config:o,message:R,transform:h});if(Dt)if(En){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-${R.id}`,$t.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let Ft=document.createElement("div");Ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ft.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(Ft)}$t.appendChild(Dt),Bn=$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-${R.id}`,$t.setAttribute("data-message-id",R.id),$t.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let Ft=document.createElement("div");Ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ft.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(Ft)}$t.appendChild(Dt),Bn=$t}}if(Bn||Wn!=null){let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${R.id}`,Dt.setAttribute("data-wrapper-id",R.id),Dt.setAttribute("data-component-directive-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),En||Dt.classList.add("persona-w-full"),y.appendChild(Dt),oe.push({messageId:R.id,fingerprint:we,bubble:Bn});return}}}if(!at)if(R.variant==="reasoning"&&R.reasoning){if(!se)return;at=Ul(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!ye)return;at=zl(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;at=Jl(R,o)}else{let yt=(nr=o.layout)==null?void 0:nr.messages;yt!=null&&yt.renderUserMessage&&R.role==="user"?at=yt.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):yt!=null&&yt.renderAssistantMessage&&R.role==="assistant"?at=yt.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):at=$l(R,h,yt,o.messageActions,K,{loadingIndicatorRenderer:V,widgetConfig:o}),R.role!=="user"&&at&&nc(at,R,o,k)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${R.id}`,Wt.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Wt.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(at),fm(go,R.id,we,Wt),y.appendChild(Wt)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let We=Ee.getAttribute("data-persona-ask-sheet-for");We&&!N.has(We)&&as(Ie.composerOverlay,We)}),(lt=(Xe=o.features)==null?void 0:Xe.toolCallDisplay)!=null&&lt.grouped){let R=[],Ee=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&ye){Ee.push(We);return}Ee.length>1&&R.push(Ee),Ee=[]}),Ee.length>1&&R.push(Ee),R.forEach((We,je)=>{var un,Ze;let we=We.map(dt=>Array.from(y.children).find(kn=>kn instanceof HTMLElement&&kn.getAttribute("data-wrapper-id")===dt.id)).filter(dt=>!!dt);if(we.length<2)return;let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id=`wrapper-tool-group-${je}-${We[0].id}`,Rt.setAttribute("data-wrapper-id",`tool-group-${je}-${We[0].id}`);let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Qt=document.createElement("div");Qt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let pn=`Called ${We.length} tools`,Wt=(Ze=(un=o.toolCall)==null?void 0:un.renderGroupedSummary)==null?void 0:Ze.call(un,{messages:We,toolCalls:We.map(dt=>dt.toolCall).filter(dt=>!!dt),defaultSummary:pn,config:o});$(Qt,Wt)||(Qt.textContent=pn);let Tn=document.createElement("div");Tn.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Qt,Tn),Rt.appendChild(at),we[0].before(Rt),we.forEach((dt,kn)=>{let fn=document.createElement("div");fn.className="persona-tool-group-item persona-relative",fn.setAttribute("data-persona-tool-group-item","true"),kn<we.length-1&&fn.setAttribute("data-persona-tool-group-connector","true"),fn.appendChild(dt),Tn.appendChild(fn)})})}hm(go,q);let ke=m.some(R=>R.role==="assistant"&&R.streaming),He=m[m.length-1],tt=(He==null?void 0:He.role)==="assistant"&&!He.streaming&&He.variant!=="approval";if(Gn&&m.some(R=>R.role==="user")&&!ke&&!tt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},Ee=r.find(je=>je.renderLoadingIndicator),We=null;if(Ee!=null&&Ee.renderLoadingIndicator&&(We=Ee.renderLoadingIndicator(R)),We===null&&((ct=o.loadingIndicator)!=null&&ct.render)&&(We=o.loadingIndicator.render(R)),We===null&&(We=ua()),We){let je=document.createElement("div"),we=((Re=o.loadingIndicator)==null?void 0:Re.showBubble)!==!1;je.className=we?["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(" "),je.setAttribute("data-typing-indicator","true"),je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",je.appendChild(We);let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id="wrapper-typing-indicator",Rt.setAttribute("data-wrapper-id","typing-indicator"),Rt.appendChild(je),y.appendChild(Rt)}}if(!Gn&&m.length>0){let R=m[m.length-1],Ee={config:o,lastMessage:R,messageCount:m.length},We=r.find(we=>we.renderIdleIndicator),je=null;if(We!=null&&We.renderIdleIndicator&&(je=We.renderIdleIndicator(Ee)),je===null&&((Le=o.loadingIndicator)!=null&&Le.renderIdle)&&(je=o.loadingIndicator.renderIdle(Ee)),je){let we=document.createElement("div"),Rt=((Ue=o.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;we.className=Rt?["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(" "),we.setAttribute("data-idle-indicator","true"),we.appendChild(je);let at=document.createElement("div");at.className="persona-flex",at.id="wrapper-idle-indicator",at.setAttribute("data-wrapper-id","idle-indicator"),at.appendChild(we),y.appendChild(at)}}if(Si(c,y),ue.length>0)for(let{messageId:R,fingerprint:Ee,bubble:We}of ue){let je=c.querySelector(`#wrapper-${R}`);je&&We!==null&&(je.replaceChildren(We),je.setAttribute("data-bubble-fp",Ee),Bo.set(R,Ee))}if(Bo.size>0)for(let R of Bo.keys())q.has(R)||Bo.delete(R);if(oe.length>0)for(let{messageId:R,fingerprint:Ee,bubble:We}of oe){let je=c.querySelector(`#wrapper-${R}`);je&&We!==null&&(je.replaceChildren(We),je.setAttribute("data-bubble-fp",Ee),To.set(R,Ee))}if(To.size>0)for(let R of To.keys())q.has(R)||To.delete(R)},Qo=null,Ha=()=>{var h;if(Qo)return;let c=y=>{let W=y.composedPath();W.includes(fe)||Ve&&W.includes(Ve)||Ht(!1,"user")};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ys=()=>{var m;if(!Qo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Qo,!0),Qo=null};ht.push(()=>ys());let Jo=null,Da=()=>{var h;if(Jo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ht(!1,"user"))};Jo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},vs=()=>{var m;if(!Jo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Jo,!0),Jo=null};ht.push(()=>vs());let Zo=!1,xs=new Set,Fa=()=>{var m,h,y,W;let c=(y=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((W=o.features)==null?void 0:W.streamAnimation)},Oo=()=>{var lt,ct,Re,Le;if(!M())return;let c=Ie.peekBanner,m=Ie.peekTextNode;if(!c||!m)return;if(E){c.classList.remove("persona-pill-peek--visible");return}let h=(lt=k==null?void 0:k.getMessages())!=null?lt:[],y;for(let Ue=h.length-1;Ue>=0;Ue--){let R=h[Ue];if(R.role==="assistant"&&R.content){y=R;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let W=y.content,V=!!y.streaming,$=Fa(),q=Mi($),N=q.type!=="none"?sa(q.type,$==null?void 0:$.plugins):null,Se=((ct=N==null?void 0:N.isAnimating)==null?void 0:ct.call(N,y))===!0,ue=N!==null&&(V||Se);ue&&N&&!xs.has(N.name)&&(Dl(N,e),xs.add(N.name));let oe=ue&&(N!=null&&N.containerClass)?N.containerClass:null,be=(Re=m.dataset.personaPeekStreamClass)!=null?Re:null;be&&be!==oe&&(m.classList.remove(be),delete m.dataset.personaPeekStreamClass),oe&&be!==oe&&(m.classList.add(oe),m.dataset.personaPeekStreamClass=oe),ue?(m.style.setProperty("--persona-stream-step",`${q.speed}ms`),m.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let ke=ue?Li(W,q.buffer,N,y,V):W;if(ue&&q.placeholder==="skeleton"&&V&&(!ke||!ke.trim())){let Ue=document.createElement("div"),R=ia();R.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(R),Si(m,Ue)}else{let Ue=Math.max(0,ke.length-100),R=ke.length>100?ke.slice(-100):ke,Ee=Gs(R);if(!ue||!N){let We=ke.length>100?`\u2026${R}`:R;m.textContent!==We&&(m.textContent=We)}else{let We=Ee;(N.wrap==="char"||N.wrap==="word")&&(We=aa(Ee,N.wrap,`peek-${y.id}`,{skipTags:N.skipTags,startIndex:Ue}));let je=document.createElement("div");if(je.innerHTML=We,N.useCaret&&R.length>0){let we=Ii(),Rt=je.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=Rt[Rt.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(we,at.nextSibling):je.appendChild(we)}Si(m,je),(Le=N.onAfterRender)==null||Le.call(N,{container:m,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Xe=Gn||Zo;c.classList.toggle("persona-pill-peek--visible",Xe)};if(M()){let c=Ie.peekBanner;if(c){let y=W=>{W.preventDefault(),W.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",y),ht.push(()=>{c.removeEventListener("pointerdown",y)})}let m=()=>{Zo||(Zo=!0,Oo())},h=()=>{Zo&&(Zo=!1,Oo())};de.addEventListener("pointerenter",m),de.addEventListener("pointerleave",h),ht.push(()=>{de.removeEventListener("pointerenter",m),de.removeEventListener("pointerleave",h)}),Ve&&(Ve.addEventListener("pointerenter",m),Ve.addEventListener("pointerleave",h),ht.push(()=>{Ve.removeEventListener("pointerenter",m),Ve.removeEventListener("pointerleave",h)}))}let Oa=c=>{var be,ke,He,tt,Xe,lt,ct,Re;let m=(ke=(be=o.launcher)==null?void 0:be.composerBar)!=null?ke:{},h=(He=m.expandedSize)!=null?He:"anchored",y=(tt=m.bottomOffset)!=null?tt:"16px",W=m.collapsedMaxWidth,V=(Xe=m.expandedMaxWidth)!=null?Xe:"880px",$=(lt=m.expandedTopOffset)!=null?lt:"5vh",q=(ct=m.modalMaxWidth)!=null?ct:"880px",N=(Re=m.modalMaxHeight)!=null?Re:"min(90vh, 800px)",Se="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",oe=fe.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",Ve){let Le=Ve.style;Le.bottom=y,Le.width=W!=null?W:""}if(c&&h!=="fullscreen"){if(h==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=q,oe.maxWidth=Se,oe.maxHeight=N,oe.height=N;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${y} + ${ue})`,oe.top=$,oe.width=V,oe.maxWidth=Se}},er=()=>{var N,Se,ue,oe,be,ke,He,tt;if(!A())return;if(M()){let lt=(ue=((Se=(N=o.launcher)==null?void 0:N.composerBar)!=null?Se:{}).expandedSize)!=null?ue:"anchored",ct=E?"expanded":"collapsed";fe.dataset.state=ct,fe.dataset.expandedSize=lt,Ve&&(Ve.dataset.state=ct,Ve.dataset.expandedSize=lt),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Oa(E),pe.style.display=E?"flex":"none",uo(),E?(Ha(),Da()):(ys(),vs()),Oo();return}let c=mn(o),m=(oe=e.ownerDocument.defaultView)!=null?oe:window,h=(ke=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?ke:640,y=(tt=(He=o.launcher)==null?void 0:He.mobileFullscreen)!=null?tt:!0,W=m.innerWidth<=h,V=y&&W&&B,$=Lo(o).reveal;E?(fe.style.removeProperty("display"),fe.style.display=c?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Ye?Ye.element.style.display="none":Je&&(Je.style.display="none")):(c?c&&($==="overlay"||$==="push")&&!V?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Ye?Ye.element.style.display=c?"none":"":Je&&(Je.style.display=c?"none":""))},Ht=(c,m="user")=>{var V,$;if(!A()||E===c)return;let h=E;E=c,er();let y=(()=>{var He,tt,Xe,lt,ct,Re,Le,Ue,R,Ee;let q=(tt=(He=o.launcher)==null?void 0:He.sidebarMode)!=null?tt:!1,N=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,Se=(ct=(lt=o.launcher)==null?void 0:lt.mobileFullscreen)!=null?ct:!0,ue=(Le=(Re=o.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Le:640,oe=N.innerWidth<=ue,be=mn(o)&&Se&&oe,ke=M()&&((Ee=(R=(Ue=o.launcher)==null?void 0:Ue.composerBar)==null?void 0:R.expandedSize)!=null?Ee:"fullscreen")==="fullscreen";return q||Se&&oe&&B||be||ke})();if(E&&y){if(!Gt){let q=e.getRootNode(),N=q instanceof ShadowRoot?q.host:e.closest(".persona-host");N&&(Gt=Fl(N,($=(V=o.launcher)==null?void 0:V.zIndex)!=null?$:yn))}Yt||(Yt=Ol(e.ownerDocument))}else E||(Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null);E&&(Xt(),Xo(!0));let W={open:E,source:m,timestamp:Date.now()};E&&!h?s.emit("widget:opened",W):!E&&h&&s.emit("widget:closed",W),s.emit("widget:state",{open:E,launcherEnabled:B,voiceActive:gt.active,streaming:k.isStreaming()})},_r=c=>{Kt(c?"stop":"send"),G&&(G.disabled=c),mo.buttons.forEach(m=>{m.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Vr=()=>{gt.active||J&&J.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Vr(),200)});let ws=()=>{var h,y,W,V,$,q,N,Se,ue,oe,be;Fn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Zn.textContent=(V=(W=o.copy)==null?void 0:W.welcomeSubtitle)!=null?V:"Ask anything about your account or products.",J.placeholder=(q=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?q:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let ke=((N=o.copy)==null?void 0:N.showWelcomeCard)!==!1;c.style.display=ke?"":"none",ke?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((ue=(Se=o.sendButton)==null?void 0:Se.useIcon)!=null&&ue)&&!(k!=null&&k.isStreaming())&&(Oe.textContent=(be=(oe=o.copy)==null?void 0:oe.sendButtonLabel)!=null?be:"Send"),J.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',J.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=>{g(m=>({...m,sessionId:c}))}});let ko=null,Na=()=>{ko==null&&(ko=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(ko),ko=null;return}let m=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=pi(m-y))})},100))};if(k=new wi(o,{onMessagesChanged(c){gr($e,c,ge),Na(),k&&(c.some(W=>W.role==="user")?mo.render([],k,J,c):mo.render(o.suggestionChips,k,J,c,o.suggestionChipsConfig)),Xo(!Gn),Ba(c);let m=[...c].reverse().find(y=>y.role==="user"),h=gt.lastUserMessageId;m&&m.id!==h&&(gt.lastUserMessageId=m.id,s.emit("user:message",m)),gt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Nr(c),Oo()},onStatusChanged(c){var y;let m=(y=o.statusIndicator)!=null?y:{};nt(cn,(W=>{var V,$,q,N;return W==="idle"?(V=m.idleText)!=null?V:bn.idle:W==="connecting"?($=m.connectingText)!=null?$:bn.connecting:W==="connected"?(q=m.connectedText)!=null?q:bn.connected:W==="error"?(N=m.errorText)!=null?N:bn.error:bn[W]})(c),m,c)},onStreamingChanged(c){Gn=c,_r(c),k&&gr($e,k.getMessages(),ge),c||Xo(!0),Oo()},onVoiceStatusChanged(c){var m,h;if(((h=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":Y(),te();break;case"speaking":Y(),ne();break;default:c==="idle"&&k.isBargeInActive()?(Y(),P(),G==null||G.setAttribute("aria-label","End voice session")):(gt.active=!1,Y(),so("system"),Pn());break}},onArtifactsState(c){$n=c,qn(),Nr()}}),Pt.current=k,((bd=(hd=o.voiceRecognition)==null?void 0:hd.provider)==null?void 0:bd.type)==="runtype")try{k.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&k.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Q||o.onSSEEvent)&&k.setSSEEventCallback((c,m)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,m),Te==null||Te.processEvent(c,m),Q==null||Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,h,y;c&&(c.metadata&&(d=cc(c.metadata),L.syncFromMetadata()),(m=c.messages)!=null&&m.length&&k.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&k.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Cs=()=>{var m,h,y;!M()||E||!((y=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ht(!0,"auto")},Ss=c=>{var W;if(c.preventDefault(),k.isStreaming()){k.cancel(),Te==null||Te.reset(),he==null||he.update();return}let m=J.value.trim(),h=(W=et==null?void 0:et.hasAttachments())!=null?W:!1;if(!m&&!h)return;Cs();let y;h&&(y=[],y.push(...et.getContentParts()),m&&y.push(Pl(m))),J.value="",J.style.height="auto",fr(),k.sendMessage(m,{contentParts:y}),h&&et.clearAttachments()},_a=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},$r={...Ai},Ur=!1,fr=()=>{$r={...Ai}},Va=()=>k.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),$a=c=>{if(!J)return;Ur=!0,J.value=c,J.dispatchEvent(new Event("input",{bubbles:!0})),Ur=!1;let m=J.value.length;J.setSelectionRange(m,m)},As=()=>{Ur||fr()},Ts=c=>{if(J){if(_a()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=J.selectionStart===0&&J.selectionEnd===0,h=pm({direction:c.key==="ArrowUp"?"up":"down",history:Va(),currentValue:J.value,atStart:m,state:$r});if($r=h.state,h.handled){c.preventDefault(),h.value!==void 0&&$a(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(k.isStreaming()){c.preventDefault();return}fr(),c.preventDefault(),Oe.click()}}},ks=c=>{c.key!=="Escape"||c.isComposing||k.isStreaming()&&c.composedPath().includes(pe)&&(k.cancel(),Te==null||Te.reset(),he==null||he.update(),fr(),c.preventDefault(),c.stopImmediatePropagation())},Es=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let m=cy(c.clipboardData);m.length!==0&&(c.preventDefault(),await et.handleFiles(m))},An=null,Yn=!1,No=null,st=null,Ms=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,hr=(c="user")=>{var V,$,q,N,Se,ue,oe;if(Yn||k.isStreaming())return;let m=Ms();if(!m)return;An=new m;let y=($=((V=o.voiceRecognition)!=null?V:{}).pauseDuration)!=null?$:2e3;An.continuous=!0,An.interimResults=!0,An.lang="en-US";let W=J.value;An.onresult=be=>{let ke="",He="";for(let Xe=0;Xe<be.results.length;Xe++){let lt=be.results[Xe],ct=lt[0].transcript;lt.isFinal?ke+=ct+" ":He=ct}let tt=W+ke+He;J.value=tt,No&&clearTimeout(No),(ke||He)&&(No=window.setTimeout(()=>{let Xe=J.value.trim();Xe&&An&&Yn&&(yo(),J.value="",J.style.height="auto",k.sendMessage(Xe,{viaVoice:!0}))},y))},An.onerror=be=>{be.error!=="no-speech"&&yo()},An.onend=()=>{if(Yn){let be=J.value.trim();be&&be!==W.trim()&&(J.value="",J.style.height="auto",k.sendMessage(be,{viaVoice:!0})),yo()}};try{if(An.start(),Yn=!0,gt.active=!0,c!=="system"&&(gt.manuallyDeactivated=!1),so(c),Pn(),G){let be=(q=o.voiceRecognition)!=null?q:{};st={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(N=be.iconName)!=null?N:"mic",iconSize:parseFloat((oe=(ue=be.iconSize)!=null?ue:(Se=o.sendButton)==null?void 0:Se.size)!=null?oe:"40")||24};let ke=be.recordingBackgroundColor,He=be.recordingIconColor,tt=be.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=ke!=null?ke:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=He!=null?He:"var(--persona-voice-recording-indicator, #ffffff)",He){let Xe=G.querySelector("svg");Xe&&Xe.setAttribute("stroke",He)}tt&&(G.style.borderColor=tt),G.setAttribute("aria-label","Stop voice recognition")}}catch{yo("system")}},yo=(c="user")=>{if(Yn){if(Yn=!1,No&&(clearTimeout(No),No=null),An){try{An.stop()}catch{}An=null}if(gt.active=!1,so(c),Pn(),G){if(G.classList.remove("persona-voice-recording"),st){G.style.backgroundColor=st.backgroundColor,G.style.color=st.color,G.style.borderColor=st.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",st.color||"currentColor"),st=null}G.setAttribute("aria-label","Start voice recognition")}}},zr=(c,m)=>{var lt,ct,Re,Le,Ue,R,Ee,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((lt=c==null?void 0:c.provider)==null?void 0:lt.type)==="runtype";if(!(h||y))return null;let V=b("div","persona-send-button-wrapper"),$=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button",$.setAttribute("aria-label","Start voice recognition");let q=(ct=c==null?void 0:c.iconName)!=null?ct:"mic",N=(Re=m==null?void 0:m.size)!=null?Re:"40px",Se=(Le=c==null?void 0:c.iconSize)!=null?Le:N,ue=parseFloat(Se)||24,oe=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:m==null?void 0:m.backgroundColor,be=(R=c==null?void 0:c.iconColor)!=null?R:m==null?void 0:m.textColor;$.style.width=Se,$.style.height=Se,$.style.minWidth=Se,$.style.minHeight=Se,$.style.fontSize="18px",$.style.lineHeight="1",be?$.style.color=be:$.style.color="var(--persona-text, #111827)";let He=Ae(q,ue,be||"currentColor",1.5);He?$.appendChild(He):$.textContent="\u{1F3A4}",oe?$.style.backgroundColor=oe:$.style.backgroundColor="",c!=null&&c.borderWidth&&($.style.borderWidth=c.borderWidth,$.style.borderStyle="solid"),c!=null&&c.borderColor&&($.style.borderColor=c.borderColor),c!=null&&c.paddingX&&($.style.paddingLeft=c.paddingX,$.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&($.style.paddingTop=c.paddingY,$.style.paddingBottom=c.paddingY),V.appendChild($);let tt=(Ee=c==null?void 0:c.tooltipText)!=null?Ee:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&tt){let je=b("div","persona-send-button-tooltip");je.textContent=tt,V.appendChild(je)}return{micButton:$,micButtonWrapper:V}},ze=()=>{var m,h,y,W,V;if(!G||st)return;let c=(m=o.voiceRecognition)!=null?m:{};st={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((V=(W=c.iconSize)!=null?W:(y=o.sendButton)==null?void 0:y.size)!=null?V:"40")||24}},T=(c,m)=>{var V,$,q,N,Se;if(!G)return;let h=G.querySelector("svg");h&&h.remove();let y=(Se=st==null?void 0:st.iconSize)!=null?Se:parseFloat((N=(q=(V=o.voiceRecognition)==null?void 0:V.iconSize)!=null?q:($=o.sendButton)==null?void 0:$.size)!=null?N:"40")||24,W=Ae(c,y,m,1.5);W&&G.appendChild(W)},z=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},P=()=>{var W;if(!G)return;ze();let c=(W=o.voiceRecognition)!=null?W:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(z(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let V=G.querySelector("svg");V&&V.setAttribute("stroke",h)}y&&(G.style.borderColor=y),G.setAttribute("aria-label","Stop voice recognition")},te=()=>{var q,N,Se,ue,oe,be,ke,He;if(!G)return;ze();let c=(q=o.voiceRecognition)!=null?q:{},m=k.getVoiceInterruptionMode(),h=(N=c.processingIconName)!=null?N:"loader",y=(ue=(Se=c.processingIconColor)!=null?Se:st==null?void 0:st.color)!=null?ue:"",W=(be=(oe=c.processingBackgroundColor)!=null?oe:st==null?void 0:st.backgroundColor)!=null?be:"",V=(He=(ke=c.processingBorderColor)!=null?ke:st==null?void 0:st.borderColor)!=null?He:"";z(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=W,G.style.borderColor=V;let $=y||"currentColor";G.style.color=$,T(h,$),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},ne=()=>{var Se,ue,oe,be,ke,He,tt,Xe,lt,ct,Re,Le;if(!G)return;ze();let c=(Se=o.voiceRecognition)!=null?Se:{},m=k.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,W=(He=c.speakingIconColor)!=null?He:m==="barge-in"?(be=(oe=c.recordingIconColor)!=null?oe:st==null?void 0:st.color)!=null?be:"":(ke=st==null?void 0:st.color)!=null?ke:"",V=(lt=c.speakingBackgroundColor)!=null?lt:m==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=st==null?void 0:st.backgroundColor)!=null?Xe:"",$=(Le=c.speakingBorderColor)!=null?Le:m==="barge-in"?(ct=c.recordingBorderColor)!=null?ct:"":(Re=st==null?void 0:st.borderColor)!=null?Re:"";z(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=V,G.style.borderColor=$;let q=W||"currentColor";G.style.color=q,T(y,q);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",N),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},Y=()=>{var c,m,h;G&&(z(),st&&(G.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",G.style.color=(m=st.color)!=null?m:"",G.style.borderColor=(h=st.borderColor)!=null?h:"",T(st.iconName,st.color||"currentColor"),st=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},qe=()=>{var c,m;if(((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let h=k.getVoiceStatus(),y=k.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){k.stopVoicePlayback();return}if(k.isBargeInActive()){k.stopVoicePlayback(),k.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),so("user"),Y()});return}k.toggleVoice().then(()=>{gt.active=k.isVoiceActive(),gt.manuallyDeactivated=!k.isVoiceActive(),Pn(),so("user"),k.isVoiceActive()?P():Y()});return}if(Yn){let h=J.value.trim();gt.manuallyDeactivated=!0,Pn(),yo("user"),h&&(J.value="",J.style.height="auto",k.sendMessage(h))}else gt.manuallyDeactivated=!1,Pn(),hr("user")};On=qe,G&&(G.addEventListener("click",qe),ht.push(()=>{var c,m;((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(k.isVoiceActive()&&k.toggleVoice(),Y()):yo("system"),G&&G.removeEventListener("click",qe)}));let Fe=s.on("assistant:complete",()=>{fs&&(gt.active||gt.manuallyDeactivated||fs==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!gt.active&&!gt.manuallyDeactivated&&(((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?k.toggleVoice().then(()=>{gt.active=k.isVoiceActive(),so("auto"),k.isVoiceActive()&&P()}):hr("auto"))},600))});ht.push(Fe);let it=s.on("action:resubmit",()=>{setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)});ht.push(it);let Ge=()=>{Ht(!E,"user")},Ye=null,Je=null;if(B&&!M()){let c=r.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:o,defaultRenderer:()=>da(o,Ge).element,onToggle:Ge});m&&(Je=m)}Je||(Ye=da(o,Ge))}Ye?e.appendChild(Ye.element):Je&&e.appendChild(Je),er(),mo.render(o.suggestionChips,k,J,void 0,o.suggestionChipsConfig),ws(),_r(k.isStreaming()),Xo(!0),Ia(),D&&(!B||M()?setTimeout(()=>Vr(),0):E&&setTimeout(()=>Vr(),200));let Xt=()=>{var N,Se,ue,oe,be,ke,He,tt,Xe,lt,ct,Re,Le,Ue,R,Ee,We,je,we,Rt,at,Qt;if(M()){vt(),er();return}let c=mn(o),m=(Se=(N=o.launcher)==null?void 0:N.sidebarMode)!=null?Se:!1,h=c||m||((oe=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?oe:!1),y=(be=e.ownerDocument.defaultView)!=null?be:window,W=(He=(ke=o.launcher)==null?void 0:ke.mobileFullscreen)!=null?He:!0,V=(Xe=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Xe:640,$=y.innerWidth<=V,q=W&&$&&B;try{if(q){uo(),Yr(e,o);return}if(w&&(w=!1,uo(),Yr(e,o)),!B&&!c){de.style.height="",de.style.width="";return}if(!m&&!c){let pn=(ct=(lt=o==null?void 0:o.launcher)==null?void 0:lt.width)!=null?ct:o==null?void 0:o.launcherWidth,Wt=pn!=null?pn:lo;de.style.width=Wt,de.style.maxWidth=Wt}if(Ao(),!h){let pn=y.innerHeight,Wt=64,Tn=(Le=(Re=o.launcher)==null?void 0:Re.heightOffset)!=null?Le:0,un=Math.max(200,pn-Wt),Ze=Math.min(640,un),dt=Math.max(200,Ze-Tn);de.style.height=`${dt}px`}}finally{if(vt(),er(),E&&B){let Wt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((Ee=(R=o.launcher)==null?void 0:R.mobileBreakpoint)!=null?Ee:640),Tn=(je=(We=o.launcher)==null?void 0:We.sidebarMode)!=null?je:!1,un=(Rt=(we=o.launcher)==null?void 0:we.mobileFullscreen)!=null?Rt:!0,Ze=mn(o)&&un&&Wt,dt=Tn||un&&Wt&&B||Ze;if(dt&&!Yt){let kn=e.getRootNode(),fn=kn instanceof ShadowRoot?kn.host:e.closest(".persona-host");fn&&!Gt&&(Gt=Fl(fn,(Qt=(at=o.launcher)==null?void 0:at.zIndex)!=null?Qt:yn)),Yt=Ol(e.ownerDocument)}else dt||(Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null)}}};Xt();let kt=(yd=e.ownerDocument.defaultView)!=null?yd:window;if(kt.addEventListener("resize",Xt),ht.push(()=>kt.removeEventListener("resize",Xt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{vt()});c.observe(_e),ht.push(()=>c.disconnect())}ho=X.scrollTop;let It=X.scrollHeight,rn=()=>{let c=X.scrollTop,m=X.scrollHeight,h=m<It;It=m;let{action:y,nextLastScrollTop:W}=ki({following:fo.isFollowing(),currentScrollTop:c,lastScrollTop:ho,nearBottom:oa(X,gs),userScrollThreshold:Ma,isAutoScrolling:Ho||ur||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ho=W,y==="resume"){Yo();return}y==="pause"&&bs()};X.addEventListener("scroll",rn,{passive:!0}),ht.push(()=>X.removeEventListener("scroll",rn));let gn=c=>{let m=Ei({following:fo.isFollowing(),deltaY:c.deltaY,nearBottom:oa(X,gs),resumeWhenNearBottom:!0});m==="pause"?bs():m==="resume"&&Yo()};X.addEventListener("wheel",gn,{passive:!0}),ht.push(()=>X.removeEventListener("wheel",gn)),Mt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,ho=X.scrollTop,Yo(),Xo(!0)}),ht.push(()=>Mt.remove()),ht.push(()=>{hs()});let dn=()=>{_&&(Kn&&(_.removeEventListener("click",Kn),Kn=null),A()?(_.style.display="",Kn=()=>{Ht(!1,"user")},_.addEventListener("click",Kn)):_.style.display="none")};dn(),(()=>{let{clearChatButton:c}=Ie;c&&c.addEventListener("click",()=>{k.clearMessages(),go.clear(),Yo(),as(Ie.composerOverlay);try{localStorage.removeItem(ls),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ls}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ls)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 m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},L.syncFromMetadata(),Q==null||Q.clear(),Te==null||Te.reset(),he==null||he.update()})})(),Ot&&Ot.addEventListener("submit",Ss),J==null||J.addEventListener("keydown",Ts),J==null||J.addEventListener("input",As),J==null||J.addEventListener("paste",Es);let ao=(vd=e.ownerDocument)!=null?vd:document;ao.addEventListener("keydown",ks,!0);let Tc="persona-attachment-drop-active",Ls=0,cl=()=>{Ls=0,pe.classList.remove(Tc)},qr=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},kc=c=>{!Gi(c.dataTransfer)||!qr()||(Ls++,Ls===1&&pe.classList.add(Tc))},Ec=c=>{!Gi(c.dataTransfer)||!qr()||(Ls--,Ls<=0&&cl())},Mc=c=>{!Gi(c.dataTransfer)||!qr()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Lc=c=>{var h;if(!Gi(c.dataTransfer)||!qr())return;c.preventDefault(),c.stopPropagation(),cl();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&et.handleFiles(m)},tr=!0;pe.addEventListener("dragenter",kc,tr),pe.addEventListener("dragleave",Ec,tr),e.addEventListener("dragover",Mc,tr),e.addEventListener("drop",Lc,tr);let Ua=e.ownerDocument,Ic=c=>{qr()&&c.preventDefault()},Rc=c=>{qr()&&c.preventDefault()};Ua.addEventListener("dragover",Ic),Ua.addEventListener("drop",Rc),ht.push(()=>{Ot&&Ot.removeEventListener("submit",Ss),J==null||J.removeEventListener("keydown",Ts),J==null||J.removeEventListener("input",As),J==null||J.removeEventListener("paste",Es),ao.removeEventListener("keydown",ks,!0)}),ht.push(()=>{pe.removeEventListener("dragenter",kc,tr),pe.removeEventListener("dragleave",Ec,tr),e.removeEventListener("dragover",Mc,tr),e.removeEventListener("drop",Lc,tr),Ua.removeEventListener("dragover",Ic),Ua.removeEventListener("drop",Rc),cl()}),ht.push(()=>{k.cancel()}),Ye?ht.push(()=>{Ye==null||Ye.destroy()}):Je&&ht.push(()=>{Je==null||Je.remove()});let tn={update(c){var nn,Eo,Vo,za,qa,ja,wr,Ka,Is,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Qp,Jp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,vu,xu,wu;let m=o.toolCall,h=o.messageActions,y=(nn=o.layout)==null?void 0:nn.messages,W=o.colorScheme,V=o.loadingIndicator,$=o.iterationDisplay,q=(Eo=o.features)==null?void 0:Eo.showReasoning,N=(Vo=o.features)==null?void 0:Vo.showToolCalls,Se=(za=o.features)==null?void 0:za.toolCallDisplay,ue=(qa=o.features)==null?void 0:qa.reasoningDisplay;o={...o,...c},uo(),Yr(e,o),ji(e,o),Ki(e,o),qn(),o.colorScheme!==W&&Go();let oe=rc.getForInstance(o.plugins);r.length=0,r.push(...oe),B=(wr=(ja=o.launcher)==null?void 0:ja.enabled)!=null?wr:!0,I=(Is=(Ka=o.launcher)==null?void 0:Ka.autoExpand)!=null?Is:!1,se=(Ed=(kd=o.features)==null?void 0:kd.showReasoning)!=null?Ed:!0,ye=(Ld=(Md=o.features)==null?void 0:Md.showToolCalls)!=null?Ld:!0,Ce=(Rd=(Id=o.features)==null?void 0:Id.scrollToBottom)!=null?Rd:{},zt(),Fo();let be=le;if(le=(Wd=(Pd=o.features)==null?void 0:Pd.showEventStreamToggle)!=null?Wd:!1,le&&!be){if(Q||(ee=new fa(ve),Q=new ga(Me,ee),Te=Te!=null?Te:new ha,ee.open().then(()=>Q==null?void 0:Q.restore()).catch(()=>{}),k.setSSEEventCallback((Z,wt)=>{var Nt;(Nt=o.onSSEEvent)==null||Nt.call(o,Z,wt),Te==null||Te.processEvent(Z,wt),Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(wt)})})),!mt&&Ne){let Z=(Hd=(Bd=o.features)==null?void 0:Bd.eventStream)==null?void 0:Hd.classNames,wt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Z!=null&&Z.toggleButton?" "+Z.toggleButton:"");mt=b("button",wt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Ln.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Nt=Ae("activity","18px","currentColor",1.5);Nt&&mt.appendChild(Nt);let pt=Ie.clearChatButtonWrapper,Lt=Ie.closeButtonWrapper,sn=pt||Lt;sn&&sn.parentNode===Ne?Ne.insertBefore(mt,sn):Ne.appendChild(mt),mt.addEventListener("click",()=>{ce?Nn():wn()})}}else!le&&be&&(Nn(),mt&&(mt.remove(),mt=null),Q==null||Q.clear(),ee==null||ee.destroy(),Q=null,ee=null,Te==null||Te.reset(),Te=null);if(((Dd=o.launcher)==null?void 0:Dd.enabled)===!1&&Ye&&(Ye.destroy(),Ye=null),((Fd=o.launcher)==null?void 0:Fd.enabled)===!1&&Je&&(Je.remove(),Je=null),((Od=o.launcher)==null?void 0:Od.enabled)!==!1&&!Ye&&!Je){let Z=r.find(wt=>wt.renderLauncher);if(Z!=null&&Z.renderLauncher){let wt=Z.renderLauncher({config:o,defaultRenderer:()=>da(o,Ge).element,onToggle:Ge});wt&&(Je=wt,e.appendChild(Je))}Je||(Ye=da(o,Ge),e.appendChild(Ye.element))}Ye&&Ye.update(o),De&&((Nd=o.launcher)==null?void 0:Nd.title)!==void 0&&(De.textContent=o.launcher.title),Qe&&((_d=o.launcher)==null?void 0:_d.subtitle)!==void 0&&(Qe.textContent=o.launcher.subtitle);let ke=(Vd=o.layout)==null?void 0:Vd.header;if((ke==null?void 0:ke.layout)!==v&&Ne){let Z=ke?Bi(o,ke,{showClose:A(),onClose:()=>Ht(!1,"user")}):Lr({config:o,showClose:A(),onClose:()=>Ht(!1,"user")});Ne.replaceWith(Z.header),Ne=Z.header,ae=Z.iconHolder,De=Z.headerTitle,Qe=Z.headerSubtitle,_=Z.closeButton,v=ke==null?void 0:ke.layout}else if(ke&&(ae&&(ae.style.display=ke.showIcon===!1?"none":""),De&&(De.style.display=ke.showTitle===!1?"none":""),Qe&&(Qe.style.display=ke.showSubtitle===!1?"none":""),_&&(_.style.display=ke.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let Z=ke.showClearChat;if(Z!==void 0){Ie.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:wt}=Ie;wt&&!wt.classList.contains("persona-absolute")&&(Z?wt.classList.remove("persona-ml-auto"):wt.classList.add("persona-ml-auto"))}}let tt=(($d=o.layout)==null?void 0:$d.showHeader)!==!1;Ne&&(Ne.style.display=tt?"":"none");let Xe=((Ud=o.layout)==null?void 0:Ud.showFooter)!==!1;_e&&(_e.style.display=Xe?"":"none"),vt(),Fo(),B!==H?B?Ht(I,"auto"):(E=!0,er()):I!==F&&Ht(I,"auto"),F=I,H=B,Xt(),dn();let Re=JSON.stringify(c.toolCall)!==JSON.stringify(m),Le=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ue=JSON.stringify((zd=o.layout)==null?void 0:zd.messages)!==JSON.stringify(y),R=((qd=o.loadingIndicator)==null?void 0:qd.render)!==(V==null?void 0:V.render)||((jd=o.loadingIndicator)==null?void 0:jd.renderIdle)!==(V==null?void 0:V.renderIdle)||((Kd=o.loadingIndicator)==null?void 0:Kd.showBubble)!==(V==null?void 0:V.showBubble),Ee=o.iterationDisplay!==$,We=((Yd=(Gd=o.features)==null?void 0:Gd.showReasoning)!=null?Yd:!0)!==(q!=null?q:!0)||((Qd=(Xd=o.features)==null?void 0:Xd.showToolCalls)!=null?Qd:!0)!==(N!=null?N:!0)||JSON.stringify((Jd=o.features)==null?void 0:Jd.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((Zd=o.features)==null?void 0:Zd.reasoningDisplay)!==JSON.stringify(ue);(Re||Le||Ue||R||Ee||We)&&k&&(ms++,gr($e,k.getMessages(),ge));let we=(ep=o.launcher)!=null?ep:{},Rt=(tp=we.headerIconHidden)!=null?tp:!1,at=(op=(np=o.layout)==null?void 0:np.header)==null?void 0:op.showIcon,Qt=Rt||at===!1,pn=we.headerIconName,Wt=(rp=we.headerIconSize)!=null?rp:"48px";if(ae){let Z=pe.querySelector(".persona-border-b-persona-divider"),wt=Z==null?void 0:Z.querySelector(".persona-flex-col");if(Qt)ae.style.display="none",Z&&wt&&!Z.contains(wt)&&Z.insertBefore(wt,Z.firstChild);else{if(ae.style.display="",ae.style.height=Wt,ae.style.width=Wt,Z&&wt&&(Z.contains(ae)?ae.nextSibling!==wt&&(ae.remove(),Z.insertBefore(ae,wt)):Z.insertBefore(ae,wt)),pn){let pt=parseFloat(Wt)||24,Lt=Ae(pn,pt*.6,"#ffffff",2);Lt?ae.replaceChildren(Lt):ae.textContent=(sp=we.agentIconText)!=null?sp:"\u{1F4AC}"}else if(we.iconUrl){let pt=ae.querySelector("img");if(pt)pt.src=we.iconUrl,pt.style.height=Wt,pt.style.width=Wt;else{let Lt=document.createElement("img");Lt.src=we.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Wt,Lt.style.width=Wt,ae.replaceChildren(Lt)}}else{let pt=ae.querySelector("svg"),Lt=ae.querySelector("img");(pt||Lt)&&ae.replaceChildren(),ae.textContent=(ap=we.agentIconText)!=null?ap:"\u{1F4AC}"}let Nt=ae.querySelector("img");Nt&&(Nt.style.height=Wt,Nt.style.width=Wt)}}let Tn=(lp=(ip=o.layout)==null?void 0:ip.header)==null?void 0:lp.showTitle,un=(dp=(cp=o.layout)==null?void 0:cp.header)==null?void 0:dp.showSubtitle;if(De&&(De.style.display=Tn===!1?"none":""),Qe&&(Qe.style.display=un===!1?"none":""),_){((up=(pp=o.layout)==null?void 0:pp.header)==null?void 0:up.showCloseButton)===!1?_.style.display="none":_.style.display="";let wt=(mp=we.closeButtonSize)!=null?mp:"32px",Nt=(gp=we.closeButtonPlacement)!=null?gp:"inline";_.style.height=wt,_.style.width=wt;let{closeButtonWrapper:pt}=Ie,Lt=Nt==="top-right",sn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&Lt!==sn)if(pt.remove(),Lt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(pt);else{let ut=(hp=(fp=we.clearChat)==null?void 0:fp.placement)!=null?hp:"inline",an=(yp=(bp=we.clearChat)==null?void 0:bp.enabled)!=null?yp:!0;pt.className=an&&ut==="inline"?"":"persona-ml-auto";let Dn=pe.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(pt)}if(_.style.color=we.closeButtonColor||Ln.actionIconColor,we.closeButtonBackgroundColor?(_.style.backgroundColor=we.closeButtonBackgroundColor,_.classList.remove("hover:persona-bg-gray-100")):(_.style.backgroundColor="",_.classList.add("hover:persona-bg-gray-100")),we.closeButtonBorderWidth||we.closeButtonBorderColor){let ut=we.closeButtonBorderWidth||"0px",an=we.closeButtonBorderColor||"transparent";_.style.border=`${ut} solid ${an}`,_.classList.remove("persona-border-none")}else _.style.border="",_.classList.add("persona-border-none");we.closeButtonBorderRadius?(_.style.borderRadius=we.closeButtonBorderRadius,_.classList.remove("persona-rounded-full")):(_.style.borderRadius="",_.classList.add("persona-rounded-full")),we.closeButtonPaddingX?(_.style.paddingLeft=we.closeButtonPaddingX,_.style.paddingRight=we.closeButtonPaddingX):(_.style.paddingLeft="",_.style.paddingRight=""),we.closeButtonPaddingY?(_.style.paddingTop=we.closeButtonPaddingY,_.style.paddingBottom=we.closeButtonPaddingY):(_.style.paddingTop="",_.style.paddingBottom="");let hn=(vp=we.closeButtonIconName)!=null?vp:"x",vo=(xp=we.closeButtonIconText)!=null?xp:"\xD7";_.innerHTML="";let Mn=Ae(hn,"28px","currentColor",1);Mn?_.appendChild(Mn):_.textContent=vo;let Jt=(wp=we.closeButtonTooltipText)!=null?wp:"Close chat",Qn=(Cp=we.closeButtonShowTooltip)!=null?Cp:!0;if(_.setAttribute("aria-label",Jt),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),Qn&&Jt)){let ut=null,an=()=>{if(ut||!_)return;let Cr=_.ownerDocument,Rs=Cr.body;if(!Rs)return;ut=Mo(Cr,"div","persona-clear-chat-tooltip"),ut.textContent=Jt;let Ps=Mo(Cr,"div");Ps.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Ps);let Sr=_.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(rr),ut.style.left=`${Sr.left+Sr.width/2}px`,ut.style.top=`${Sr.top-8}px`,ut.style.transform="translate(-50%, -100%)",Rs.appendChild(ut)},Dn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};pt.addEventListener("mouseenter",an),pt.addEventListener("mouseleave",Dn),_.addEventListener("focus",an),_.addEventListener("blur",Dn),pt._cleanupTooltip=()=>{Dn(),pt&&(pt.removeEventListener("mouseenter",an),pt.removeEventListener("mouseleave",Dn)),_&&(_.removeEventListener("focus",an),_.removeEventListener("blur",Dn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:dt}=Ie;if(Ze){let Z=(Sp=we.clearChat)!=null?Sp:{},wt=(Ap=Z.enabled)!=null?Ap:!0,Nt=(kp=(Tp=o.layout)==null?void 0:Tp.header)==null?void 0:kp.showClearChat,pt=Nt!==void 0?Nt:wt,Lt=(Ep=Z.placement)!=null?Ep:"inline";if(dt){dt.style.display=pt?"":"none";let{closeButtonWrapper:sn}=Ie;!M()&&sn&&!sn.classList.contains("persona-absolute")&&(pt?sn.classList.remove("persona-ml-auto"):sn.classList.add("persona-ml-auto"));let hn=Lt==="top-right",vo=dt.classList.contains("persona-absolute");if(!M()&&hn!==vo&&pt){if(dt.remove(),hn)dt.className="persona-absolute persona-top-4 persona-z-50",dt.style.right="48px",pe.style.position="relative",pe.appendChild(dt);else{dt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",dt.style.right="";let Jt=pe.querySelector(".persona-border-b-persona-divider"),Qn=Ie.closeButtonWrapper;Jt&&Qn&&Qn.parentElement===Jt?Jt.insertBefore(dt,Qn):Jt&&Jt.appendChild(dt)}let Mn=Ie.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(hn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(pt){if(!M()){let ut=(Mp=Z.size)!=null?Mp:"32px";Ze.style.height=ut,Ze.style.width=ut}let sn=(Lp=Z.iconName)!=null?Lp:"refresh-cw",hn=(Ip=Z.iconColor)!=null?Ip:"";Ze.style.color=hn||Ln.actionIconColor,Ze.innerHTML="";let vo=M()?"14px":"20px",Mn=Ae(sn,vo,"currentColor",2);if(Mn&&Ze.appendChild(Mn),Z.backgroundColor?(Ze.style.backgroundColor=Z.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let ut=Z.borderWidth||"0px",an=Z.borderColor||"transparent";Ze.style.border=`${ut} solid ${an}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");Z.borderRadius?(Ze.style.borderRadius=Z.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),Z.paddingX?(Ze.style.paddingLeft=Z.paddingX,Ze.style.paddingRight=Z.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),Z.paddingY?(Ze.style.paddingTop=Z.paddingY,Ze.style.paddingBottom=Z.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let Jt=(Rp=Z.tooltipText)!=null?Rp:"Clear chat",Qn=(Pp=Z.showTooltip)!=null?Pp:!0;if(Ze.setAttribute("aria-label",Jt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Qn&&Jt)){let ut=null,an=()=>{if(ut||!Ze)return;let Cr=Ze.ownerDocument,Rs=Cr.body;if(!Rs)return;ut=Mo(Cr,"div","persona-clear-chat-tooltip"),ut.textContent=Jt;let Ps=Mo(Cr,"div");Ps.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Ps);let Sr=Ze.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(rr),ut.style.left=`${Sr.left+Sr.width/2}px`,ut.style.top=`${Sr.top-8}px`,ut.style.transform="translate(-50%, -100%)",Rs.appendChild(ut)},Dn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",an),dt.addEventListener("mouseleave",Dn),Ze.addEventListener("focus",an),Ze.addEventListener("blur",Dn),dt._cleanupTooltip=()=>{Dn(),dt&&(dt.removeEventListener("mouseenter",an),dt.removeEventListener("mouseleave",Dn)),Ze&&(Ze.removeEventListener("focus",an),Ze.removeEventListener("blur",Dn))}}}}let kn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ac],fn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ba.message,ba.messageAndClick];L=ic({parsers:kn,handlers:fn,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ge=pg(o,L,j),k.updateConfig(o),gr($e,k.getMessages(),ge),mo.render(o.suggestionChips,k,J,void 0,o.suggestionChipsConfig),ws(),_r(k.isStreaming());let br=((Wp=o.voiceRecognition)==null?void 0:Wp.enabled)===!0,yr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),vr=((Hp=(Bp=o.voiceRecognition)==null?void 0:Bp.provider)==null?void 0:Hp.type)==="runtype";if(br&&(yr||vr))if(!G||!ft){let Z=zr(o.voiceRecognition,o.sendButton);Z&&(G=Z.micButton,ft=Z.micButtonWrapper,_t.insertBefore(ft,In),G.addEventListener("click",qe),G.disabled=k.isStreaming())}else{let Z=(Dp=o.voiceRecognition)!=null?Dp:{},wt=(Fp=o.sendButton)!=null?Fp:{},Nt=(Op=Z.iconName)!=null?Op:"mic",pt=(Np=wt.size)!=null?Np:"40px",Lt=(_p=Z.iconSize)!=null?_p:pt,sn=parseFloat(Lt)||24;G.style.width=Lt,G.style.height=Lt,G.style.minWidth=Lt,G.style.minHeight=Lt;let hn=($p=(Vp=Z.iconColor)!=null?Vp:wt.textColor)!=null?$p:"currentColor";G.innerHTML="";let vo=Ae(Nt,sn,hn,2);vo?G.appendChild(vo):G.textContent="\u{1F3A4}";let Mn=(Up=Z.backgroundColor)!=null?Up:wt.backgroundColor;Mn?G.style.backgroundColor=Mn:G.style.backgroundColor="",hn?G.style.color=hn:G.style.color="var(--persona-text, #111827)",Z.borderWidth?(G.style.borderWidth=Z.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Z.borderColor?G.style.borderColor=Z.borderColor:G.style.borderColor="",Z.paddingX?(G.style.paddingLeft=Z.paddingX,G.style.paddingRight=Z.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Z.paddingY?(G.style.paddingTop=Z.paddingY,G.style.paddingBottom=Z.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Jt=ft==null?void 0:ft.querySelector(".persona-send-button-tooltip"),Qn=(zp=Z.tooltipText)!=null?zp:"Start voice recognition";if(((qp=Z.showTooltip)!=null?qp:!1)&&Qn)if(Jt)Jt.textContent=Qn,Jt.style.display="";else{let an=document.createElement("div");an.className="persona-send-button-tooltip",an.textContent=Qn,ft==null||ft.insertBefore(an,G)}else Jt&&(Jt.style.display="none");ft.style.display="",G.disabled=k.isStreaming()}else G&&ft&&(ft.style.display="none",((Kp=(jp=o.voiceRecognition)==null?void 0:jp.provider)==null?void 0:Kp.type)==="runtype"?k.isVoiceActive()&&k.toggleVoice():Yn&&yo());if(((Gp=o.attachments)==null?void 0:Gp.enabled)===!0)if(!Ut||!ot){let Z=(Yp=o.attachments)!=null?Yp:{},Nt=(Qp=((Xp=o.sendButton)!=null?Xp:{}).size)!=null?Qp:"40px";xe||(xe=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xe.style.display="none",Ot.insertBefore(xe,J)),ie||(ie=document.createElement("input"),ie.type="file",ie.accept=((Jp=Z.allowedTypes)!=null?Jp:$o).join(","),ie.multiple=((Zp=Z.maxFiles)!=null?Zp:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Ot.insertBefore(ie,J)),Ut=b("div","persona-send-button-wrapper"),ot=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ot.type="button",ot.setAttribute("aria-label",(eu=Z.buttonTooltipText)!=null?eu:"Attach file");let pt=(tu=Z.buttonIconName)!=null?tu:"paperclip",Lt=Nt,sn=parseFloat(Lt)||40,hn=Math.round(sn*.6);ot.style.width=Lt,ot.style.height=Lt,ot.style.minWidth=Lt,ot.style.minHeight=Lt,ot.style.fontSize="18px",ot.style.lineHeight="1",ot.style.backgroundColor="transparent",ot.style.color="var(--persona-primary, #111827)",ot.style.border="none",ot.style.borderRadius="6px",ot.style.transition="background-color 0.15s ease",ot.addEventListener("mouseenter",()=>{ot.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ot.addEventListener("mouseleave",()=>{ot.style.backgroundColor="transparent"});let vo=Ae(pt,hn,"currentColor",1.5);vo?ot.appendChild(vo):ot.textContent="\u{1F4CE}",ot.addEventListener("click",Qn=>{Qn.preventDefault(),ie==null||ie.click()}),Ut.appendChild(ot);let Mn=(nu=Z.buttonTooltipText)!=null?nu:"Attach file",Jt=b("div","persona-send-button-tooltip");Jt.textContent=Mn,Ut.appendChild(Jt),At.append(Ut),!et&&ie&&xe&&(et=ta.fromConfig(Z),et.setPreviewsContainer(xe),ie.addEventListener("change",async()=>{et&&(ie!=null&&ie.files)&&(await et.handleFileSelect(ie.files),ie.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(ug(Z.dropOverlay))}else{Ut.style.display="";let Z=(ou=o.attachments)!=null?ou:{};ie&&(ie.accept=((ru=Z.allowedTypes)!=null?ru:$o).join(","),ie.multiple=((su=Z.maxFiles)!=null?su:4)>1),et&&et.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}else Ut&&(Ut.style.display="none"),et&&et.clearAttachments(),(au=pe.querySelector(".persona-attachment-drop-overlay"))==null||au.remove();let qt=(iu=o.sendButton)!=null?iu:{},xr=(lu=qt.useIcon)!=null?lu:!1,nr=(cu=qt.iconText)!=null?cu:"\u2191",yt=qt.iconName,Wn=(du=qt.tooltipText)!=null?du:"Send message",_o=(pu=qt.showTooltip)!=null?pu:!1,En=(uu=qt.size)!=null?uu:"40px",Bn=qt.backgroundColor,Dt=qt.textColor;if(xr){if(Oe.style.width=En,Oe.style.height=En,Oe.style.minWidth=En,Oe.style.minHeight=En,Oe.style.fontSize="18px",Oe.style.lineHeight="1",Oe.innerHTML="",Dt?Oe.style.color=Dt:Oe.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Z=parseFloat(En)||24,wt=(Dt==null?void 0:Dt.trim())||"currentColor",Nt=Ae(yt,Z,wt,2);Nt?Oe.appendChild(Nt):Oe.textContent=nr}else Oe.textContent=nr;Oe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Bn?(Oe.style.backgroundColor=Bn,Oe.classList.remove("persona-bg-persona-primary")):(Oe.style.backgroundColor="",Oe.classList.add("persona-bg-persona-primary"))}else Oe.textContent=(gu=(mu=o.copy)==null?void 0:mu.sendButtonLabel)!=null?gu:"Send",Oe.style.width="",Oe.style.height="",Oe.style.minWidth="",Oe.style.minHeight="",Oe.style.fontSize="",Oe.style.lineHeight="",Oe.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",Bn?(Oe.style.backgroundColor=Bn,Oe.classList.remove("persona-bg-persona-accent")):Oe.classList.add("persona-bg-persona-accent"),Dt?Oe.style.color=Dt:Oe.classList.add("persona-text-white");qt.borderWidth?(Oe.style.borderWidth=qt.borderWidth,Oe.style.borderStyle="solid"):(Oe.style.borderWidth="",Oe.style.borderStyle=""),qt.borderColor?Oe.style.borderColor=qt.borderColor:Oe.style.borderColor="",qt.paddingX?(Oe.style.paddingLeft=qt.paddingX,Oe.style.paddingRight=qt.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),qt.paddingY?(Oe.style.paddingTop=qt.paddingY,Oe.style.paddingBottom=qt.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let $t=In==null?void 0:In.querySelector(".persona-send-button-tooltip");if(_o&&Wn)if($t)$t.textContent=Wn,$t.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=Wn,In==null||In.insertBefore(Z,Oe)}else $t&&($t.style.display="none");let Ft=(vu=(fu=o.layout)==null?void 0:fu.contentMaxWidth)!=null?vu:M()?(yu=(bu=(hu=o.launcher)==null?void 0:hu.composerBar)==null?void 0:bu.contentMaxWidth)!=null?yu:"720px":void 0;Ft?($e.style.maxWidth=Ft,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ot&&(Ot.style.maxWidth=Ft,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),St&&(St.style.maxWidth=Ft,St.style.marginLeft="auto",St.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),St&&(St.style.maxWidth="",St.style.marginLeft="",St.style.marginRight=""));let jt=(xu=o.statusIndicator)!=null?xu:{},Hn=(wu=jt.visible)!=null?wu:!0;if(cn.style.display=Hn?"":"none",k){let Z=k.getStatus();nt(cn,(Nt=>{var pt,Lt,sn,hn;return Nt==="idle"?(pt=jt.idleText)!=null?pt:bn.idle:Nt==="connecting"?(Lt=jt.connectingText)!=null?Lt:bn.connecting:Nt==="connected"?(sn=jt.connectedText)!=null?sn:bn.connected:Nt==="error"?(hn=jt.errorText)!=null?hn:bn.error:bn[Nt]})(Z),jt,Z)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Xn=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Xn)},open(){A()&&Ht(!0,"api")},close(){A()&&Ht(!1,"api")},toggle(){A()&&Ht(!E,"api")},clearChat(){Cn=!1,k.clearMessages(),go.clear(),Yo();try{localStorage.removeItem(ls),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ls}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ls)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}d={},L.syncFromMetadata(),Q==null||Q.clear(),Te==null||Te.reset(),he==null||he.update()},setMessage(c){return!J||k.isStreaming()?!1:(!E&&A()&&Ht(!0,"system"),J.value=c,J.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(k.isStreaming())return!1;let m=(c==null?void 0:c.trim())||J.value.trim();return m?(!E&&A()&&Ht(!0,"system"),J.value="",J.style.height="auto",k.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return k.isStreaming()?!1:((h=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(k.isVoiceActive()||(!E&&A()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),k.toggleVoice().then(()=>{gt.active=k.isVoiceActive(),so("user"),k.isVoiceActive()&&P()})),!0):Yn?!0:Ms()?(!E&&A()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),hr("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?k.isVoiceActive()?(k.toggleVoice().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),so("user"),Y()}),!0):!1:Yn?(gt.manuallyDeactivated=!0,Pn(),yo("user"),!0):!1},injectMessage(c){return!E&&A()&&Ht(!0,"system"),k.injectMessage(c)},injectAssistantMessage(c){!E&&A()&&Ht(!0,"system");let m=k.injectAssistantMessage(c);return O&&(O=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)),m},injectUserMessage(c){return!E&&A()&&Ht(!0,"system"),k.injectUserMessage(c)},injectSystemMessage(c){return!E&&A()&&Ht(!0,"system"),k.injectSystemMessage(c)},injectMessageBatch(c){return!E&&A()&&Ht(!0,"system"),k.injectMessageBatch(c)},injectComponentDirective(c){return!E&&A()&&Ht(!0,"system"),k.injectComponentDirective(c)},injectTestMessage(c){!E&&A()&&Ht(!0,"system"),k.injectTestEvent(c)},async connectStream(c,m){return k.connectStream(c,m)},__pushEventStreamEvent(c){Q&&(Te==null||Te.processEvent(c.type,c.payload),Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!le||!Q||wn()},hideEventStream(){ce&&Nn()},isEventStreamVisible(){return ce},showArtifacts(){po(o)&&(Cn=!1,qn(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){po(o)&&(Cn=!0,qn())},upsertArtifact(c){return po(o)?(Cn=!1,k.upsertArtifact(c)):null},selectArtifact(c){po(o)&&k.selectArtifact(c)},clearArtifacts(){po(o)&&k.clearArtifacts()},getArtifacts(){var c;return(c=k==null?void 0:k.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=k==null?void 0:k.getSelectedArtifactId())!=null?c:null},focusInput(){return B&&!E&&!M()||!J?!1:(J.focus(),!0)},async resolveApproval(c,m){let y=k.getMessages().find(W=>{var V;return W.variant==="approval"&&((V=W.approval)==null?void 0:V.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){k.resolveWebMcpApproval(y.id,m);return}return k.resolveApproval(y.approval,m)},getMessages(){return k.getMessages()},getStatus(){return k.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return A()&&E},isVoiceActive(){return gt.active},getState(){return{open:A()&&E,launcherEnabled:B,voiceActive:gt.active,streaming:k.isStreaming()}},showCSATFeedback(c){!E&&A()&&Ht(!0,"system");let m=$e.querySelector(".persona-feedback-container");m&&m.remove();let h=lg({onSubmit:async(y,W)=>{var V;k.isClientTokenMode()&&await k.submitCSATFeedback(y,W),(V=c==null?void 0:c.onSubmit)==null||V.call(c,y,W)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!E&&A()&&Ht(!0,"system");let m=$e.querySelector(".persona-feedback-container");m&&m.remove();let h=cg({onSubmit:async(y,W)=>{var V;k.isClientTokenMode()&&await k.submitNPSFeedback(y,W),(V=c==null?void 0:c.onSubmit)==null||V.call(c,y,W)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return k.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return k.submitNPSFeedback(c,m)},destroy(){ko!=null&&(clearInterval(ko),ko=null),ht.forEach(c=>c()),fe.remove(),Ve==null||Ve.remove(),Ye==null||Ye.destroy(),Je==null||Je.remove(),Kn&&_.removeEventListener("click",Kn)}};if((((xd=n==null?void 0:n.debugTools)!=null?xd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ht.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),ht.push(()=>{window.removeEventListener("persona:focusInput",m)}),le){let q=Se=>{let ue=Se.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.showEventStream()},N=Se=>{let ue=Se.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",N),ht.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",N)})}let h=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&tn.showArtifacts()},y=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&tn.hideArtifacts()},W=q=>{let N=q.detail;N!=null&&N.instanceId&&N.instanceId!==c||N!=null&&N.artifact&&tn.upsertArtifact(N.artifact)},V=q=>{let N=q.detail;N!=null&&N.instanceId&&N.instanceId!==c||typeof(N==null?void 0:N.id)=="string"&&tn.selectArtifact(N.id)},$=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",V),window.addEventListener("persona:clearArtifacts",$),ht.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",V),window.removeEventListener("persona:clearArtifacts",$)})}let io=dy(o.persistState);if(io&&A()){let c=py(io.storage),m=`${io.keyPrefix}widget-open`,h=`${io.keyPrefix}widget-voice`,y=`${io.keyPrefix}widget-voice-mode`;if(c){let W=((wd=io.persist)==null?void 0:wd.openState)&&c.getItem(m)==="true",V=((Cd=io.persist)==null?void 0:Cd.voiceState)&&c.getItem(h)==="true",$=((Sd=io.persist)==null?void 0:Sd.voiceState)&&c.getItem(y)==="true";if(W&&setTimeout(()=>{tn.open(),setTimeout(()=>{var q;if(V||$)tn.startVoiceRecognition();else if((q=io.persist)!=null&&q.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(Ad=io.persist)!=null&&Ad.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Td=io.persist)!=null&&Td.voiceState&&(s.on("voice:state",q=>{c.setItem(h,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),io.clearOnChatClear){let q=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(y)},N=()=>q();window.addEventListener("persona:clear-chat",N),ht.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return u&&A()&&setTimeout(()=>{tn.open()},0),Oo(),tn};var uy=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},gg=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},mc=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=""},fg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",mc(e)},dc=e=>{e.style.transition=""},pc=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=""},uc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Yi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},my=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},gy=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},hg=(e,t,n,o,r,s,a)=>{var x,C,L,B,I,D;let i=Lo(s),d=i.reveal==="push";my(e,t,n,o,d),gy(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(C=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,p=(B=(L=s==null?void 0:s.launcher)==null?void 0:L.mobileBreakpoint)!=null?B:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),pc(t),dc(o),fg(o),uc(n),Yi(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",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((D=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?D:yn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),fg(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",pc(t),dc(o),uc(n),Yi(r,o);let F=i.animate?"transform 180ms ease":"none",H=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":H;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=F,o.style.transform=v,o.style.pointerEvents=a?"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",dc(o),mc(o),Yi(r,o);let F=uy(i.width,e.clientWidth),H=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",w=i.side==="right"?a?`translateX(-${F}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${F}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${H+F}px`,t.style.transition=v,t.style.transform=w,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${H}px`,n.style.maxWidth=`${H}px`,n.style.minWidth=`${H}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.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",pc(t),mc(o),uc(n),Yi(r,o);let F=i.reveal==="emerge";F?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let H=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",w=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${H}`,o.style.width=H,o.style.maxWidth=H,o.style.minWidth=H,o.style.minHeight="0",o.style.position="relative",o.style.overflow=F||w?"hidden":"visible",o.style.transition=v,F&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},fy=(e,t)=>{let n=e.ownerDocument.createElement("div");return gg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){gg(n,o)},destroy(){n.remove()}}},hy=(e,t)=>{var I,D,F,H;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),u=n.createElement("div"),p=(D=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||D?(H=(F=t==null?void 0:t.launcher)==null?void 0:F.autoExpand)!=null?H:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),Lo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{hg(a,i,d,l,u,t,p)}),f.observe(a))},C=()=>{hg(a,i,d,l,u,t,p),x()},L=a.ownerDocument.defaultView,B=()=>{C()};return L==null||L.addEventListener("resize",B),Lo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),C(),{mode:"docked",host:u,shell:a,syncWidgetState(v){let w=v.launcherEnabled?v.open:!0;p!==w&&(p=w,C())},updateConfig(v){var w,M;t=v,((M=(w=t==null?void 0:t.launcher)==null?void 0:w.enabled)!=null?M:!0)===!1&&(p=!0),C()},destroy(){L==null||L.removeEventListener("resize",B),g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},bg=(e,t)=>mn(t)?hy(e,t):fy(e,t);var Br={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Xi=.15,Qi=1.5,ya="persona-preview-shell-theme",gc={load:()=>null,save:()=>{},clear:()=>{}},fc=["How do I get started?","Pricing & plans","Talk to support"];function va(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function hc(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Ji(e){let t=hc(e);return`* { box-sizing: border-box; }
108
108
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
109
109
  html { color-scheme: ${e}; }
110
110
  body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
@@ -187,13 +187,13 @@ _Details: ${n.message}_`:o}var wi=class e{constructor(t={},n){this.config=t;this
187
187
  <body>
188
188
  ${n?s:r}
189
189
  </body>
190
- </html>`}var fy={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)"};function bf(e){return fy[e]}function tl(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
190
+ </html>`}var by={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)"};function yg(e){return by[e]}function tl(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
191
191
  `),createdAt:n};case"assistant-markdown-table":return{id:`preview-seq-assistant-table-${o}`,role:"assistant",content:["Here are the built-in streaming animations at a glance:","","| Preset | Wrap unit | Best for |","| ------------ | --------- | --------------------------- |","| Typewriter | Character | Classic terminal feel |","| Letter rise | Character | Soft, staggered entrance |","| Word fade | Word | Longer-form assistant replies |","| Pop bubble | Bubble | Short, punchy affirmations |"].join(`
192
192
  `),createdAt:n};case"assistant-image":return{id:`preview-seq-assistant-image-${o}`,role:"assistant",content:["Here's the reference diagram you asked for \u2014 let me know if you'd like a different view:","","![Stream animation reference](https://placehold.co/320x200/png?text=Stream+Animation)","","The gradient shows how per-unit delays stagger across the reply."].join(`
193
- `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function yf(e,t){return[...e,tl(t,e.length)]}function vc(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function vf(e,t,n){var d,l;let o=tl(e,t);if(!vc(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let u=r;u<a.length;u+=r)i.push({message:{...o,content:a.slice(0,u),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var gy=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],hy=e=>{var t,n,o,r,s,a,i,d;return!!((n=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&n.activePreview||(r=(o=e==null?void 0:e.features)==null?void 0:o.toolCallDisplay)!=null&&r.grouped||(a=(s=e==null?void 0:e.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function xc(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&hy(t)?[...gy(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function nl(e,t,n=[]){var s,a;let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?(s=e.suggestionChips)!=null&&s.length?e.suggestionChips:gc:e.suggestionChips,initialMessages:xc(t,e,n),storageAdapter:fc};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function cr(e,t){var s,a,i,d;let n=e.theme?on(e.theme,{validate:!1}):on(),o=(s=e.scene)!=null?s:"conversation",r={...Et,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return nl(r,o,(d=e.appendedMessages)!=null?d:[])}function xf(e,t,n){var a,i,d;let o=e.theme?on(e.theme,{validate:!1}):on(),r=(a=e.scene)!=null?a:"conversation",s={...Et,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return nl(s,r,t)}function wf(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:cr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:cr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:cr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:cr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:cr(e,n),shellMode:n}]}function Cf(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function u(){var B;return(B=n.device)!=null?B:"desktop"}function p(){var B;return(B=n.zoom)!=null?B:i}function g(){var E,F;let B=getComputedStyle(e),D=parseFloat(B.paddingLeft)+parseFloat(B.paddingRight),V=parseFloat(B.paddingTop)+parseFloat(B.paddingBottom),H=40,v=((E=n.compareMode)!=null?E:"off")!=="off",C=(e.clientWidth-D-H)/(v?2:1),M=e.clientHeight-V-H;if(C<=0||M<=0)return 1;let A=(F=Br[u()])!=null?F:Br.desktop;return Math.min(C/A.w,M/A.h,1)}function m(){var V,H,v;i=g();let B=Math.max(Xi,Math.min(Qi,p()));d=B;let D=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let C of D){let M=(V=C.dataset.device)!=null?V:"desktop",A=(H=Br[M])!=null?H:Br.desktop;C.style.width=`${A.w*B}px`,C.style.height=`${A.h*B}px`,M==="mobile"&&(C.style.borderRadius=`${32*B}px`);let E=C.querySelector("iframe");E&&(E.style.width=`${A.w}px`,E.style.height=`${A.h}px`,E.style.transformOrigin="top left",E.style.transition="none",E.style.transform=`scale(${B})`)}(v=n.onScaleChange)==null||v.call(n,B)}function w(){var B;(B=n.onBeforeDestroy)==null||B.call(n);for(let D of o)D.destroy();for(let D of r)D();o=[],r=[]}function x(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function L(){var ye,le,Ce,Be;if(a)return;w();let B=++l,D=wf(n),V=u(),H=((ye=n.compareMode)!=null?ye:"off")!=="off",v=((le=n.scene)!=null?le:"conversation")==="minimized",C=(Ce=n.widgetCssPath)!=null?Ce:"/widget-dist/widget.css",M=(Be=n.buildSrcdoc)!=null?Be:el,A=V==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",E=ve=>`<div class="${A}" data-mount-id="${ve.mountId}" data-device="${V}" data-shell-mode="${ve.shellMode}">
193
+ `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function vg(e,t){return[...e,tl(t,e.length)]}function vc(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function xg(e,t,n){var d,l;let o=tl(e,t);if(!vc(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let u=r;u<a.length;u+=r)i.push({message:{...o,content:a.slice(0,u),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var yy=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],vy=e=>{var t,n,o,r,s,a,i,d;return!!((n=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&n.activePreview||(r=(o=e==null?void 0:e.features)==null?void 0:o.toolCallDisplay)!=null&&r.grouped||(a=(s=e==null?void 0:e.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function xc(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&vy(t)?[...yy(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function nl(e,t,n=[]){var s,a;let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?(s=e.suggestionChips)!=null&&s.length?e.suggestionChips:fc:e.suggestionChips,initialMessages:xc(t,e,n),storageAdapter:gc};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function cr(e,t){var s,a,i,d;let n=e.theme?on(e.theme,{validate:!1}):on(),o=(s=e.scene)!=null?s:"conversation",r={...Et,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return nl(r,o,(d=e.appendedMessages)!=null?d:[])}function wg(e,t,n){var a,i,d;let o=e.theme?on(e.theme,{validate:!1}):on(),r=(a=e.scene)!=null?a:"conversation",s={...Et,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return nl(s,r,t)}function Cg(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:cr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:cr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:cr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:cr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:cr(e,n),shellMode:n}]}function Sg(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function u(){var I;return(I=n.device)!=null?I:"desktop"}function p(){var I;return(I=n.zoom)!=null?I:i}function f(){var E,O;let I=getComputedStyle(e),D=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),F=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),H=40,v=((E=n.compareMode)!=null?E:"off")!=="off",w=(e.clientWidth-D-H)/(v?2:1),M=e.clientHeight-F-H;if(w<=0||M<=0)return 1;let A=(O=Br[u()])!=null?O:Br.desktop;return Math.min(w/A.w,M/A.h,1)}function g(){var F,H,v;i=f();let I=Math.max(Xi,Math.min(Qi,p()));d=I;let D=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let w of D){let M=(F=w.dataset.device)!=null?F:"desktop",A=(H=Br[M])!=null?H:Br.desktop;w.style.width=`${A.w*I}px`,w.style.height=`${A.h*I}px`,M==="mobile"&&(w.style.borderRadius=`${32*I}px`);let E=w.querySelector("iframe");E&&(E.style.width=`${A.w}px`,E.style.height=`${A.h}px`,E.style.transformOrigin="top left",E.style.transition="none",E.style.transform=`scale(${I})`)}(v=n.onScaleChange)==null||v.call(n,I)}function x(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let D of o)D.destroy();for(let D of r)D();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function L(){var ye,le,Ce,Be;if(a)return;x();let I=++l,D=Cg(n),F=u(),H=((ye=n.compareMode)!=null?ye:"off")!=="off",v=((le=n.scene)!=null?le:"conversation")==="minimized",w=(Ce=n.widgetCssPath)!=null?Ce:"/widget-dist/widget.css",M=(Be=n.buildSrcdoc)!=null?Be:el,A=F==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",E=ve=>`<div class="${A}" data-mount-id="${ve.mountId}" data-device="${F}" data-shell-mode="${ve.shellMode}">
194
194
  ${H?`<div class="preview-frame-meta"><span class="preview-frame-label">${va(ve.label)}</span></div>`:""}
195
195
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ve.mountId}"></iframe>
196
- </div>`,F=H?`<div class="preview-compare-grid">${D.map(ve=>`<div class="preview-compare-cell">${E(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${E(D[0])}</div>`;n.morphContainer?n.morphContainer(e,F):e.innerHTML=F,m();let U=x(),j=0,fe=U.length,se=()=>{var ee,Me,Q,Te,he;if(a||B!==l)return;for(let ce of U){let me=ce.dataset.mountId;if(!me||!ce.contentDocument)continue;let Ke=D.find(ge=>ge.mountId===me);if(!Ke)continue;let K=()=>{},re=mn(Ke.config),Pe=re?(()=>{var X;let ge=(X=ce.contentDocument)==null?void 0:X.getElementById(`preview-content-${me}`);if(!ge)return null;let de=hf(ge,Ke.config),Ve=ce.contentDocument.createElement("div");Ve.id=me,Ve.style.height="100%",Ve.style.display="flex",Ve.style.flexDirection="column",Ve.style.flex="1",Ve.style.minHeight="0",de.host.appendChild(Ve);let Ie=()=>de.syncWidgetState(nt.getState()),pe=K;return K=()=>{de.destroy(),pe()},Ve.__syncDock=Ie,Ve.__hostLayout=de,Ve})():ce.contentDocument.getElementById(me);if(!Pe)continue;let nt=uf(Pe,Ke.config);if(o.push(nt),re&&Pe.__syncDock){let ge=Pe.__syncDock,de=nt.on("widget:opened",ge),Ve=nt.on("widget:closed",ge),Ie=K;K=()=>{de(),Ve(),Ie()},ge()}r.push(K),v&&nt.close()}if(((ee=n.scene)!=null?ee:"conversation")==="artifact"||(Te=(Q=(Me=n.config)==null?void 0:Me.features)==null?void 0:Q.artifacts)!=null&&Te.enabled)for(let ce of o)ce.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
196
+ </div>`,O=H?`<div class="preview-compare-grid">${D.map(ve=>`<div class="preview-compare-cell">${E(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${E(D[0])}</div>`;n.morphContainer?n.morphContainer(e,O):e.innerHTML=O,g();let U=C(),j=0,ge=U.length,se=()=>{var ee,Me,Q,Te,he;if(a||I!==l)return;for(let ce of U){let me=ce.dataset.mountId;if(!me||!ce.contentDocument)continue;let Ke=D.find(fe=>fe.mountId===me);if(!Ke)continue;let K=()=>{},re=mn(Ke.config),Pe=re?(()=>{var X;let fe=(X=ce.contentDocument)==null?void 0:X.getElementById(`preview-content-${me}`);if(!fe)return null;let de=bg(fe,Ke.config),Ve=ce.contentDocument.createElement("div");Ve.id=me,Ve.style.height="100%",Ve.style.display="flex",Ve.style.flexDirection="column",Ve.style.flex="1",Ve.style.minHeight="0",de.host.appendChild(Ve);let Ie=()=>de.syncWidgetState(nt.getState()),pe=K;return K=()=>{de.destroy(),pe()},Ve.__syncDock=Ie,Ve.__hostLayout=de,Ve})():ce.contentDocument.getElementById(me);if(!Pe)continue;let nt=mg(Pe,Ke.config);if(o.push(nt),re&&Pe.__syncDock){let fe=Pe.__syncDock,de=nt.on("widget:opened",fe),Ve=nt.on("widget:closed",fe),Ie=K;K=()=>{de(),Ve(),Ie()},fe()}r.push(K),v&&nt.close()}if(((ee=n.scene)!=null?ee:"conversation")==="artifact"||(Te=(Q=(Me=n.config)==null?void 0:Me.features)==null?void 0:Q.artifacts)!=null&&Te.enabled)for(let ce of o)ce.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
197
197
 
198
198
  This is a preview of the artifact sidebar.
199
199
 
@@ -201,4 +201,4 @@ This is a preview of the artifact sidebar.
201
201
 
202
202
  - Markdown rendering
203
203
  - Document toolbar
204
- - Resizable panes`});(he=n.onAfterMount)==null||he.call(n,{iframes:U,controllers:[...o]})};for(let ve of U){let ee=ve.dataset.mountId;if(!ee)continue;let Me=D.find(Q=>Q.mountId===ee);Me&&(ve.addEventListener("load",()=>{j++,j>=fe&&se()},{once:!0}),ve.srcdoc=M(ee,Me.shellMode,mn(Me.config),C))}fe===0&&se()}function W(){var V;if(a)return;let B=wf(n);if(o.length!==B.length){L();return}if(B.some(H=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${H.mountId}"]`);return!v||v.dataset.shellMode!==H.shellMode})){L();return}o.forEach((H,v)=>{var C;H.update(B[v].config),((C=n.scene)!=null?C:"conversation")==="minimized"&&H.close()});for(let H of B){let v=e.querySelector(`iframe[data-mount-id="${H.mountId}"]`);v&&Zi(v,H.shellMode)}(V=n.onAfterUpdate)==null||V.call(n,{iframes:x(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),L(),{update(B){if(a)return;let D=B.device!==void 0&&B.device!==n.device||B.scene!==void 0&&B.scene!==n.scene||B.compareMode!==void 0&&B.compareMode!==n.compareMode||B.widgetCssPath!==void 0&&B.widgetCssPath!==n.widgetCssPath;n={...n,...B},D?L():W()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(B){a||(n={...n,zoom:B},m())}}}function Io(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Ca={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},by=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function yy(e){return by.test(e)}function Hr(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Ca[t];if(n)return n;let o=Xr(t);if(ei(o)||o==="transparent"||yy(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Ca).slice(0,6).join(", ")}).`)}var rl=Hs.map(e=>e==="gray"?"neutral":e),vy={...Object.fromEntries(rl.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Sa(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=vy[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Aa(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function Ta(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var xy={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function ka(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=xy[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Ea(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=Ja(t);return Za(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function sl(e){for(let t of kr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var Sf=sl("typo-font-family"),xa=sl("typo-font-size"),wa=sl("typo-font-weight"),ol=sl("typo-line-height"),Af={...Sf,monospace:Sf.mono},Tf={...xa,small:xa.sm,md:xa.base,medium:xa.base,large:xa.lg},kf={...wa,400:wa.normal,500:wa.medium,600:wa.semibold,700:wa.bold},Ef={...ol,"1.25":ol.tight,"1.5":ol.normal,"1.625":ol.relaxed};function Mf(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var Lf="theme.palette.radius.";function wy(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of kr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(Lf)&&typeof i=="string"&&(s[a.slice(Lf.length)]=i);e[r[1]]=s}return e}var ds=wy(),If=["sm","md","lg","xl","full"];function il(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?il(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?il(e,r,n,o+1):null}function al(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function ps(e){return e.replace(/^role-/,"")}function Cy(e){for(let[t,n]of Object.entries(ds))if(If.every(o=>e[o]===n[o]))return t;return"custom"}function dr(e){var o,r;let t={};for(let s of If)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of or)n[ps(s.roleId)]=ri(a=>e.get(`theme.${a}`),s);return{brand:{primary:wc(e.get("theme.palette.colors.primary.500")),secondary:wc(e.get("theme.palette.colors.secondary.500")),accent:wc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:al(e,"theme.semantic.typography.fontFamily"),fontSize:al(e,"theme.semantic.typography.fontSize"),fontWeight:al(e,"theme.semantic.typography.fontWeight"),lineHeight:al(e,"theme.semantic.typography.lineHeight")},roundness:{style:Cy(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function wc(e){return typeof e=="string"&&e!==""?e:null}var cs=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function Rf(e){let t=new Set(e.targets.map(n=>n.path));return cs.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Sy={AA:4.5,AAA:7};function Ay(e){return Math.round(e*100)/100}function Ty(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Tr.indexOf(a[2]),l=null,u=1/0;return Tr.forEach((p,g)=>{let m=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&Bs(m,n)>=o){let w=d>=0?Math.abs(g-d):g;w<u&&(u=w,l=`palette.colors.${i}.${p}`)}}),l}function us(e,t="AA",n="both",o){let r=Sy[t],s=n==="both"?["light","dark"]:[n],a=o?cs.filter(d=>o.includes(d.key)):cs,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let p=il(e,u.fg,l),g=il(e,u.bg,l);if(!p||!g)continue;let m=Ay(Bs(p,g)),w=m>=r,x={pair:u.key,label:u.label,variant:d,fg:p,bg:g,ratio:m,threshold:r,passes:w};if(!w){let L=Ty(e,u.fg,g,r,l);L&&(x.suggestion=L)}i.push(x)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Dr(e,t,n="light",o="AA"){return t.length===0?[]:us(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var ln={};for(let e of or){let t=ps(e.roleId);ln[t]=e,ln[e.roleId]=e}Object.assign(ln,{surface:ln.surfaces,background:ln.surfaces,backgrounds:ln.surfaces,user:ln["user-messages"],"user-message":ln["user-messages"],assistant:ln["assistant-messages"],"assistant-message":ln["assistant-messages"],actions:ln["primary-actions"],buttons:ln["primary-actions"],composer:ln.input,links:ln["links-focus"],focus:ln["links-focus"],border:ln.borders,dividers:ln.borders,scroll:ln["scroll-to-bottom"]});function ky(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=ln[t];if(!n){let o=or.map(r=>ps(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Pf(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of si)t(n.sections);for(let n of Ks)t(n.sections);return e}var Ey={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},My={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Cc=["bottom-right","bottom-left","top-right","top-left"],Sc=["bubble","flat","minimal"],Ly={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Ac(e,t){var H;let n=(H=t==null?void 0:t.editTarget)!=null?H:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,C,M=n)=>{let A={};return(M==="light"||M==="both")&&(A[`theme.${v}`]=C),(M==="dark"||M==="both")&&(A[`darkTheme.${v}`]=C),A},a=v=>{if(n==="both")return v;let C={};for(let[M,A]of Object.entries(v))(n==="light"&&M.startsWith("theme.")||n==="dark"&&M.startsWith("darkTheme."))&&(C[M]=A);return C},i=()=>n==="dark"?"dark":"light",d=(v,C=[])=>Io({ok:!0,summary:dr(e),warnings:C,applied:v});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(v){let{verbosity:C}=r(v),M={summary:dr(e),availableRoles:or.map(A=>({role:ps(A.roleId),helper:A.helper})),availableFamilies:rl,presets:Qr.map(A=>{var E;return{id:A.id,name:A.name,description:A.description,tags:(E=A.tags)!=null?E:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return C==="full"&&(o!=null||(o=Pf()),M.fieldIndex=Array.from(o.values()).map(A=>{var E;return{id:A.id,path:A.path,type:A.type,label:A.label,options:(E=A.options)==null?void 0:E.map(F=>F.value)}})),Io(M)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let C=r(v),M=["primary","secondary","accent"],A={},E={};for(let U of M){if(C[U]===void 0)continue;let j=Hr(C[U]);E[U]=j;let fe=ni(j);for(let se of Tr){let ye=fe[se];ye!==void 0&&Object.assign(A,s(`palette.colors.${U}.${se}`,ye))}}if(Object.keys(E).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(A);let F=Dr(e,["primary-button","user-message"],i());return d(E,F)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:rl},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let C=r(v),M=ky(C.role),A=Sa(C.family,!0),E=Aa(C.intensity),F=a(qs(A,E,M)),U=Object.keys(F).length;e.setBatch(F);let j=Dr(e,Rf(M),i());return d({role:ps(M.roleId),family:A,intensity:E,tokensWritten:U},j)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(v){let C=r(v),M={},A={},E=(F,U)=>{var fe;if(C[F]===void 0)return;let j=Mf(C[F],U,F);A[F]=(fe=j.split(".").pop())!=null?fe:j,Object.assign(M,s(`semantic.typography.${F}`,j))};if(E("fontFamily",Af),E("fontSize",Tf),E("fontWeight",kf),E("lineHeight",Ef),Object.keys(A).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(M),d(A)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let C=r(v),M={},A={};if(C.style!==void 0){let E=ka(C.style);A.style=E;for(let[F,U]of Object.entries(ds[E]))Object.assign(M,s(`palette.radius.${F}`,U))}if(C.radius!==void 0){let E=r(C.radius),F={};for(let U of["sm","md","lg","xl","full"]){if(E[U]===void 0)continue;let j=Ea(E[U]);F[U]=j,Object.assign(M,s(`palette.radius.${U}`,j))}A.radius=F}if(Object.keys(M).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(M),d(A)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let C=r(v),M={};if(C.scheme!==void 0){let A=Ta(C.scheme);e.set("colorScheme",A),M.scheme=A}if(C.editTarget!==void 0){let A=String(C.editTarget).trim().toLowerCase();if(A!=="light"&&A!=="dark"&&A!=="both")throw new Error(`Unknown editTarget "${C.editTarget}". Valid: light, dark, both.`);n=A,M.editTarget=A}if(Object.keys(M).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Io({ok:!0,summary:dr(e),warnings:[],applied:M,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:C}=r(v),M=ai(String(C!=null?C:""));if(!M){let U=Qr.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${C}". Valid presets: ${U}.`)}let A=on(M.theme,{validate:!1}),E={...e.getConfig()};M.darkTheme&&(E.darkTheme=on(M.darkTheme,{validate:!1})),M.toolCall&&(E.toolCall=M.toolCall),e.setFullConfig(E,A);let F=Dr(e,["body","assistant-message"],"light");return d({appliedPreset:{id:M.id,name:M.name}},F)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Cc},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:Sc}},additionalProperties:!1}},additionalProperties:!1},execute(v){var U,j,fe;let C=r(v),M={},A={};if(C.launcherPosition!==void 0){let se=String(C.launcherPosition);if(!Cc.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Cc.join(", ")}.`);M["launcher.position"]=se,A.launcherPosition=se}let E=r(C.features);for(let[se,ye]of Object.entries(Ey))E[se]!==void 0&&(M[ye]=!!E[se],(U=A.features)!=null||(A.features={}),A.features[se]=!!E[se]);let F=r(C.layout);for(let[se,ye]of Object.entries(My))if(F[se]!==void 0)if(se==="messageStyle"){let le=String(F[se]);if(!Sc.includes(le))throw new Error(`Unknown messageStyle "${le}". Valid: ${Sc.join(", ")}.`);M[ye]=le,(j=A.layout)!=null||(A.layout={}),A.layout[se]=le}else M[ye]=!!F[se],(fe=A.layout)!=null||(A.layout={}),A.layout[se]=!!F[se];if(Object.keys(M).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(M),d(A)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let C=r(v),M={},A={};for(let[E,F]of Object.entries(Ly))C[E]!==void 0&&(M[F]=String(C[E]),A[E]=String(C[E]));if(C.suggestions!==void 0){if(!Array.isArray(C.suggestions))throw new Error("`suggestions` must be an array of strings.");let E=C.suggestions.filter(F=>typeof F=="string");M.suggestionChips=E,A.suggestions=E}if(Object.keys(M).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(M),d(A)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var F;let{updates:C}=r(v);if(!Array.isArray(C)||C.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=Pf());let M={},A=[];for(let U of C){let j=r(U),fe=String((F=j.field)!=null?F:"");try{let se=o.get(fe),ye=se?se.path:fe;if(!se&&!/^(theme|darkTheme)\.|\./.test(ye))throw new Error(`Unknown field "${fe}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let le=Iy(se,j.value);if(se&&ye.startsWith("theme.")){let Ce=s(ye.slice(6),le);Object.assign(M,Ce),A.push({field:fe,resolvedPath:Object.keys(Ce),ok:!0})}else M[ye]=le,A.push({field:fe,resolvedPath:ye,ok:!0})}catch(se){A.push({field:fe,ok:!1,error:se.message})}}let E=A.filter(U=>U.ok);return Object.keys(M).length>0&&e.setBatch(M),Io({ok:E.length>0,summary:dr(e),warnings:[],applied:{updates:A}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let C=r(v),M=C.level==="AAA"?"AAA":"AA",A=C.variant==="light"||C.variant==="dark"?C.variant:"both",E=us(e,M,A);return Io({level:E.level,passing:E.checks.length-E.failures.length,total:E.checks.length,checks:E.checks,failures:E.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:C}=r(v);switch(C){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Io({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${C}". Valid: undo, redo, reset, export.`)}}}]}function Iy(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(Hr(t)):Hr(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}0&&(module.exports={ADVANCED_TOKENS_SECTION,ALL_ROLES,ALL_TABS,BRAND_PALETTE_SECTION,BUILT_IN_PRESETS,COLORS_SECTIONS,COLOR_FAMILIES,COMPONENTS_SECTIONS,COMPONENT_COLOR_SECTIONS,COMPONENT_SHAPE_SECTIONS,CONFIGURE_SECTIONS,CONFIGURE_SUB_GROUPS,CONTRAST_PAIRS,CSS_NAMED_COLORS,DEVICE_DIMENSIONS,HOME_SUGGESTION_CHIPS,INTERFACE_ROLES_SECTION,MOCK_BROWSER_CONTENT,MOCK_WORKSPACE_CONTENT,PALETTE_SECTION,PREVIEW_STORAGE_ADAPTER,RADIUS_PRESETS,ROLE_ASSISTANT_MESSAGES,ROLE_BORDERS,ROLE_FAMILIES,ROLE_FAMILY_LABELS,ROLE_HEADER,ROLE_INPUT,ROLE_INTENSITIES,ROLE_LINKS_FOCUS,ROLE_PRIMARY_ACTIONS,ROLE_SCROLL_TO_BOTTOM,ROLE_SURFACES,ROLE_USER_MESSAGES,SEMANTIC_COLORS_SECTION,SHADE_KEYS,SHELL_STYLE_ID,STATUS_COLORS_SECTION,STATUS_PALETTE_SECTION,STYLE_SECTIONS,STYLE_SECTIONS_V2,THEME_EDITOR_PRESETS,THEME_SECTION,ThemeEditorState,ZOOM_MAX,ZOOM_MIN,appendPreviewTranscriptEntry,applySceneConfig,applyShellTheme,buildPreviewConfig,buildPreviewConfigWithMessages,buildShellCss,buildSrcdoc,buildSummary,buildTranscriptStreamFrames,coerceColor,coerceFamily,coerceIntensity,coerceRadius,coerceRoundnessStyle,coerceScheme,convertFromPx,convertToPx,createPreviewMessages,createPreviewTranscriptEntry,createThemeEditorTools,createThemePreview,detectRoleAssignment,escapeHtml,findSection,formatCssValue,generateColorScale,getPreviewTranscriptPresetLabel,getShellPalette,getThemeEditorPreset,hexToHsl,hslToHex,isValidHex,normalizeColorValue,paletteColorPath,parseCssValue,presetStreamsText,quickContrastWarnings,resolveRoleAssignment,resolveThemeColorPath,rgbToHex,runContrastChecks,scopeSection,tokenRefDisplayName,toolResult,wcagContrastRatio});
204
+ - Resizable panes`});(he=n.onAfterMount)==null||he.call(n,{iframes:U,controllers:[...o]})};for(let ve of U){let ee=ve.dataset.mountId;if(!ee)continue;let Me=D.find(Q=>Q.mountId===ee);Me&&(ve.addEventListener("load",()=>{j++,j>=ge&&se()},{once:!0}),ve.srcdoc=M(ee,Me.shellMode,mn(Me.config),w))}ge===0&&se()}function B(){var F;if(a)return;let I=Cg(n);if(o.length!==I.length){L();return}if(I.some(H=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${H.mountId}"]`);return!v||v.dataset.shellMode!==H.shellMode})){L();return}o.forEach((H,v)=>{var w;H.update(I[v].config),((w=n.scene)!=null?w:"conversation")==="minimized"&&H.close()});for(let H of I){let v=e.querySelector(`iframe[data-mount-id="${H.mountId}"]`);v&&Zi(v,H.shellMode)}(F=n.onAfterUpdate)==null||F.call(n,{iframes:C(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||g()}),s.observe(e)),L(),{update(I){if(a)return;let D=I.device!==void 0&&I.device!==n.device||I.scene!==void 0&&I.scene!==n.scene||I.compareMode!==void 0&&I.compareMode!==n.compareMode||I.widgetCssPath!==void 0&&I.widgetCssPath!==n.widgetCssPath;n={...n,...I},D?L():B()},destroy(){a||(a=!0,x(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return d},setZoom(I){a||(n={...n,zoom:I},g())}}}function Io(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Ca={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},xy=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function wy(e){return xy.test(e)}function Hr(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Ca[t];if(n)return n;let o=Xr(t);if(ei(o)||o==="transparent"||wy(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Ca).slice(0,6).join(", ")}).`)}var rl=Hs.map(e=>e==="gray"?"neutral":e),Cy={...Object.fromEntries(rl.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Sa(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Cy[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Aa(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function Ta(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var Sy={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function ka(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Sy[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Ea(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=Ja(t);return Za(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function sl(e){for(let t of kr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var Ag=sl("typo-font-family"),xa=sl("typo-font-size"),wa=sl("typo-font-weight"),ol=sl("typo-line-height"),Tg={...Ag,monospace:Ag.mono},kg={...xa,small:xa.sm,md:xa.base,medium:xa.base,large:xa.lg},Eg={...wa,400:wa.normal,500:wa.medium,600:wa.semibold,700:wa.bold},Mg={...ol,"1.25":ol.tight,"1.5":ol.normal,"1.625":ol.relaxed};function Lg(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var Ig="theme.palette.radius.";function Ay(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of kr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(Ig)&&typeof i=="string"&&(s[a.slice(Ig.length)]=i);e[r[1]]=s}return e}var ds=Ay(),Rg=["sm","md","lg","xl","full"];function il(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?il(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?il(e,r,n,o+1):null}function al(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function ps(e){return e.replace(/^role-/,"")}function Ty(e){for(let[t,n]of Object.entries(ds))if(Rg.every(o=>e[o]===n[o]))return t;return"custom"}function dr(e){var o,r;let t={};for(let s of Rg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of or)n[ps(s.roleId)]=ri(a=>e.get(`theme.${a}`),s);return{brand:{primary:wc(e.get("theme.palette.colors.primary.500")),secondary:wc(e.get("theme.palette.colors.secondary.500")),accent:wc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:al(e,"theme.semantic.typography.fontFamily"),fontSize:al(e,"theme.semantic.typography.fontSize"),fontWeight:al(e,"theme.semantic.typography.fontWeight"),lineHeight:al(e,"theme.semantic.typography.lineHeight")},roundness:{style:Ty(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function wc(e){return typeof e=="string"&&e!==""?e:null}var cs=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function Pg(e){let t=new Set(e.targets.map(n=>n.path));return cs.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var ky={AA:4.5,AAA:7};function Ey(e){return Math.round(e*100)/100}function My(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Tr.indexOf(a[2]),l=null,u=1/0;return Tr.forEach((p,f)=>{let g=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof g!="string"||!(g.startsWith("#")||g.startsWith("rgb")))&&Bs(g,n)>=o){let x=d>=0?Math.abs(f-d):f;x<u&&(u=x,l=`palette.colors.${i}.${p}`)}}),l}function us(e,t="AA",n="both",o){let r=ky[t],s=n==="both"?["light","dark"]:[n],a=o?cs.filter(d=>o.includes(d.key)):cs,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let p=il(e,u.fg,l),f=il(e,u.bg,l);if(!p||!f)continue;let g=Ey(Bs(p,f)),x=g>=r,C={pair:u.key,label:u.label,variant:d,fg:p,bg:f,ratio:g,threshold:r,passes:x};if(!x){let L=My(e,u.fg,f,r,l);L&&(C.suggestion=L)}i.push(C)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Dr(e,t,n="light",o="AA"){return t.length===0?[]:us(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var ln={};for(let e of or){let t=ps(e.roleId);ln[t]=e,ln[e.roleId]=e}Object.assign(ln,{surface:ln.surfaces,background:ln.surfaces,backgrounds:ln.surfaces,user:ln["user-messages"],"user-message":ln["user-messages"],assistant:ln["assistant-messages"],"assistant-message":ln["assistant-messages"],actions:ln["primary-actions"],buttons:ln["primary-actions"],composer:ln.input,links:ln["links-focus"],focus:ln["links-focus"],border:ln.borders,dividers:ln.borders,scroll:ln["scroll-to-bottom"]});function Ly(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=ln[t];if(!n){let o=or.map(r=>ps(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Wg(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of si)t(n.sections);for(let n of Ks)t(n.sections);return e}var Iy={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Ry={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Cc=["bottom-right","bottom-left","top-right","top-left"],Sc=["bubble","flat","minimal"],Py={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Ac(e,t){var H;let n=(H=t==null?void 0:t.editTarget)!=null?H:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,w,M=n)=>{let A={};return(M==="light"||M==="both")&&(A[`theme.${v}`]=w),(M==="dark"||M==="both")&&(A[`darkTheme.${v}`]=w),A},a=v=>{if(n==="both")return v;let w={};for(let[M,A]of Object.entries(v))(n==="light"&&M.startsWith("theme.")||n==="dark"&&M.startsWith("darkTheme."))&&(w[M]=A);return w},i=()=>n==="dark"?"dark":"light",d=(v,w=[])=>Io({ok:!0,summary:dr(e),warnings:w,applied:v});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(v){let{verbosity:w}=r(v),M={summary:dr(e),availableRoles:or.map(A=>({role:ps(A.roleId),helper:A.helper})),availableFamilies:rl,presets:Qr.map(A=>{var E;return{id:A.id,name:A.name,description:A.description,tags:(E=A.tags)!=null?E:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return w==="full"&&(o!=null||(o=Wg()),M.fieldIndex=Array.from(o.values()).map(A=>{var E;return{id:A.id,path:A.path,type:A.type,label:A.label,options:(E=A.options)==null?void 0:E.map(O=>O.value)}})),Io(M)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let w=r(v),M=["primary","secondary","accent"],A={},E={};for(let U of M){if(w[U]===void 0)continue;let j=Hr(w[U]);E[U]=j;let ge=ni(j);for(let se of Tr){let ye=ge[se];ye!==void 0&&Object.assign(A,s(`palette.colors.${U}.${se}`,ye))}}if(Object.keys(E).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(A);let O=Dr(e,["primary-button","user-message"],i());return d(E,O)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:rl},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let w=r(v),M=Ly(w.role),A=Sa(w.family,!0),E=Aa(w.intensity),O=a(qs(A,E,M)),U=Object.keys(O).length;e.setBatch(O);let j=Dr(e,Pg(M),i());return d({role:ps(M.roleId),family:A,intensity:E,tokensWritten:U},j)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(v){let w=r(v),M={},A={},E=(O,U)=>{var ge;if(w[O]===void 0)return;let j=Lg(w[O],U,O);A[O]=(ge=j.split(".").pop())!=null?ge:j,Object.assign(M,s(`semantic.typography.${O}`,j))};if(E("fontFamily",Tg),E("fontSize",kg),E("fontWeight",Eg),E("lineHeight",Mg),Object.keys(A).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(M),d(A)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let w=r(v),M={},A={};if(w.style!==void 0){let E=ka(w.style);A.style=E;for(let[O,U]of Object.entries(ds[E]))Object.assign(M,s(`palette.radius.${O}`,U))}if(w.radius!==void 0){let E=r(w.radius),O={};for(let U of["sm","md","lg","xl","full"]){if(E[U]===void 0)continue;let j=Ea(E[U]);O[U]=j,Object.assign(M,s(`palette.radius.${U}`,j))}A.radius=O}if(Object.keys(M).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(M),d(A)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let w=r(v),M={};if(w.scheme!==void 0){let A=Ta(w.scheme);e.set("colorScheme",A),M.scheme=A}if(w.editTarget!==void 0){let A=String(w.editTarget).trim().toLowerCase();if(A!=="light"&&A!=="dark"&&A!=="both")throw new Error(`Unknown editTarget "${w.editTarget}". Valid: light, dark, both.`);n=A,M.editTarget=A}if(Object.keys(M).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Io({ok:!0,summary:dr(e),warnings:[],applied:M,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:w}=r(v),M=ai(String(w!=null?w:""));if(!M){let U=Qr.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${w}". Valid presets: ${U}.`)}let A=on(M.theme,{validate:!1}),E={...e.getConfig()};M.darkTheme&&(E.darkTheme=on(M.darkTheme,{validate:!1})),M.toolCall&&(E.toolCall=M.toolCall),e.setFullConfig(E,A);let O=Dr(e,["body","assistant-message"],"light");return d({appliedPreset:{id:M.id,name:M.name}},O)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Cc},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:Sc}},additionalProperties:!1}},additionalProperties:!1},execute(v){var U,j,ge;let w=r(v),M={},A={};if(w.launcherPosition!==void 0){let se=String(w.launcherPosition);if(!Cc.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Cc.join(", ")}.`);M["launcher.position"]=se,A.launcherPosition=se}let E=r(w.features);for(let[se,ye]of Object.entries(Iy))E[se]!==void 0&&(M[ye]=!!E[se],(U=A.features)!=null||(A.features={}),A.features[se]=!!E[se]);let O=r(w.layout);for(let[se,ye]of Object.entries(Ry))if(O[se]!==void 0)if(se==="messageStyle"){let le=String(O[se]);if(!Sc.includes(le))throw new Error(`Unknown messageStyle "${le}". Valid: ${Sc.join(", ")}.`);M[ye]=le,(j=A.layout)!=null||(A.layout={}),A.layout[se]=le}else M[ye]=!!O[se],(ge=A.layout)!=null||(A.layout={}),A.layout[se]=!!O[se];if(Object.keys(M).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(M),d(A)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let w=r(v),M={},A={};for(let[E,O]of Object.entries(Py))w[E]!==void 0&&(M[O]=String(w[E]),A[E]=String(w[E]));if(w.suggestions!==void 0){if(!Array.isArray(w.suggestions))throw new Error("`suggestions` must be an array of strings.");let E=w.suggestions.filter(O=>typeof O=="string");M.suggestionChips=E,A.suggestions=E}if(Object.keys(M).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(M),d(A)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var O;let{updates:w}=r(v);if(!Array.isArray(w)||w.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=Wg());let M={},A=[];for(let U of w){let j=r(U),ge=String((O=j.field)!=null?O:"");try{let se=o.get(ge),ye=se?se.path:ge;if(!se&&!/^(theme|darkTheme)\.|\./.test(ye))throw new Error(`Unknown field "${ge}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let le=Wy(se,j.value);if(se&&ye.startsWith("theme.")){let Ce=s(ye.slice(6),le);Object.assign(M,Ce),A.push({field:ge,resolvedPath:Object.keys(Ce),ok:!0})}else M[ye]=le,A.push({field:ge,resolvedPath:ye,ok:!0})}catch(se){A.push({field:ge,ok:!1,error:se.message})}}let E=A.filter(U=>U.ok);return Object.keys(M).length>0&&e.setBatch(M),Io({ok:E.length>0,summary:dr(e),warnings:[],applied:{updates:A}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let w=r(v),M=w.level==="AAA"?"AAA":"AA",A=w.variant==="light"||w.variant==="dark"?w.variant:"both",E=us(e,M,A);return Io({level:E.level,passing:E.checks.length-E.failures.length,total:E.checks.length,checks:E.checks,failures:E.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:w}=r(v);switch(w){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Io({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${w}". Valid: undo, redo, reset, export.`)}}}]}function Wy(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(Hr(t)):Hr(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}0&&(module.exports={ADVANCED_TOKENS_SECTION,ALL_ROLES,ALL_TABS,BRAND_PALETTE_SECTION,BUILT_IN_PRESETS,COLORS_SECTIONS,COLOR_FAMILIES,COMPONENTS_SECTIONS,COMPONENT_COLOR_SECTIONS,COMPONENT_SHAPE_SECTIONS,CONFIGURE_SECTIONS,CONFIGURE_SUB_GROUPS,CONTRAST_PAIRS,CSS_NAMED_COLORS,DEVICE_DIMENSIONS,HOME_SUGGESTION_CHIPS,INTERFACE_ROLES_SECTION,MOCK_BROWSER_CONTENT,MOCK_WORKSPACE_CONTENT,PALETTE_SECTION,PREVIEW_STORAGE_ADAPTER,RADIUS_PRESETS,ROLE_ASSISTANT_MESSAGES,ROLE_BORDERS,ROLE_FAMILIES,ROLE_FAMILY_LABELS,ROLE_HEADER,ROLE_INPUT,ROLE_INTENSITIES,ROLE_LINKS_FOCUS,ROLE_PRIMARY_ACTIONS,ROLE_SCROLL_TO_BOTTOM,ROLE_SURFACES,ROLE_USER_MESSAGES,SEMANTIC_COLORS_SECTION,SHADE_KEYS,SHELL_STYLE_ID,STATUS_COLORS_SECTION,STATUS_PALETTE_SECTION,STYLE_SECTIONS,STYLE_SECTIONS_V2,THEME_EDITOR_PRESETS,THEME_SECTION,ThemeEditorState,ZOOM_MAX,ZOOM_MIN,appendPreviewTranscriptEntry,applySceneConfig,applyShellTheme,buildPreviewConfig,buildPreviewConfigWithMessages,buildShellCss,buildSrcdoc,buildSummary,buildTranscriptStreamFrames,coerceColor,coerceFamily,coerceIntensity,coerceRadius,coerceRoundnessStyle,coerceScheme,convertFromPx,convertToPx,createPreviewMessages,createPreviewTranscriptEntry,createThemeEditorTools,createThemePreview,detectRoleAssignment,escapeHtml,findSection,formatCssValue,generateColorScale,getPreviewTranscriptPresetLabel,getShellPalette,getThemeEditorPreset,hexToHsl,hslToHex,isValidHex,normalizeColorValue,paletteColorPath,parseCssValue,presetStreamsText,quickContrastWarnings,resolveRoleAssignment,resolveThemeColorPath,rgbToHex,runContrastChecks,scopeSection,tokenRefDisplayName,toolResult,wcagContrastRatio});