@runtypelabs/persona 3.25.0 → 3.27.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
- var Yp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ts(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];Yp(s)&&Yp(r)?n[o]=Ts(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Aa="440px",kt={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:io,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 Xp(e,t){if(!(!e&&!t))return e?t?Ts(e,t):e:t}function Qp(e){var t,n,o,r,s,a,i,d,l,u,p,f,g,x,C,M,W,L,H,D,B;return e?{...kt,...e,theme:Xp(kt.theme,e.theme),darkTheme:Xp(kt.darkTheme,e.darkTheme),launcher:{...kt.launcher,...e.launcher,dock:{...(t=kt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=kt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...kt.copy,...e.copy},sendButton:{...kt.sendButton,...e.sendButton},statusIndicator:{...kt.statusIndicator,...e.statusIndicator},voiceRecognition:{...kt.voiceRecognition,...e.voiceRecognition},features:(()=>{var we,We,ye,Z,Ee,X,Ae,fe;let v=(we=kt.features)==null?void 0:we.artifacts,w=(We=e.features)==null?void 0:We.artifacts,E=(ye=kt.features)==null?void 0:ye.scrollToBottom,S=(Z=e.features)==null?void 0:Z.scrollToBottom,k=(Ee=kt.features)==null?void 0:Ee.streamAnimation,F=(X=e.features)==null?void 0:X.streamAnimation,$=(Ae=kt.features)==null?void 0:Ae.askUserQuestion,q=(fe=e.features)==null?void 0:fe.askUserQuestion,me=v===void 0&&w===void 0?void 0:{...v,...w,layout:{...v==null?void 0:v.layout,...w==null?void 0:w.layout}},re=E===void 0&&S===void 0?void 0:{...E,...S},be=k===void 0&&F===void 0?void 0:{...k,...F},ie=$===void 0&&q===void 0?void 0:{...$,...q,styles:{...$==null?void 0:$.styles,...q==null?void 0:q.styles}};return{...kt.features,...e.features,...re!==void 0?{scrollToBottom:re}:{},...me!==void 0?{artifacts:me}:{},...be!==void 0?{streamAnimation:be}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:kt.suggestionChips,suggestionChipsConfig:{...kt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...kt.layout,...e.layout,header:{...(a=kt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=kt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=kt.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=kt.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(W=(M=e.layout)==null?void 0:M.messages)==null?void 0:W.timestamp}},slots:{...(L=kt.layout)==null?void 0:L.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...kt.markdown,...e.markdown,options:{...(D=kt.markdown)==null?void 0:D.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...kt.messageActions,...e.messageActions}}:kt}var lg={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"}},cg={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"}},dg={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:io,maxWidth:Aa,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 Vr(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."))?Vr(e,o):o}function Jp(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=Vr(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 pg(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 Zp(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]=Zp(s,r):n[o]=r}return n}function ug(e,t){return t?Zp(e,t):e}function nn(e,t={}){var r,s,a,i,d,l,u,p,f,g,x,C,M;let n={palette:lg,semantic:cg,components:dg},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,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:ug(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let W=pg(o);if(!W.valid)throw new Error(`Theme validation failed: ${W.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let W of t.plugins)o=W.transform(o);return o}function eu(e){var C,M,W,L,H,D,B,v,w,E,S,k,F,$,q,me,re,be,ie,we,We,ye,Z,Ee,X,Ae,fe,le,ue,je,j,oe,Re,tt,ge,ce,_e,Le,de,Y,Ve,Ct,Q,Fe,Ln,Ft,ln,Dn,Jn,N,se,He,Xe,Oe,Ne,ot,St,Nt,jt,K,gt,nt,$t,ae,ve,wt,_t,Jt,vn,Et,At,ht,yt,Ut,Ze,Fn,Zn,xn,On,ut,wo,Nn,ar,In,Ir,$o,Lo,vt,_n,Vn,wn,Rt,eo,to,$n,Uo,Io,zo,Un,Wt,Cn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn;let t=Jp(e),n={};for(let[T,Kn]of Object.entries(t)){let mo=T.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(C=n["--persona-semantic-colors-primary"])!=null?C:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M: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"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(H=n["--persona-semantic-colors-background"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(B=n["--persona-semantic-colors-text"])!=null?B: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"]=(E=n["--persona-semantic-colors-border"])!=null?E:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k: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"]=($=n["--persona-components-voice-processing-icon"])!=null?$:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(q=n["--persona-components-voice-speaking-icon"])!=null?q:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(me=n["--persona-components-approval-requested-background"])!=null?me:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(re=n["--persona-components-approval-requested-border"])!=null?re:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(be=n["--persona-components-approval-requested-text"])!=null?be:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ie=n["--persona-components-approval-approve-background"])!=null?ie:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(we=n["--persona-components-approval-deny-background"])!=null?we:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(We=n["--persona-components-attachment-image-background"])!=null?We:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ye=n["--persona-components-attachment-image-border"])!=null?ye:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Z=n["--persona-semantic-typography-fontFamily"])!=null?Z:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Ee=n["--persona-semantic-typography-fontSize"])!=null?Ee:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(X=n["--persona-semantic-typography-fontWeight"])!=null?X:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Ae=n["--persona-semantic-typography-lineHeight"])!=null?Ae: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"]=(fe=n["--persona-palette-radius-sm"])!=null?fe:"0.125rem",n["--persona-radius-md"]=(le=n["--persona-palette-radius-md"])!=null?le:"0.375rem",n["--persona-radius-lg"]=(ue=n["--persona-palette-radius-lg"])!=null?ue:"0.5rem",n["--persona-radius-xl"]=(je=n["--persona-palette-radius-xl"])!=null?je:"0.75rem",n["--persona-radius-full"]=(j=n["--persona-palette-radius-full"])!=null?j:"9999px",n["--persona-launcher-radius"]=(Re=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?Re:"9999px",n["--persona-launcher-bg"]=(tt=n["--persona-components-launcher-background"])!=null?tt:n["--persona-primary"],n["--persona-launcher-fg"]=(ge=n["--persona-components-launcher-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-launcher-border"]=(ce=n["--persona-components-launcher-border"])!=null?ce:n["--persona-border"],n["--persona-button-primary-bg"]=(_e=n["--persona-components-button-primary-background"])!=null?_e:n["--persona-primary"],n["--persona-button-primary-fg"]=(Le=n["--persona-components-button-primary-foreground"])!=null?Le:n["--persona-text-inverse"],n["--persona-button-radius"]=(Y=(de=n["--persona-components-button-primary-borderRadius"])!=null?de:n["--persona-palette-radius-full"])!=null?Y:"9999px",n["--persona-panel-radius"]=(Ct=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Ct:"0.75rem",n["--persona-panel-border"]=(Q=n["--persona-components-panel-border"])!=null?Q:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(Fe=n["--persona-components-panel-shadow"])!=null?Fe:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Ft=n["--persona-components-input-borderRadius"])!=null?Ft:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Jn=(Dn=n["--persona-components-message-user-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?Jn:"0.5rem",n["--persona-message-assistant-radius"]=(se=(N=n["--persona-components-message-assistant-borderRadius"])!=null?N:n["--persona-radius-lg"])!=null?se:"0.5rem",n["--persona-header-bg"]=(He=n["--persona-components-header-background"])!=null?He:n["--persona-surface"],n["--persona-header-border"]=(Xe=n["--persona-components-header-border"])!=null?Xe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Oe=n["--persona-components-header-iconBackground"])!=null?Oe:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ne=n["--persona-components-header-iconForeground"])!=null?Ne:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ot=n["--persona-components-header-titleForeground"])!=null?ot:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(St=n["--persona-components-header-subtitleForeground"])!=null?St:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Nt=n["--persona-components-header-actionIconForeground"])!=null?Nt:n["--persona-muted"];let o=(jt=e.components)==null?void 0:jt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(K=e.components)==null?void 0:K.introCard;n["--persona-intro-card-bg"]=(gt=n["--persona-components-introCard-background"])!=null?gt:n["--persona-surface"],n["--persona-intro-card-radius"]=(nt=n["--persona-components-introCard-borderRadius"])!=null?nt:"1rem",n["--persona-intro-card-padding"]=($t=n["--persona-components-introCard-padding"])!=null?$t:"1.5rem",n["--persona-intro-card-shadow"]=(ve=(ae=r==null?void 0:r.shadow)!=null?ae:n["--persona-components-introCard-shadow"])!=null?ve:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(wt=n["--persona-components-input-background"])!=null?wt:n["--persona-surface"],n["--persona-input-placeholder"]=(_t=n["--persona-components-input-placeholder"])!=null?_t:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Jt=n["--persona-components-message-user-background"])!=null?Jt:n["--persona-accent"],n["--persona-message-user-text"]=(vn=n["--persona-components-message-user-text"])!=null?vn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Et=n["--persona-components-message-user-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(At=n["--persona-components-message-assistant-background"])!=null?At:n["--persona-surface"],n["--persona-message-assistant-text"]=(ht=n["--persona-components-message-assistant-text"])!=null?ht:n["--persona-text"],n["--persona-message-assistant-border"]=(yt=n["--persona-components-message-assistant-border"])!=null?yt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Ut=n["--persona-components-message-assistant-shadow"])!=null?Ut:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Fn=(Ze=n["--persona-components-scrollToBottom-background"])!=null?Ze:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(xn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?xn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(On=n["--persona-components-scrollToBottom-border"])!=null?On:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(ar=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ar:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Ir=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=($o=n["--persona-components-scrollToBottom-padding"])!=null?$o:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Lo=n["--persona-components-scrollToBottom-gap"])!=null?Lo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(_n=(vt=n["--persona-components-scrollToBottom-fontSize"])!=null?vt:n["--persona-palette-typography-fontSize-sm"])!=null?_n:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Vn=n["--persona-components-scrollToBottom-iconSize"])!=null?Vn:"14px",n["--persona-tool-bubble-shadow"]=(wn=n["--persona-components-toolBubble-shadow"])!=null?wn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Rt=n["--persona-components-reasoningBubble-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(eo=n["--persona-components-composer-shadow"])!=null?eo:"none",n["--persona-md-inline-code-bg"]=(to=n["--persona-components-markdown-inlineCode-background"])!=null?to:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Io=(Uo=n["--persona-components-markdown-link-foreground"])!=null?Uo:n["--persona-accent"])!=null?Io:"#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"]=(zo=n["--persona-components-markdown-codeBlock-background"])!=null?zo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Un=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Un:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(Cn=n["--persona-components-markdown-table-headerBackground"])!=null?Cn:n["--persona-container"],n["--persona-md-table-border-color"]=(no=n["--persona-components-markdown-table-borderColor"])!=null?no:n["--persona-border"],n["--persona-md-hr-color"]=(qo=n["--persona-components-markdown-hr-color"])!=null?qo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ro=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ro:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jo=n["--persona-components-markdown-blockquote-background"])!=null?jo:"transparent",n["--persona-md-blockquote-text-color"]=(Co=n["--persona-components-markdown-blockquote-textColor"])!=null?Co:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zn=n["--persona-components-collapsibleWidget-container"])!=null?zn:n["--persona-surface"],n["--cw-surface"]=(po=n["--persona-components-collapsibleWidget-surface"])!=null?po:n["--persona-surface"],n["--cw-border"]=(ft=n["--persona-components-collapsibleWidget-border"])!=null?ft:n["--persona-border"],n["--persona-message-border"]=(Kt=n["--persona-components-message-border"])!=null?Kt: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 T=x.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(x!=null&&x.tab){let T=x.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(x!=null&&x.pane){let T=x.pane;if(T.toolbarBackground){let Kn=(jn=Vr(e,T.toolbarBackground))!=null?jn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var mg={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"}}},tu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ui=()=>{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"},gg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ui()},fg=e=>gg(e),hg=e=>nn(e),bg=e=>{var n;let t=nn(void 0,{validate:!1});return nn({...e,palette:{...t.palette,colors:{...mg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ta=e=>{let t=fg(e),n=tu(e==null?void 0:e.theme),o=tu(e==null?void 0:e.darkTheme);return t==="dark"?bg(Ts(n!=null?n:{},o!=null?o:{})):hg(n)},yg=e=>eu(e),$r=(e,t)=>{var s;let n=Ta(t),o=yg(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)},nu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ui())});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(Ui());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 zi(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function vr(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]:vr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var qi=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?{...kt,...n}:n!=null?n:kt,this.theme=nn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?zi(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?zi((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):zi(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=vr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:nn();this.config={...this.config,darkTheme:vr(s,r,n)}}else this.config=vr(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=vr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:nn();this.config={...this.config,darkTheme:vr(l,d,i)},o=!0}else this.config=vr(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=nn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=nn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...kt},this.theme=nn(),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=nn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function ji(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 Ki(e,t){return t==="rem"?`${e}rem`:`${e}px`}function vg(e,t){return t==="rem"?e*16:e}function xg(e,t){return t==="rem"?e/16:e}function ks(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 Gi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Yi(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 ka(e,t){let n=s=>{var l;let a=ks(s),i=a.startsWith("rgb")?(l=Yi(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 ou(e){var f;let t=ks(e),n=t.startsWith("rgb")?(f=Yi(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 ru(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 Xi(e){let{h:t,s:n,l:o}=ou(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]=ru(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],Qi=["primary","secondary","accent","gray","success","warning","error","info"];function wg(e,t){return`palette.colors.${e}.${t}`}function su(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.")?su(e,`theme.${o}`,n+1):"#cbd5e1"}function Cg(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 ko=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ea=["primary","secondary","accent","gray"],Sg={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ma={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:ko,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},La={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:ko,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"}]},Ia={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:ko,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Ra={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:ko,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Pa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:ko,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"}]},Wa={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:ko,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Ba={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:ko,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"}]},Ha={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:ko,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"}]},Da={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},xr=[Ma,La,Ia,Ra,Pa,Wa,Ba,Ha,Da];function Fa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ag(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 Ag(e,t,n,o){let r=t==="solid";if(o==="role-header")return Tg(e,r,n);if(o==="role-input")return kg(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 Tg(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 kg(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 Ji(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=Ea.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=Fa(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 Mg={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"}]}]},Lg={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"}]},Ig={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)"}]}]},Pg={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"}]}]},Wg={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"}}]},Bg={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)"}]},Hg={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"}]}]},zr=[Lg,Ig,Pg,Rg,Mg,Wg,Bg,Hg];function au(){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:Qi.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 iu={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"}}]},Dg=au(),Fg=iu,Og=[au(),iu],Ng={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:io},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Aa},{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"}]}]},_g={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"}]}]},Vg={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"}]}]},$g={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"}]}]},Ug={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"}]}]},zg={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"}}]},qg={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"}}]},jg={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"}}]},Kg={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"}}]},Gg={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"}]},lu=[Ng,_g,Vg,$g,Ug],cu=[zg,qg,jg,Kg,Gg],du=[...lu,...cu],Zi=1024*1024,Yg=["What can you help me with?","Tell me about your features","How does this work?"],Es={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)*Zi}function Qg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/Zi)):String(t):"10"}function Jg(e){var t;return(t=Es[String(e)])!=null?t:Es.images}function Zg(e){let t=Array.isArray(e)?e:Es.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Es)){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 ef={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"}]},tf={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:Yg}]},nf={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:""}]},of={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}]},rf={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"}]}]},sf={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"}]}]},af={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:io},{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"}]},lf={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:""}]},cf={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"}]},df={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"}]},pf={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"}]},uf={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"}]},mf={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:""}]},gf={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)}]},ff={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*Zi,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:Qg,parseValue:Xg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Es.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:Zg,parseValue:Jg}]},hf={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"}]}]},bf={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}]},yf={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"}]}]},vf={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}]},xf={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}]},Oa=[{label:"Content",sections:[ef,tf]},{label:"Layout",sections:[nf,of,rf,sf]},{label:"Widget",sections:[af,lf,cf,df,pf,uf]},{label:"Features",sections:[mf,gf,ff,hf,bf]},{label:"Developer",collapsedByDefault:!0,sections:[yf,vf,xf]}],pu=Oa.flatMap(e=>e.sections),uu={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"}]}]},mu={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"}]},gu={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"}]},fu={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:Ma},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:La},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ia},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ra},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Pa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Wa},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ba},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Ha},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Da}]},hu={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"}}]},bu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},wf=[uu,mu,gu,fu,hu,bu],el=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:du},{id:"configure",label:"Configure",sections:pu}];function yu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Cf(e,t,n){return{...e,id:`${n}-${e.id}`,path:yu(e.path,t)}}function Sf(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Af(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=>Cf(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])=>[yu(d,t),l]))}))}}var vu=[{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"]}],Ms=[...vu];function tl(e){return Ms.find(t=>t.id===e)}import{Marked as Tf}from"marked";var kf=e=>{if(e)return e},nl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Tf({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)},Na=e=>e?nl({markedOptions:e.options,renderer:e.renderer}):nl(),Jx=nl();var Ls=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");import Ef from"dompurify";var Mf={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Lf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,If=()=>{let e=Ef(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:")&&!Lf.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Mf)},_a=e=>e===!1?null:typeof e=="function"?e:If();var ol="webmcp:",Va={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function wu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var 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}:${Rf(t.join(""))}`}function xu(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 Rf(e){let t=xu(e,0).toString(36),n=xu(e,2654435761).toString(36);return`${t}.${n}`}var $a=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 Va.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=Bf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let g=typeof document!="undefined"&&!!document.modelContext;return vo(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=Pf(t),a;try{a=await r.getTools()}catch(g){let x=g instanceof Error?g.message:String(g);return vo(`Failed to read WebMCP registry: ${x}`)}let i=a.find(g=>g.name===s);if(!i)return vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("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,Of(n),{signal:l.signal});return Hf(g)}catch(g){if(u)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let x=g instanceof Error?g.message:String(g);return vo(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){Va.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Va.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Df;try{return await n(t)}catch(r){return Va.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=>Wf(t,o))}},Pf=e=>e.startsWith(ol)?e.slice(ol.length):e,rl=e=>e.startsWith(ol),Wf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Bf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Hf=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:Nf(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Df=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ff(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var Yp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ts(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];Yp(s)&&Yp(r)?n[o]=Ts(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Ta="440px",St={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:io,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 Xp(e,t){if(!(!e&&!t))return e?t?Ts(e,t):e:t}function Qp(e){var t,n,o,r,s,a,i,d,l,p,m,f,u,w,C,M,I,R,H,D,B;return e?{...St,...e,theme:Xp(St.theme,e.theme),darkTheme:Xp(St.darkTheme,e.darkTheme),launcher:{...St.launcher,...e.launcher,dock:{...(t=St.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=St.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...St.copy,...e.copy},sendButton:{...St.sendButton,...e.sendButton},statusIndicator:{...St.statusIndicator,...e.statusIndicator},voiceRecognition:{...St.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Fe,ve,J,Le,Y,xe,Se;let v=(be=St.features)==null?void 0:be.artifacts,x=(Fe=e.features)==null?void 0:Fe.artifacts,k=(ve=St.features)==null?void 0:ve.scrollToBottom,S=(J=e.features)==null?void 0:J.scrollToBottom,E=(Le=St.features)==null?void 0:Le.streamAnimation,F=(Y=e.features)==null?void 0:Y.streamAnimation,$=(xe=St.features)==null?void 0:xe.askUserQuestion,j=(Se=e.features)==null?void 0:Se.askUserQuestion,me=v===void 0&&x===void 0?void 0:{...v,...x,layout:{...v==null?void 0:v.layout,...x==null?void 0:x.layout}},se=k===void 0&&S===void 0?void 0:{...k,...S},ge=E===void 0&&F===void 0?void 0:{...E,...F},ie=$===void 0&&j===void 0?void 0:{...$,...j,styles:{...$==null?void 0:$.styles,...j==null?void 0:j.styles}};return{...St.features,...e.features,...se!==void 0?{scrollToBottom:se}:{},...me!==void 0?{artifacts:me}:{},...ge!==void 0?{streamAnimation:ge}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:St.suggestionChips,suggestionChipsConfig:{...St.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...St.layout,...e.layout,header:{...(a=St.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=St.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=St.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(f=e.layout)==null?void 0:f.messages)==null?void 0:u.avatar},timestamp:{...(C=(w=St.layout)==null?void 0:w.messages)==null?void 0:C.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(R=St.layout)==null?void 0:R.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...St.markdown,...e.markdown,options:{...(D=St.markdown)==null?void 0:D.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...St.messageActions,...e.messageActions}}:St}var lg={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"}},cg={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"}},dg={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:io,maxWidth:Ta,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 Vr(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."))?Vr(e,o):o}function Jp(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=Vr(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 pg(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 Zp(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]=Zp(s,r):n[o]=r}return n}function ug(e,t){return t?Zp(e,t):e}function tn(e,t={}){var r,s,a,i,d,l,p,m,f,u,w,C,M;let n={palette:lg,semantic:cg,components:dg},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,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(w=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:ug(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=pg(o);if(!I.valid)throw new Error(`Theme validation failed: ${I.errors.map(R=>R.message).join(", ")}`)}if(t.plugins)for(let I of t.plugins)o=I.transform(o);return o}function eu(e){var C,M,I,R,H,D,B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve,J,Le,Y,xe,Se,de,we,Ue,te,ne,re,nt,ye,le,$e,Be,ce,K,_e,Et,pe,ae,Ln,Nt,ln,Dn,Jn,ze,_,ke,He,De,Ve,dt,ot,At,Vt,q,_t,Qe,Ft,oe,fe,xt,$t,Jt,yn,Tt,wt,ft,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn;let t=Jp(e),n={};for(let[T,Kn]of Object.entries(t)){let mo=T.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(C=n["--persona-semantic-colors-primary"])!=null?C:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(I=n["--persona-semantic-colors-accent"])!=null?I:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(R=n["--persona-semantic-colors-surface"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(H=n["--persona-semantic-colors-background"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(B=n["--persona-semantic-colors-text"])!=null?B: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"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S: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"]=($=n["--persona-components-voice-processing-icon"])!=null?$: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"]=(me=n["--persona-components-approval-requested-background"])!=null?me: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"]=(ge=n["--persona-components-approval-requested-text"])!=null?ge:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ie=n["--persona-components-approval-approve-background"])!=null?ie:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(be=n["--persona-components-approval-deny-background"])!=null?be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Fe=n["--persona-components-attachment-image-background"])!=null?Fe: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"]=(J=n["--persona-semantic-typography-fontFamily"])!=null?J:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Le=n["--persona-semantic-typography-fontSize"])!=null?Le:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Y=n["--persona-semantic-typography-fontWeight"])!=null?Y:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(xe=n["--persona-semantic-typography-lineHeight"])!=null?xe: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"]=(Se=n["--persona-palette-radius-sm"])!=null?Se:"0.125rem",n["--persona-radius-md"]=(de=n["--persona-palette-radius-md"])!=null?de:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(Ue=n["--persona-palette-radius-xl"])!=null?Ue:"0.75rem",n["--persona-radius-full"]=(te=n["--persona-palette-radius-full"])!=null?te:"9999px",n["--persona-launcher-radius"]=(re=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?re:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(ye=n["--persona-components-launcher-foreground"])!=null?ye:n["--persona-text-inverse"],n["--persona-launcher-border"]=(le=n["--persona-components-launcher-border"])!=null?le:n["--persona-border"],n["--persona-button-primary-bg"]=($e=n["--persona-components-button-primary-background"])!=null?$e:n["--persona-primary"],n["--persona-button-primary-fg"]=(Be=n["--persona-components-button-primary-foreground"])!=null?Be:n["--persona-text-inverse"],n["--persona-button-radius"]=(K=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?K:"9999px",n["--persona-panel-radius"]=(Et=(_e=n["--persona-components-panel-borderRadius"])!=null?_e:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Nt=n["--persona-components-input-borderRadius"])!=null?Nt:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Jn=(Dn=n["--persona-components-message-user-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?Jn:"0.5rem",n["--persona-message-assistant-radius"]=(_=(ze=n["--persona-components-message-assistant-borderRadius"])!=null?ze:n["--persona-radius-lg"])!=null?_:"0.5rem",n["--persona-header-bg"]=(ke=n["--persona-components-header-background"])!=null?ke:n["--persona-surface"],n["--persona-header-border"]=(He=n["--persona-components-header-border"])!=null?He:n["--persona-divider"],n["--persona-header-icon-bg"]=(De=n["--persona-components-header-iconBackground"])!=null?De:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ve=n["--persona-components-header-iconForeground"])!=null?Ve:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(ot=n["--persona-components-header-subtitleForeground"])!=null?ot:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let o=(Vt=e.components)==null?void 0:Vt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Qe=n["--persona-components-introCard-borderRadius"])!=null?Qe:"1rem",n["--persona-intro-card-padding"]=(Ft=n["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",n["--persona-intro-card-shadow"]=(fe=(oe=r==null?void 0:r.shadow)!=null?oe:n["--persona-components-introCard-shadow"])!=null?fe:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(xt=n["--persona-components-input-background"])!=null?xt:n["--persona-surface"],n["--persona-input-placeholder"]=($t=n["--persona-components-input-placeholder"])!=null?$t:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Jt=n["--persona-components-message-user-background"])!=null?Jt:n["--persona-accent"],n["--persona-message-user-text"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(ft=n["--persona-components-message-assistant-text"])!=null?ft:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(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"]=(Fn=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?vn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(On=n["--persona-components-scrollToBottom-border"])!=null?On:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(ir=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ir:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Rr=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=($o=n["--persona-components-scrollToBottom-padding"])!=null?$o:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Lo=n["--persona-components-scrollToBottom-gap"])!=null?Lo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(_n=(yt=n["--persona-components-scrollToBottom-fontSize"])!=null?yt:n["--persona-palette-typography-fontSize-sm"])!=null?_n:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Vn=n["--persona-components-scrollToBottom-iconSize"])!=null?Vn:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(It=n["--persona-components-reasoningBubble-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(eo=n["--persona-components-composer-shadow"])!=null?eo:"none",n["--persona-md-inline-code-bg"]=(to=n["--persona-components-markdown-inlineCode-background"])!=null?to:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Io=(Uo=n["--persona-components-markdown-link-foreground"])!=null?Uo:n["--persona-accent"])!=null?Io:"#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"]=(zo=n["--persona-components-markdown-codeBlock-background"])!=null?zo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Un=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Un:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(wn=n["--persona-components-markdown-table-headerBackground"])!=null?wn:n["--persona-container"],n["--persona-md-table-border-color"]=(no=n["--persona-components-markdown-table-borderColor"])!=null?no:n["--persona-border"],n["--persona-md-hr-color"]=(qo=n["--persona-components-markdown-hr-color"])!=null?qo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ro=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ro:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jo=n["--persona-components-markdown-blockquote-background"])!=null?jo:"transparent",n["--persona-md-blockquote-text-color"]=(Co=n["--persona-components-markdown-blockquote-textColor"])!=null?Co:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zn=n["--persona-components-collapsibleWidget-container"])!=null?zn:n["--persona-surface"],n["--cw-surface"]=(po=n["--persona-components-collapsibleWidget-surface"])!=null?po:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Kt=n["--persona-components-message-border"])!=null?Kt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let w=p==null?void 0:p.artifact;if(w!=null&&w.toolbar){let T=w.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(w!=null&&w.tab){let T=w.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(w!=null&&w.pane){let T=w.pane;if(T.toolbarBackground){let Kn=(jn=Vr(e,T.toolbarBackground))!=null?jn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var mg={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"}}},tu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},zi=()=>{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"},gg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":zi()},fg=e=>gg(e),hg=e=>tn(e),bg=e=>{var n;let t=tn(void 0,{validate:!1});return tn({...e,palette:{...t.palette,colors:{...mg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ka=e=>{let t=fg(e),n=tu(e==null?void 0:e.theme),o=tu(e==null?void 0:e.darkTheme);return t==="dark"?bg(Ts(n!=null?n:{},o!=null?o:{})):hg(n)},yg=e=>eu(e),$r=(e,t)=>{var s;let n=ka(t),o=yg(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)},nu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(zi())});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(zi());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 qi(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function xr(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]:xr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var ji=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?{...St,...n}:n!=null?n:St,this.theme=tn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?qi(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?qi((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):qi(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=xr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:tn();this.config={...this.config,darkTheme:xr(s,r,n)}}else this.config=xr(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=xr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:tn();this.config={...this.config,darkTheme:xr(l,d,i)},o=!0}else this.config=xr(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=tn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=tn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...St},this.theme=tn(),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=tn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Ki(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 Gi(e,t){return t==="rem"?`${e}rem`:`${e}px`}function vg(e,t){return t==="rem"?e*16:e}function xg(e,t){return t==="rem"?e/16:e}function ks(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 Yi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Xi(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("%"),p=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(p)?Math.max(0,Math.min(255,Math.round(l?p/100*255:p))):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 Ea(e,t){let n=s=>{var l;let a=ks(s),i=a.startsWith("rgb")?(l=Xi(a))!=null?l:"#000000":a,d=[1,3,5].map(p=>{let m=parseInt(i.slice(p,p+2),16)/255;return m<=.03928?m/12.92:Math.pow((m+.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 ou(e){var f;let t=ks(e),n=t.startsWith("rgb")?(f=Xi(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,p=d>.5?l/(2-a-i):l/(a+i),m;switch(a){case o:m=((r-s)/l+(r<s?6:0))/6;break;case r:m=((s-o)/l+2)/6;break;default:m=((o-r)/l+4)/6;break}return{h:m*360,s:p,l:d}}function ru(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 p=m=>{let f=Math.round((m+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${p(i)}${p(d)}${p(l)}`}function Qi(e){let{h:t,s:n,l:o}=ou(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]=ru(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],Ji=["primary","secondary","accent","gray","success","warning","error","info"];function wg(e,t){return`palette.colors.${e}.${t}`}function su(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.")?su(e,`theme.${o}`,n+1):"#cbd5e1"}function Cg(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 ko=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ma=["primary","secondary","accent","gray"],Sg={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},La={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:ko,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Ia={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:ko,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"}]},Ra={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:ko,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Pa={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:ko,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Wa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:ko,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"}]},Ba={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:ko,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Ha={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:ko,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"}]},Da={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:ko,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"}]},Fa={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},wr=[La,Ia,Ra,Pa,Wa,Ba,Ha,Da,Fa];function Oa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ag(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 Ag(e,t,n,o){let r=t==="solid";if(o==="role-header")return Tg(e,r,n);if(o==="role-input")return kg(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 Tg(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 kg(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 Zi(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=Ma.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let p=Oa(a,l,t);if(t.targets.every(f=>{var w;return String((w=e(f.path))!=null?w:"")===p[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var Mg={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"}]}]},Lg={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"}]},Ig={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)"}]}]},Pg={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"}]}]},Wg={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"}}]},Bg={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)"}]},Hg={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"}]}]},zr=[Lg,Ig,Pg,Rg,Mg,Wg,Bg,Hg];function au(){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:Ji.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 iu={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"}}]},Dg=au(),Fg=iu,Og=[au(),iu],Ng={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:io},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ta},{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"}]}]},_g={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"}]}]},Vg={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"}]}]},$g={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"}]}]},Ug={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"}]}]},zg={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"}}]},qg={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"}}]},jg={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"}}]},Kg={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"}}]},Gg={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"}]},lu=[Ng,_g,Vg,$g,Ug],cu=[zg,qg,jg,Kg,Gg],du=[...lu,...cu],el=1024*1024,Yg=["What can you help me with?","Tell me about your features","How does this work?"],Es={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)*el}function Qg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/el)):String(t):"10"}function Jg(e){var t;return(t=Es[String(e)])!=null?t:Es.images}function Zg(e){let t=Array.isArray(e)?e:Es.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Es)){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 ef={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"}]},tf={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:Yg}]},nf={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:""}]},of={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}]},rf={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"}]}]},sf={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"}]}]},af={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:io},{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"}]},lf={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:""}]},cf={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"}]},df={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"}]},pf={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"}]},uf={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"}]},mf={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:""}]},gf={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)}]},ff={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*el,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:Qg,parseValue:Xg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Es.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:Zg,parseValue:Jg}]},hf={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"}]}]},bf={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}]},yf={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"}]}]},vf={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}]},xf={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}]},Na=[{label:"Content",sections:[ef,tf]},{label:"Layout",sections:[nf,of,rf,sf]},{label:"Widget",sections:[af,lf,cf,df,pf,uf]},{label:"Features",sections:[mf,gf,ff,hf,bf]},{label:"Developer",collapsedByDefault:!0,sections:[yf,vf,xf]}],pu=Na.flatMap(e=>e.sections),uu={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"}]}]},mu={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"}]},gu={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"}]},fu={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:La},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Ia},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ra},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Pa},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Wa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Ba},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ha},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Da},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Fa}]},hu={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"}}]},bu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},wf=[uu,mu,gu,fu,hu,bu],tl=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:du},{id:"configure",label:"Configure",sections:pu}];function yu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Cf(e,t,n){return{...e,id:`${n}-${e.id}`,path:yu(e.path,t)}}function Sf(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Af(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=>Cf(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])=>[yu(d,t),l]))}))}}var vu=[{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"]}],Ms=[...vu];function nl(e){return Ms.find(t=>t.id===e)}import{Marked as Tf}from"marked";var kf=e=>{if(e)return e},ol=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Tf({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)},_a=e=>e?ol({markedOptions:e.options,renderer:e.renderer}):ol(),Jx=ol();var Ls=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");import Ef from"dompurify";var Mf={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Lf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,If=()=>{let e=Ef(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:")&&!Lf.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Mf)},Va=e=>e===!1?null:typeof e=="function"?e:If();var rl="webmcp:",$a={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function wu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var 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}:${Rf(t.join(""))}`}function xu(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 Rf(e){let t=xu(e,0).toString(36),n=xu(e,2654435761).toString(36);return`${t}.${n}`}var Ua=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 $a.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=Bf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let u=typeof document!="undefined"&&!!document.modelContext;return vo(u?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Pf(t),a;try{a=await r.getTools()}catch(u){let w=u instanceof Error?u.message:String(u);return vo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(u=>u.name===s);if(!i)return vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),f=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",f,{once:!0}));try{let u=await r.executeTool(i,Of(n),{signal:l.signal});return Hf(u)}catch(u){if(p)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let w=u instanceof Error?u.message:String(u);return vo(w)}finally{clearTimeout(m),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){$a.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,$a.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:Df;try{return await n(t)}catch(r){return $a.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=>Wf(t,o))}},Pf=e=>e.startsWith(rl)?e.slice(rl.length):e,sl=e=>e.startsWith(rl),Wf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Bf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Hf=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:Nf(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Df=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ff(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
4
  ${t}`:"")+(e.description?`
5
5
 
6
6
  ${e.description}`:"");return window.confirm(n)},Ff=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)}},Of=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Nf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as _f,STR as Vf,OBJ as $f}from"partial-json";var Cu=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),qr=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)}},Uf=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`},Su=e=>e.status==="complete"?Uf(e):e.status==="pending"?"Waiting":"",zf=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 Au=e=>e.status==="complete"?zf(e):"Using tool...",Ua=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Rs=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 Ua(t)},za=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 Ua(t)},sl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Rs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Is(o,n.slice(s,a.index),[]),a[1]!==void 0?Is(o,a[1],["bold"]):a[2]!==void 0?Is(o,a[2],["italic"]):a[3]!==void 0&&Is(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Is(o,n.slice(s),[]),o},Is=(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})},qf=()=>{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,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),qr=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)}},Uf=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`},Su=e=>e.status==="complete"?Uf(e):e.status==="pending"?"Waiting":"",zf=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 Au=e=>e.status==="complete"?zf(e):"Using tool...",za=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Rs=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 za(t)},qa=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 za(t)},al=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Rs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ja=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Is(o,n.slice(s,a.index),[]),a[1]!==void 0?Is(o,a[1],["bold"]):a[2]!==void 0?Is(o,a[2],["italic"]):a[3]!==void 0&&Is(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Is(o,n.slice(s),[]),o},Is=(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})},qf=()=>{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()=>{}}},wr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ku=()=>{var t;let e=qf();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)}},Eu=()=>{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=_f(n,Vf|$f);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mu=()=>{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 ja=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var 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 jf="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function Kf(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 al=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 Gf(e){switch(e){case"json":return Eu;case"regex-json":return ku;case"xml":return Mu;default:return Tu}}var Lu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Yf(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=Lu(n);if(!Lu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=wr(e);return wr(t)!==null&&a===null?t:e}var Ps=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:jf,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Gf(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 $a(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$/,""))||Ka}/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$/,""))||Ka}/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 D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(al).map(D=>{var B,v,w;return{id:D.id,role:D.role,content:(w=(v=(B=D.contentParts)!=null?B:D.llmContent)!=null?v:D.rawContent)!=null?w:D.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?wu(f):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,M=g&&C&&this.lastSentClientToolsFingerprint===x,W=!1,L=null,H;for(let D=0;;D++){let v={...p,...g&&(W||!M)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),H=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),H.status===409&&D===0&&g){let w=await H.json().catch(()=>null);if((w==null?void 0:w.error)==="client_tools_resend_required"){W=!0,this.lastSentClientToolsFingerprint=null;continue}L=w!=null?w:{error:"Chat request failed"}}break}if(!H.ok){let D=L!=null?L:await H.json().catch(()=>({error:"Chat request failed"}));if(H.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(H.status===429){let v=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let B=new Error(D.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!H.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(H.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$/,""))||Ka}/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(/\/+$/,""))||Ka}/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(al).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(al).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 Ft,ln,Dn,Jn;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=N=>{let se=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,He=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,Xe=N.tools?N.tools.map(Oe=>({...Oe,chunks:Oe.chunks?[...Oe.chunks]:void 0})):void 0;return{...N,reasoning:se,toolCall:He,tools:Xe}},p=N=>{n({type:"message",message:u(N)})},f=null,g=null,x={current:null},C={current:null},M=!1,W=new Map,L=new Map,H=new Map,D=new Map,B={lastId:null,byStep:new Map},v={lastId:null,byCall:new Map},w=(N,se,He="")=>`${N}::${se}::${He}`,E=(N,se)=>`${N}::${se}::`,S=(N,se,He,Xe)=>{let Oe=w(N,se,He),Ne=H.get(Oe);if(Ne)return Ne;let ot=He?`-${He}`:"",St={id:`nested-${N}-${se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Xe,parentToolId:N,parentStepId:se}};return H.set(Oe,St),p(St),St},k=N=>{if(N==null)return null;try{return String(N)}catch{return null}},F=N=>{var se,He,Xe,Oe,Ne;return k((Ne=(Oe=(Xe=(He=(se=N.stepId)!=null?se:N.step_id)!=null?He:N.step)!=null?Xe:N.parentId)!=null?Oe:N.flowStepId)!=null?Ne:N.flow_step_id)},$=N=>{var se,He,Xe,Oe,Ne,ot,St;return k((St=(ot=(Ne=(Oe=(Xe=(He=(se=N.callId)!=null?se:N.call_id)!=null?He:N.requestId)!=null?Xe:N.request_id)!=null?Oe:N.toolCallId)!=null?Ne:N.tool_call_id)!=null?ot:N.stepId)!=null?St:N.step_id)},q=o,me=!1,re=()=>{if(f)return f;let N;return!me&&q?(N=q,me=!0):q&&C.current?N=`${q}_${C.current}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:N,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},be=(N,se)=>{B.lastId=se,N&&B.byStep.set(N,se)},ie=(N,se)=>{var Ne;let He=(Ne=N.reasoningId)!=null?Ne:N.id,Xe=F(N);if(He){let ot=String(He);return be(Xe,ot),ot}if(Xe){let ot=B.byStep.get(Xe);if(ot)return B.lastId=ot,ot}if(B.lastId&&!se)return B.lastId;if(!se)return null;let Oe=`reason-${l()}`;return be(Xe,Oe),Oe},we=N=>{let se=W.get(N);if(se)return se;let He={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,He),p(He),He},We=(N,se)=>{v.lastId=se,N&&v.byCall.set(N,se)},ye=new Set,Z=new Map,Ee=new Set,X=new Map,Ae=N=>{if(!N)return!1;let se=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return se==="emit_artifact_markdown"||se==="emit_artifact_component"},fe=(N,se)=>{var Ne;let He=(Ne=N.toolId)!=null?Ne:N.id,Xe=$(N);if(He){let ot=String(He);return We(Xe,ot),ot}if(Xe){let ot=v.byCall.get(Xe);if(ot)return v.lastId=ot,ot}if(v.lastId&&!se)return v.lastId;if(!se)return null;let Oe=`tool-${l()}`;return We(Xe,Oe),Oe},le=N=>{let se=L.get(N);if(se)return se;let He={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:N,status:"pending"}};return L.set(N,He),p(He),He},ue=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let se=Number(N);if(!Number.isNaN(se)&&Number.isFinite(se))return se;let He=Date.parse(N);if(!Number.isNaN(He))return He}return Date.now()},je=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},j=new Map,oe=new Map,Re=new Map,tt=new Map,ge=null,ce=(N,se,He)=>{var St;let Xe=Re.get(N);Xe||(Xe=[],Re.set(N,Xe));let Oe=0,Ne=Xe.length;for(;Oe<Ne;){let Nt=Oe+Ne>>>1;Xe[Nt].seq<se?Oe=Nt+1:Ne=Nt}((St=Xe[Oe])==null?void 0:St.seq)===se?Xe[Oe]={seq:se,text:He}:Xe.splice(Oe,0,{seq:se,text:He});let ot="";for(let Nt=0;Nt<Xe.length;Nt++)ot+=Xe[Nt].text;return ot},_e=(N,se)=>{let He=je(se),Xe=oe.get(N.id),Oe=Yf(Xe,He);N.rawContent=Oe;let Ne=j.get(N.id),ot=gt=>{var $t;let nt=($t=N.content)!=null?$t:"";gt.trim()!==""&&(nt.trim().length===0||gt.startsWith(nt)||gt.trimStart().startsWith(nt.trim()))&&(N.content=gt)},St=()=>{var gt;if(Ne){let nt=(gt=Ne.close)==null?void 0:gt.call(Ne);nt instanceof Promise&&nt.catch(()=>{})}j.delete(N.id),oe.delete(N.id),N.streaming=!1,p(N)};if(!Ne){ot(He),St();return}let Nt=wr(Oe);if(Nt!==null&&Nt.trim()!==""){ot(Nt),St();return}let jt=gt=>{var ae;let nt=typeof gt=="string"?gt:(ae=gt==null?void 0:gt.text)!=null?ae:null;if(nt!==null&&nt.trim()!=="")return nt;let $t=Ne.getExtractedText();return $t!==null&&$t.trim()!==""?$t:He},K;try{K=Ne.processChunk(Oe)}catch{ot(He),St();return}if(K instanceof Promise){K.then(gt=>{ot(jt(gt)),St()}).catch(()=>{ot(He),St()});return}ot(jt(K)),St()},Le=[],de=!1,Y,Ve=()=>{de||(de=!0,queueMicrotask(()=>{de=!1,Y()}))},Ct=new ja((N,se)=>{Le.push({payloadType:N,payload:se}),Ve()}),Q=null,Fe=new Map,Ln=(Ft=this.config.iterationDisplay)!=null?Ft:"separate";for(Y=()=>{var N,se,He,Xe,Oe,Ne,ot,St,Nt,jt,K,gt,nt,$t,ae,ve,wt,_t,Jt,vn,Et,At,ht,yt,Ut,Ze,Fn,Zn,xn,On,ut,wo,Nn,ar,In,Ir,$o,Lo,vt,_n,Vn,wn,Rt,eo,to,$n,Uo,Io,zo,Un,Wt,Cn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn,T,Kn,mo,Po,So,ss,go,fo,ho,Wo,ir,ra,as,sa,Rr,mt,is,ro,Rn,aa,ia,Pr,Bo,la,lr,ls,Ho,cs,Go,Yo,ca,da,Vi,cr,Xo,pa,ds,Qo,ua,ps,Jo,us,ma,Do,ga,Zo,Bt,Wr,Br,ms,Ao,fa,gs,fs,ha,Hr,Dr,dr,ba,ya,hs,bs,ys,vs,Sn,Gn,Fo,rt,xs,pr,bo;for(let Fr=0;Fr<Le.length;Fr++){let Ue=Le[Fr].payloadType,A=Le[Fr].payload;if(Ue==="reason_start"){let U=(N=ie(A,!0))!=null?N:`reason-${l()}`,R=we(U);R.reasoning=(se=R.reasoning)!=null?se:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(Xe=R.reasoning.startedAt)!=null?Xe:ue((He=A.startedAt)!=null?He:A.timestamp),R.reasoning.completedAt=void 0,R.reasoning.durationMs=void 0,R.streaming=!0,R.reasoning.status="streaming",p(R)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let U=(Ne=(Oe=ie(A,!1))!=null?Oe:ie(A,!0))!=null?Ne:`reason-${l()}`,R=we(U);R.reasoning=(ot=R.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(Nt=R.reasoning.startedAt)!=null?Nt:ue((St=A.startedAt)!=null?St:A.timestamp);let ee=(gt=(K=(jt=A.reasoningText)!=null?jt:A.text)!=null?K:A.delta)!=null?gt:"";if(ee&&A.hidden!==!0){let te=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(te!==void 0){let G=ce(U,te,String(ee));R.reasoning.chunks=[G]}else R.reasoning.chunks.push(String(ee))}if(R.reasoning.status=A.done?"complete":"streaming",A.done){R.reasoning.completedAt=ue((nt=A.completedAt)!=null?nt:A.timestamp);let te=($t=R.reasoning.startedAt)!=null?$t:Date.now();R.reasoning.durationMs=Math.max(0,((ae=R.reasoning.completedAt)!=null?ae:Date.now())-te)}R.streaming=R.reasoning.status!=="complete",p(R)}else if(Ue==="reason_complete"){let U=(wt=(ve=ie(A,!1))!=null?ve:ie(A,!0))!=null?wt:`reason-${l()}`,R=W.get(U);if(R!=null&&R.reasoning){R.reasoning.status="complete",R.reasoning.completedAt=ue((_t=A.completedAt)!=null?_t:A.timestamp);let te=(Jt=R.reasoning.startedAt)!=null?Jt:Date.now();R.reasoning.durationMs=Math.max(0,((vn=R.reasoning.completedAt)!=null?vn:Date.now())-te),R.streaming=!1,p(R)}let ee=F(A);ee&&B.byStep.delete(ee)}else if(Ue==="tool_start"){let U=(Et=fe(A,!0))!=null?Et:`tool-${l()}`,R=(At=A.toolName)!=null?At:A.name;if(Ae(R)){ye.add(U);continue}let ee=le(U),te=(ht=ee.toolCall)!=null?ht:{id:U,status:"pending"};te.name=R!=null?R:te.name,te.status="running",A.args!==void 0?te.args=A.args:A.parameters!==void 0&&(te.args=A.parameters),te.startedAt=(Ut=te.startedAt)!=null?Ut:ue((yt=A.startedAt)!=null?yt:A.timestamp),te.completedAt=void 0,te.durationMs=void 0,ee.toolCall=te,ee.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(ee.agentMetadata={executionId:(Ze=G==null?void 0:G.executionId)!=null?Ze:A.executionId,iteration:(Fn=G==null?void 0:G.iteration)!=null?Fn:A.iteration}),p(ee)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let U=(xn=(Zn=fe(A,!1))!=null?Zn:fe(A,!0))!=null?xn:`tool-${l()}`;if(ye.has(U))continue;let R=le(U),ee=(On=R.toolCall)!=null?On:{id:U,status:"running"};ee.startedAt=(wo=ee.startedAt)!=null?wo:ue((ut=A.startedAt)!=null?ut:A.timestamp);let te=(In=(ar=(Nn=A.text)!=null?Nn:A.delta)!=null?ar:A.message)!=null?In:"";te&&(ee.chunks=(Ir=ee.chunks)!=null?Ir:[],ee.chunks.push(String(te))),ee.status="running",R.toolCall=ee,R.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(R.agentMetadata=(vt=R.agentMetadata)!=null?vt:{executionId:($o=G==null?void 0:G.executionId)!=null?$o:A.executionId,iteration:(Lo=G==null?void 0:G.iteration)!=null?Lo:A.iteration}),p(R)}else if(Ue==="tool_complete"){let U=(Vn=(_n=fe(A,!1))!=null?_n:fe(A,!0))!=null?Vn:`tool-${l()}`;if(ye.has(U)){ye.delete(U);continue}let R=le(U),ee=(wn=R.toolCall)!=null?wn:{id:U,status:"running"};ee.status="complete",A.result!==void 0&&(ee.result=A.result),typeof A.duration=="number"&&(ee.duration=A.duration),ee.completedAt=ue((Rt=A.completedAt)!=null?Rt:A.timestamp);let te=(eo=A.duration)!=null?eo:A.executionTime;if(typeof te=="number")ee.durationMs=te;else{let De=(to=ee.startedAt)!=null?to:Date.now();ee.durationMs=Math.max(0,(($n=ee.completedAt)!=null?$n:Date.now())-De)}R.toolCall=ee,R.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(R.agentMetadata=(zo=R.agentMetadata)!=null?zo:{executionId:(Uo=G==null?void 0:G.executionId)!=null?Uo:A.executionId,iteration:(Io=G==null?void 0:G.iteration)!=null?Io:A.iteration}),p(R);let ze=$(A);ze&&v.byCall.delete(ze)}else if(Ue==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,R=(Un=U!=null?U:A.toolId)!=null?Un:`local-${l()}`,ee=le(R),te=(Wt=ee.toolCall)!=null?Wt:{id:R,status:"pending"};te.name=A.toolName,te.args=A.parameters,te.status="complete",te.chunks=(Cn=te.chunks)!=null?Cn:[],te.startedAt=(qo=te.startedAt)!=null?qo:ue((no=A.startedAt)!=null?no:A.timestamp),te.completedAt=(Ro=te.completedAt)!=null?Ro:te.startedAt,ee.toolCall=te,ee.streaming=!1,ee.agentMetadata={...ee.agentMetadata,executionId:(Co=A.executionId)!=null?Co:(jo=ee.agentMetadata)==null?void 0:jo.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(ee)}else if(Ue==="text_start"){if((zn=A.toolContext)!=null&&zn.toolId)continue;let U=A.partId;if(U!==void 0&&C.current!==null&&U!==C.current){let R=f;R&&(R.streaming=!1,p(R),ge=R,f=null,M=!0)}U!==void 0&&(C.current=U)}else if(Ue==="text_end"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=f;U&&(U.streaming=!1,p(U),ge=U,f=null,M=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let U=A.stepType,R=A.executionType;if(U==="tool"||R==="context")continue;let ee=A.toolContext;if(ee!=null&&ee.toolId){let De=String((Kt=(ft=A.id)!=null?ft:ee.stepId)!=null?Kt:`step-${l()}`),at=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ke=`${ee.toolId}::${De}`,Ge=D.get(Ke);if(at!==""&&Ge!==void 0&&Ge!==""&&Ge!==at){let Tt=H.get(w(ee.toolId,De,Ge));Tt&&Tt.streaming!==!1&&(Tt.streaming=!1,p(Tt))}at!==""&&D.set(Ke,at);let Qe=S(ee.toolId,De,at,ee.executionId),Yt=(oo=(Ko=(qn=(Gt=A.text)!=null?Gt:A.delta)!=null?qn:A.content)!=null?Ko:A.chunk)!=null?oo:"";Yt&&(Qe.content+=String(Yt),Qe.streaming=!0,p(Qe)),A.isComplete&&(Qe.streaming=!1,p(Qe));continue}let te=A.partId;if(te!==void 0&&C.current!==null&&te!==C.current){let De=f;De&&(De.streaming=!1,p(De),ge=De,f=null,M=!0)}te!==void 0&&(C.current=te);let G=te!==void 0&&(uo=tt.get(te))!=null?uo:re();te!==void 0&&(G.partId||(G.partId=te),tt.set(te,G));let ze=(mo=(Kn=(T=(jn=A.text)!=null?jn:A.delta)!=null?T:A.content)!=null?Kn:A.chunk)!=null?mo:"";if(ze){let De=typeof A.seq=="number"?A.seq:void 0,at=te!=null?te:G.id,Ke=De!==void 0?ce(at,De,String(ze)):((Po=oe.get(G.id))!=null?Po:"")+ze;G.rawContent=Ke,j.has(G.id)||j.set(G.id,this.createStreamParser());let Ge=j.get(G.id),Qe=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(Qe&&oe.set(G.id,Ke),Ge.__isPlainTextParser===!0){G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G);continue}let Tt=Ge.processChunk(Ke);if(Tt instanceof Promise)Tt.then(Lt=>{var mn;let on=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(on!==null&&on.trim()!=="")G.content=on,p(G);else if(!Qe&&!Ke.trim().startsWith("<")){let cn=f,Zt=cn&&cn.id===G.id?cn:G;Zt.id===G.id&&(Zt.content=De!==void 0?Ke:Zt.content+ze,oe.delete(Zt.id),j.delete(Zt.id),Zt.rawContent=void 0,p(Zt))}}).catch(()=>{G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G)});else{let Lt=typeof Tt=="string"?Tt:(So=Tt==null?void 0:Tt.text)!=null?So:null;Lt!==null&&Lt.trim()!==""?(G.content=Lt,p(G)):!Qe&&!Ke.trim().startsWith("<")&&(G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G))}}if(A.isComplete){let De=(go=(ss=A.result)==null?void 0:ss.response)!=null?go:G.content;if(De){let at=oe.get(G.id),Ke=at!=null?at:je(De);G.rawContent=Ke;let Ge=j.get(G.id),Qe=null,Yt=!1;if(Ge&&(Qe=Ge.getExtractedText(),Qe===null&&(Qe=wr(Ke)),Qe===null)){let Tt=Ge.processChunk(Ke);Tt instanceof Promise?(Yt=!0,Tt.then(Lt=>{var mn;let on=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(on!==null){let cn=f;cn&&cn.id===G.id&&(cn.content=on,cn.streaming=!1,j.delete(cn.id),oe.delete(cn.id),p(cn))}})):Qe=typeof Tt=="string"?Tt:(fo=Tt==null?void 0:Tt.text)!=null?fo:null}if(!Yt){Qe!==null&&Qe.trim()!==""?G.content=Qe:oe.has(G.id)||(G.content=je(De));let Tt=j.get(G.id);if(Tt){let Lt=(ho=Tt.close)==null?void 0:ho.call(Tt);Lt instanceof Promise&&Lt.catch(()=>{}),j.delete(G.id)}oe.delete(G.id),G.streaming=!1,p(G)}}}}else if(Ue==="step_complete"){let U=A.stepType,R=A.executionType;if(U==="tool"||R==="context")continue;let ee=A.toolContext;if(ee!=null&&ee.toolId){let De=String((ir=(Wo=A.id)!=null?Wo:ee.stepId)!=null?ir:"");if(De){let at=E(ee.toolId,De);for(let[Ke,Ge]of H)Ke.startsWith(at)&&Ge.streaming!==!1&&(Ge.streaming=!1,p(Ge));D.delete(`${ee.toolId}::${De}`)}continue}let te=A.stopReason;if(M){if(f!==null){let Ke=f;te&&(Ke.stopReason=te),j.delete(Ke.id),oe.delete(Ke.id),Ke.streaming!==!1&&(Ke.streaming=!1,p(Ke))}let De=(ra=A.result)==null?void 0:ra.response,at=ge;at&&(te&&(at.stopReason=te),De!=null?_e(at,De):(j.delete(at.id),oe.delete(at.id))),ge=null;continue}let G=(as=A.result)==null?void 0:as.response,ze=re();if(te&&(ze.stopReason=te),G!=null){let De=j.get(ze.id),at=!1,Ke=!1;if(De){let Ge=De.getExtractedText(),Qe=oe.get(ze.id),Yt=Qe!=null?Qe:je(G);if(ze.rawContent=Yt,Ge!==null&&Ge.trim()!=="")ze.content=Ge,at=!0;else{let Tt=wr(Yt);if(Tt!==null)ze.content=Tt,at=!0;else{let Lt=De.processChunk(Yt);if(Lt instanceof Promise)Ke=!0,Lt.then(on=>{var cn;let mn=typeof on=="string"?on:(cn=on==null?void 0:on.text)!=null?cn:null;if(mn!==null&&mn.trim()!==""){let Zt=f;Zt&&Zt.id===ze.id&&(Zt.content=mn,Zt.streaming=!1,j.delete(Zt.id),oe.delete(Zt.id),p(Zt))}else{let Zt=De.getExtractedText(),so=f;so&&so.id===ze.id&&(Zt!==null&&Zt.trim()!==""?so.content=Zt:oe.has(so.id)||(so.content=je(G)),so.streaming=!1,j.delete(so.id),oe.delete(so.id),p(so))}});else{let on=typeof Lt=="string"?Lt:(sa=Lt==null?void 0:Lt.text)!=null?sa:null;if(on!==null&&on.trim()!=="")ze.content=on,at=!0;else{let mn=De.getExtractedText();mn!==null&&mn.trim()!==""&&(ze.content=mn,at=!0)}}}}}if(!Ke){if(!ze.rawContent){let Ge=oe.get(ze.id);ze.rawContent=Ge!=null?Ge:je(G)}if(!at&&!oe.has(ze.id)&&(ze.content=je(G)),De){let Ge=(Rr=De.close)==null?void 0:Rr.call(De);Ge instanceof Promise&&Ge.catch(()=>{})}j.delete(ze.id),oe.delete(ze.id),ze.streaming=!1,p(ze)}}else j.delete(ze.id),oe.delete(ze.id),ze.streaming=!1,p(ze)}else if(Ue==="flow_complete"){let U=(mt=A.result)==null?void 0:mt.response;if(M){if(f!==null){let R=f;j.delete(R.id),oe.delete(R.id),R.streaming!==!1&&(R.streaming=!1,p(R))}}else if(U!=null){let R=re(),ee=oe.get(R.id),te=ee!=null?ee:je(U);R.rawContent=te;let G=je(U),ze=j.get(R.id);if(ze){let Ke=wr(te);if(Ke!==null)G=Ke;else{let Ge=ze.processChunk(te);Ge instanceof Promise&&Ge.then(Yt=>{var Lt;let Tt=typeof Yt=="string"?Yt:(Lt=Yt==null?void 0:Yt.text)!=null?Lt:null;Tt!==null&&(R.content=Tt,R.streaming=!1,p(R))});let Qe=ze.getExtractedText();Qe!==null&&(G=Qe)}}j.delete(R.id),oe.delete(R.id);let De=G!==R.content,at=R.streaming!==!1;De&&(R.content=G),R.streaming=!1,(De||at)&&p(R)}else if(f!==null){let R=f;j.delete(R.id),oe.delete(R.id),R.streaming!==!1&&(R.streaming=!1,p(R))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")Q={executionId:A.executionId,agentId:(is=A.agentId)!=null?is:"virtual",agentName:(ro=A.agentName)!=null?ro:"",status:"running",currentIteration:0,maxTurns:(Rn=A.maxTurns)!=null?Rn:1,startedAt:ue(A.startedAt)};else if(Ue==="agent_iteration_start"){if(Q&&(Q.currentIteration=A.iteration),Ln==="separate"&&A.iteration>1){let U=f;U&&(U.streaming=!1,p(U),Fe.set(A.iteration-1,U),f=null)}}else if(Ue==="agent_turn_start")g=null;else if(Ue==="agent_turn_delta"){if(A.contentType==="text"){let U=re();U.content+=(aa=A.delta)!=null?aa:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:Q==null?void 0:Q.agentName},g=U,p(U)}else if(A.contentType==="thinking"){let U=(ia=A.turnId)!=null?ia:`agent-think-${A.iteration}`,R=we(U);R.reasoning=(Pr=R.reasoning)!=null?Pr:{id:U,status:"streaming",chunks:[]},R.reasoning.chunks.push((Bo=A.delta)!=null?Bo:""),R.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},p(R)}else if(A.contentType==="tool_input"){let U=(la=A.toolCallId)!=null?la:v.lastId;if(U){let R=L.get(U);R!=null&&R.toolCall&&(R.toolCall.chunks=(lr=R.toolCall.chunks)!=null?lr:[],R.toolCall.chunks.push((ls=A.delta)!=null?ls:""),p(R))}}}else if(Ue==="agent_turn_complete"){let U=A.turnId;if(U){let te=W.get(U);if(te!=null&&te.reasoning){te.reasoning.status="complete",te.reasoning.completedAt=ue(A.completedAt);let G=(Ho=te.reasoning.startedAt)!=null?Ho:Date.now();te.reasoning.durationMs=Math.max(0,((cs=te.reasoning.completedAt)!=null?cs:Date.now())-G),te.streaming=!1,p(te)}}let R=A.stopReason,ee=f!=null?f:g;if(R&&ee!==null){let te=A.turnId;(!te||((Go=ee.agentMetadata)==null?void 0:Go.turnId)===te)&&(ee.stopReason=R,p(ee))}}else if(Ue==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let U=(Yo=A.toolCallId)!=null?Yo:`agent-tool-${l()}`;We($(A),U);let R=le(U),ee=(ca=R.toolCall)!=null?ca:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};ee.name=(Vi=(da=A.toolName)!=null?da:A.name)!=null?Vi:ee.name,ee.status="running",A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=ue((cr=A.startedAt)!=null?cr:A.timestamp),R.toolCall=ee,R.streaming=!0,R.agentMetadata={executionId:A.executionId,iteration:A.iteration},p(R)}else if(Ue==="agent_tool_delta"){let U=(Xo=A.toolCallId)!=null?Xo:v.lastId;if(U){let R=(pa=L.get(U))!=null?pa:le(U);R.toolCall&&(R.toolCall.chunks=(ds=R.toolCall.chunks)!=null?ds:[],R.toolCall.chunks.push((Qo=A.delta)!=null?Qo:""),R.toolCall.status="running",R.streaming=!0,p(R))}}else if(Ue==="agent_tool_complete"){let U=(ua=A.toolCallId)!=null?ua:v.lastId;if(U){let R=(ps=L.get(U))!=null?ps:le(U);if(R.toolCall){R.toolCall.status="complete",A.result!==void 0&&(R.toolCall.result=A.result),typeof A.executionTime=="number"&&(R.toolCall.durationMs=A.executionTime),R.toolCall.completedAt=ue((Jo=A.completedAt)!=null?Jo:A.timestamp),R.streaming=!1,p(R);let ee=$(A);ee&&v.byCall.delete(ee)}}}else if(Ue==="agent_media"){let U=Array.isArray(A.media)?A.media:[],R=[];for(let ee of U){if(!ee||typeof ee!="object")continue;let te=ee,G=typeof te.type=="string"?te.type:void 0,ze=typeof te.mediaType=="string"?te.mediaType.toLowerCase():"",De=null,at="";if(G==="media"){let Ke=typeof te.data=="string"?te.data:void 0;if(!Ke)continue;at=ze.length>0?ze:"application/octet-stream",De=`data:${at};base64,${Ke}`}else if(G==="image-url"){let Ke=typeof te.url=="string"?te.url:void 0;if(!Ke)continue;at=ze,De=Ke}else if(G==="file-url"){let Ke=typeof te.url=="string"?te.url:void 0;if(!Ke)continue;at=ze,De=Ke}else continue;if(De)if(G==="image-url"||at.startsWith("image/"))R.push({type:"image",image:De,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))R.push({type:"audio",audio:De,mimeType:at});else if(at.startsWith("video/"))R.push({type:"video",video:De,mimeType:at});else{let Ke=at||"application/octet-stream";R.push({type:"file",data:De,mimeType:Ke,filename:Kf(Ke)})}}if(R.length>0){let ee=l(),te=A.toolCallId,ze={id:`agent-media-${typeof te=="string"&&te.length>0?`${te}-${ee}`:String(ee)}`,role:"assistant",content:"",contentParts:R,createdAt:new Date().toISOString(),streaming:!1,sequence:ee,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(ze);let De=f;De&&(De.streaming=!1,p(De)),f=null,x.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,R={id:U,role:"assistant",content:(us=A.reflection)!=null?us:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(ma=A.reflection)!=null?ma:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(R)}else if(Ue==="agent_complete"){Q&&(Q.status=A.success?"complete":"error",Q.completedAt=ue(A.completedAt),Q.stopReason=A.stopReason);let U=f;U&&(U.streaming=!1,p(U)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let U=typeof A.error=="string"?A.error:(ga=(Do=A.error)==null?void 0:Do.message)!=null?ga:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let U=(Zo=A.approvalId)!=null?Zo:`approval-${l()}`,R={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Bt=Q==null?void 0:Q.agentId)!=null?Bt:"virtual",executionId:(Br=(Wr=A.executionId)!=null?Wr:Q==null?void 0:Q.executionId)!=null?Br:"",toolName:(ms=A.toolName)!=null?ms:"",toolType:A.toolType,description:(fa=A.description)!=null?fa:`Execute ${(Ao=A.toolName)!=null?Ao:"tool"}`,parameters:A.parameters}};p(R)}else if(Ue==="step_await"&&A.awaitReason==="approval_required"){let U=(gs=A.approvalId)!=null?gs:`approval-${l()}`,R={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(fs=Q==null?void 0:Q.agentId)!=null?fs:"virtual",executionId:(Hr=(ha=A.executionId)!=null?ha:Q==null?void 0:Q.executionId)!=null?Hr:"",toolName:(Dr=A.toolName)!=null?Dr:"",toolType:A.toolType,description:(ba=A.description)!=null?ba:`Execute ${(dr=A.toolName)!=null?dr:"tool"}`,parameters:A.parameters}};p(R)}else if(Ue==="agent_approval_complete"){let U=A.approvalId;if(U){let ee={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ya=A.decision)!=null?ya:"approved",agentId:(hs=Q==null?void 0:Q.agentId)!=null?hs:"virtual",executionId:(ys=(bs=A.executionId)!=null?bs:Q==null?void 0:Q.executionId)!=null?ys:"",toolName:(vs=A.toolName)!=null?vs:"",description:(Sn=A.description)!=null?Sn:"",resolvedAt:Date.now()}};p(ee)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let U=A.artifactType,R=String(A.id),ee=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:R,artifactType:U,title:ee,component:typeof A.component=="string"?A.component:void 0}),X.set(R,{markdown:"",title:ee}),!Ee.has(R)){Ee.add(R);let te={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:R,title:ee,artifactType:U,status:"streaming"}})};Z.set(R,te),p(te)}}else if(Ue==="artifact_delta"){let U=String(A.id),R=typeof A.delta=="string"?A.delta:String((Gn=A.delta)!=null?Gn:"");n({type:"artifact_delta",id:U,artDelta:R});let ee=X.get(U);ee&&(ee.markdown+=R)}else if(Ue==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(Ue==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let R=Z.get(U);if(R){R.streaming=!1;try{let ee=JSON.parse((Fo=R.rawContent)!=null?Fo:"{}");if(ee.props){ee.props.status="complete";let te=X.get(U);te!=null&&te.markdown&&(ee.props.markdown=te.markdown)}R.rawContent=JSON.stringify(ee)}catch{}X.delete(U),p(R),Z.delete(U)}}}else if(Ue==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let R=String((rt=U.id)!=null?rt:`msg-${l()}`),ee=U.role,G={id:R,role:ee==="user"?"user":ee==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(p(G),G.rawContent)try{let ze=JSON.parse(G.rawContent),De=(xs=ze==null?void 0:ze.props)==null?void 0:xs.artifactId;typeof De=="string"&&Ee.add(De)}catch{}f=null,x.current=null,j.delete(R),oe.delete(R)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(Ue==="dispatch_error"){let R=(pr=A.message)!=null?pr:A.error;R!=null&&R!==""&&(U=new Error(String(R)))}else if(Ue==="step_error"||Ue==="flow_error"){let R=A.error;typeof R=="string"&&R!==""?U=new Error(R):R!=null&&typeof R=="object"&&"message"in R&&(U=new Error(String((bo=R.message)!=null?bo:R)))}else Ue==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let R=f;R&&R.streaming&&(R.streaming=!1,p(R)),n({type:"status",status:"idle"})}}}}}Le.length=0};;){let{done:N,value:se}=await r.read();if(N)break;a+=s.decode(se,{stream:!0});let He=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()=>{}}},Cr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ku=()=>{var t;let e=qf();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)}},Eu=()=>{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=_f(n,Vf|$f);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mu=()=>{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 Ka=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var 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 jf="https://api.runtype.com/v1/dispatch",Ga="https://api.runtype.com";function Kf(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 il=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 Gf(e){switch(e){case"json":return Eu;case"regex-json":return ku;case"xml":return Mu;default:return Tu}}var Lu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Yf(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=Lu(n);if(!Lu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Cr(e);return Cr(t)!==null&&a===null?t:e}var Ps=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:jf,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Gf(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 Ua(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$/,""))||Ga}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let 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$/,""))||Ga}/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 D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(il).map(D=>{var B,v,x;return{id:D.id,role:D.role,content:(x=(v=(B=D.contentParts)!=null?B:D.llmContent)!=null?v:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,u=!!(f&&f.length>0),w=u?wu(f):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,M=u&&C&&this.lastSentClientToolsFingerprint===w,I=!1,R=null,H;for(let D=0;;D++){let v={...m,...u&&(I||!M)&&f?{clientTools:f}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),H=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),H.status===409&&D===0&&u){let x=await H.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=x!=null?x:{error:"Chat request failed"}}break}if(!H.ok){let D=R!=null?R:await H.json().catch(()=>({error:"Chat request failed"}));if(H.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(H.status===429){let v=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let B=new Error(D.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!H.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(H.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$/,""))||Ga}/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,p;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ga}/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:(p=o==null?void 0:o.streamResponse)!=null?p:!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(il).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(il).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=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return o.current=m,r(m),m},l=p=>o.current?o.current:d(p);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 p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,r(p)}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 ln,Dn,Jn,ze;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,He=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,De=_.tools?_.tools.map(Ve=>({...Ve,chunks:Ve.chunks?[...Ve.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:He,tools:De}},m=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,He=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||He||!!_.stopReason},f=_=>{m(_)&&n({type:"message",message:p(_)})},u=null,w=null,C={current:null},M={current:null},I=!1,R=new Map,H=new Map,D=new Map,B=new Map,v={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(_,ke,He="")=>`${_}::${ke}::${He}`,S=(_,ke)=>`${_}::${ke}::`,E=(_,ke,He,De)=>{let Ve=k(_,ke,He),dt=D.get(Ve);if(dt)return dt;let ot=He?`-${He}`:"",At={id:`nested-${_}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:De,parentToolId:_,parentStepId:ke}};return D.set(Ve,At),f(At),At},F=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var ke,He,De,Ve,dt;return F((dt=(Ve=(De=(He=(ke=_.stepId)!=null?ke:_.step_id)!=null?He:_.step)!=null?De:_.parentId)!=null?Ve:_.flowStepId)!=null?dt:_.flow_step_id)},j=_=>{var ke,He,De,Ve,dt,ot,At;return F((At=(ot=(dt=(Ve=(De=(He=(ke=_.callId)!=null?ke:_.call_id)!=null?He:_.requestId)!=null?De:_.request_id)!=null?Ve:_.toolCallId)!=null?dt:_.tool_call_id)!=null?ot:_.stepId)!=null?At:_.step_id)},me=o,se=!1,ge=()=>{if(u)return u;let _;return!se&&me?(_=me,se=!0):me&&M.current?_=`${me}_${M.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(u),u},ie=(_,ke)=>{v.lastId=ke,_&&v.byStep.set(_,ke)},be=(_,ke)=>{var dt;let He=(dt=_.reasoningId)!=null?dt:_.id,De=$(_);if(He){let ot=String(He);return ie(De,ot),ot}if(De){let ot=v.byStep.get(De);if(ot)return v.lastId=ot,ot}if(v.lastId&&!ke)return v.lastId;if(!ke)return null;let Ve=`reason-${l()}`;return ie(De,Ve),Ve},Fe=_=>{let ke=R.get(_);if(ke)return ke;let He={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return R.set(_,He),f(He),He},ve=(_,ke)=>{x.lastId=ke,_&&x.byCall.set(_,ke)},J=new Set,Le=new Map,Y=new Set,xe=new Map,Se=_=>{if(!_)return!1;let ke=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},de=(_,ke)=>{var dt;let He=(dt=_.toolId)!=null?dt:_.id,De=j(_);if(He){let ot=String(He);return ve(De,ot),ot}if(De){let ot=x.byCall.get(De);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ke)return x.lastId;if(!ke)return null;let Ve=`tool-${l()}`;return ve(De,Ve),Ve},we=_=>{let ke=H.get(_);if(ke)return ke;let He={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return H.set(_,He),f(He),He},Ue=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let He=Date.parse(_);if(!Number.isNaN(He))return He}return Date.now()},te=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},ne=new Map,re=new Map,nt=new Map,ye=new Map,le=null,$e=(_,ke,He)=>{var At;let De=nt.get(_);De||(De=[],nt.set(_,De));let Ve=0,dt=De.length;for(;Ve<dt;){let Vt=Ve+dt>>>1;De[Vt].seq<ke?Ve=Vt+1:dt=Vt}((At=De[Ve])==null?void 0:At.seq)===ke?De[Ve]={seq:ke,text:He}:De.splice(Ve,0,{seq:ke,text:He});let ot="";for(let Vt=0;Vt<De.length;Vt++)ot+=De[Vt].text;return ot},Be=(_,ke)=>{let He=te(ke),De=re.get(_.id),Ve=Yf(De,He);_.rawContent=Ve;let dt=ne.get(_.id),ot=Qe=>{var oe;let Ft=(oe=_.content)!=null?oe:"";Qe.trim()!==""&&(Ft.trim().length===0||Qe.startsWith(Ft)||Qe.trimStart().startsWith(Ft.trim()))&&(_.content=Qe)},At=()=>{var Qe;if(dt){let Ft=(Qe=dt.close)==null?void 0:Qe.call(dt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(_.id),re.delete(_.id),_.streaming=!1,f(_)};if(!dt){ot(He),At();return}let Vt=Cr(Ve);if(Vt!==null&&Vt.trim()!==""){ot(Vt),At();return}let q=Qe=>{var fe;let Ft=typeof Qe=="string"?Qe:(fe=Qe==null?void 0:Qe.text)!=null?fe:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let oe=dt.getExtractedText();return oe!==null&&oe.trim()!==""?oe:He},_t;try{_t=dt.processChunk(Ve)}catch{ot(He),At();return}if(_t instanceof Promise){_t.then(Qe=>{ot(q(Qe)),At()}).catch(()=>{ot(He),At()});return}ot(q(_t)),At()},ce=[],K=!1,_e,Et=()=>{K||(K=!0,queueMicrotask(()=>{K=!1,_e()}))},pe=new Ka((_,ke)=>{ce.push({payloadType:_,payload:ke}),Et()}),ae=null,Ln=new Map,Nt=(ln=this.config.iterationDisplay)!=null?ln:"separate";for(_e=()=>{var _,ke,He,De,Ve,dt,ot,At,Vt,q,_t,Qe,Ft,oe,fe,xt,$t,Jt,yn,Tt,wt,ft,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn,T,Kn,mo,Po,So,ss,go,fo,ho,Wo,lr,ra,as,sa,Pr,mt,is,ro,Rn,aa,ia,Wr,Bo,la,cr,ls,Ho,cs,Go,Yo,ca,da,$i,dr,Xo,pa,ds,Qo,ua,ps,Jo,us,ma,Do,ga,Zo,Bt,Br,Hr,ms,Ao,fa,gs,fs,ha,Dr,Fr,pr,ba,ya,hs,bs,ys,vs,Cn,Gn,Fo,rt,xs,ur,bo,va;for(let er=0;er<ce.length;er++){let je=ce[er].payloadType,A=ce[er].payload;if(je==="reason_start"){let U=(_=be(A,!0))!=null?_:`reason-${l()}`,W=Fe(U);W.reasoning=(ke=W.reasoning)!=null?ke:{id:U,status:"streaming",chunks:[]},W.reasoning.startedAt=(De=W.reasoning.startedAt)!=null?De:Ue((He=A.startedAt)!=null?He:A.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",f(W)}else if(je==="reason_delta"||je==="reason_chunk"){let U=(dt=(Ve=be(A,!1))!=null?Ve:be(A,!0))!=null?dt:`reason-${l()}`,W=Fe(U);W.reasoning=(ot=W.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},W.reasoning.startedAt=(Vt=W.reasoning.startedAt)!=null?Vt:Ue((At=A.startedAt)!=null?At:A.timestamp);let Z=(Qe=(_t=(q=A.reasoningText)!=null?q:A.text)!=null?_t:A.delta)!=null?Qe:"";if(Z&&A.hidden!==!0){let G=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(G!==void 0){let X=$e(U,G,String(Z));W.reasoning.chunks=[X]}else W.reasoning.chunks.push(String(Z))}if(W.reasoning.status=A.done?"complete":"streaming",A.done){W.reasoning.completedAt=Ue((Ft=A.completedAt)!=null?Ft:A.timestamp);let G=(oe=W.reasoning.startedAt)!=null?oe:Date.now();W.reasoning.durationMs=Math.max(0,((fe=W.reasoning.completedAt)!=null?fe:Date.now())-G)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(je==="reason_complete"){let U=($t=(xt=be(A,!1))!=null?xt:be(A,!0))!=null?$t:`reason-${l()}`,W=R.get(U);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Ue((Jt=A.completedAt)!=null?Jt:A.timestamp);let G=(yn=W.reasoning.startedAt)!=null?yn:Date.now();W.reasoning.durationMs=Math.max(0,((Tt=W.reasoning.completedAt)!=null?Tt:Date.now())-G),W.streaming=!1,f(W)}let Z=$(A);Z&&v.byStep.delete(Z)}else if(je==="tool_start"){let U=(wt=de(A,!0))!=null?wt:`tool-${l()}`,W=(ft=A.toolName)!=null?ft:A.name;if(Se(W)){J.add(U);continue}let Z=we(U),G=(bt=Z.toolCall)!=null?bt:{id:U,status:"pending"};G.name=W!=null?W:G.name,G.status="running",A.args!==void 0?G.args=A.args:A.parameters!==void 0&&(G.args=A.parameters),G.startedAt=(et=G.startedAt)!=null?et:Ue((zt=A.startedAt)!=null?zt:A.timestamp),G.completedAt=void 0,G.durationMs=void 0,Z.toolCall=G,Z.streaming=!0;let X=A.agentContext;(X||A.executionId)&&(Z.agentMetadata={executionId:(Fn=X==null?void 0:X.executionId)!=null?Fn:A.executionId,iteration:(Zn=X==null?void 0:X.iteration)!=null?Zn:A.iteration}),f(Z)}else if(je==="tool_chunk"||je==="tool_delta"){let U=(On=(vn=de(A,!1))!=null?vn:de(A,!0))!=null?On:`tool-${l()}`;if(J.has(U))continue;let W=we(U),Z=(ut=W.toolCall)!=null?ut:{id:U,status:"running"};Z.startedAt=(Nn=Z.startedAt)!=null?Nn:Ue((wo=A.startedAt)!=null?wo:A.timestamp);let G=(Rr=(In=(ir=A.text)!=null?ir:A.delta)!=null?In:A.message)!=null?Rr:"";G&&(Z.chunks=($o=Z.chunks)!=null?$o:[],Z.chunks.push(String(G))),Z.status="running",W.toolCall=Z,W.streaming=!0;let X=A.agentContext;(X||A.executionId)&&(W.agentMetadata=(_n=W.agentMetadata)!=null?_n:{executionId:(Lo=X==null?void 0:X.executionId)!=null?Lo:A.executionId,iteration:(yt=X==null?void 0:X.iteration)!=null?yt:A.iteration}),f(W)}else if(je==="tool_complete"){let U=(xn=(Vn=de(A,!1))!=null?Vn:de(A,!0))!=null?xn:`tool-${l()}`;if(J.has(U)){J.delete(U);continue}let W=we(U),Z=(It=W.toolCall)!=null?It:{id:U,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=Ue((eo=A.completedAt)!=null?eo:A.timestamp);let G=(to=A.duration)!=null?to:A.executionTime;if(typeof G=="number")Z.durationMs=G;else{let Ne=($n=Z.startedAt)!=null?$n:Date.now();Z.durationMs=Math.max(0,((Uo=Z.completedAt)!=null?Uo:Date.now())-Ne)}W.toolCall=Z,W.streaming=!1;let X=A.agentContext;(X||A.executionId)&&(W.agentMetadata=(Un=W.agentMetadata)!=null?Un:{executionId:(Io=X==null?void 0:X.executionId)!=null?Io:A.executionId,iteration:(zo=X==null?void 0:X.iteration)!=null?zo:A.iteration}),f(W);let Xe=j(A);Xe&&x.byCall.delete(Xe)}else if(je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,W=(Wt=U!=null?U:A.toolId)!=null?Wt:`local-${l()}`,Z=we(W),G=(wn=Z.toolCall)!=null?wn:{id:W,status:"pending"};G.name=A.toolName,G.args=A.parameters,G.status="complete",G.chunks=(no=G.chunks)!=null?no:[],G.startedAt=(Ro=G.startedAt)!=null?Ro:Ue((qo=A.startedAt)!=null?qo:A.timestamp),G.completedAt=(jo=G.completedAt)!=null?jo:G.startedAt,Z.toolCall=G,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(zn=A.executionId)!=null?zn:(Co=Z.agentMetadata)==null?void 0:Co.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(Z)}else if(je==="text_start"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=A.partId;if(U!==void 0&&M.current!==null&&U!==M.current){let W=u;W&&(W.streaming=!1,f(W),le=W,u=null,I=!0)}U!==void 0&&(M.current=U)}else if(je==="text_end"){if((gt=A.toolContext)!=null&&gt.toolId)continue;let U=u;U&&(U.streaming=!1,f(U),le=U,u=null,I=!0)}else if(je==="step_chunk"||je==="step_delta"){let U=A.stepType,W=A.executionType;if(U==="tool"||W==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Gt=(Kt=A.id)!=null?Kt:Z.stepId)!=null?Gt:`step-${l()}`),Ze=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ie=`${Z.toolId}::${Ne}`,Ge=B.get(Ie);if(Ze!==""&&Ge!==void 0&&Ge!==""&&Ge!==Ze){let Ct=D.get(k(Z.toolId,Ne,Ge));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,f(Ct))}Ze!==""&&B.set(Ie,Ze);let Rt=E(Z.toolId,Ne,Ze,Z.executionId),nn=(uo=(oo=(Ko=(qn=A.text)!=null?qn:A.delta)!=null?Ko:A.content)!=null?oo:A.chunk)!=null?uo:"";nn&&(Rt.content+=String(nn),Rt.streaming=!0,f(Rt)),A.isComplete&&(Rt.streaming=!1,f(Rt));continue}let G=A.partId;if(G!==void 0&&M.current!==null&&G!==M.current){let Ne=u;Ne&&(Ne.streaming=!1,f(Ne),le=Ne,u=null,I=!0)}G!==void 0&&(M.current=G);let X=G!==void 0&&(jn=ye.get(G))!=null?jn:ge();G!==void 0&&(X.partId||(X.partId=G),ye.set(G,X));let Xe=(Po=(mo=(Kn=(T=A.text)!=null?T:A.delta)!=null?Kn:A.content)!=null?mo:A.chunk)!=null?Po:"";if(Xe){let Ne=typeof A.seq=="number"?A.seq:void 0,Ze=G!=null?G:X.id,Ie=Ne!==void 0?$e(Ze,Ne,String(Xe)):((So=re.get(X.id))!=null?So:"")+Xe;X.rawContent=Ie,ne.has(X.id)||ne.set(X.id,this.createStreamParser());let Ge=ne.get(X.id),Rt=Ie.trim().startsWith("{")||Ie.trim().startsWith("[");if(Rt&&re.set(X.id,Ie),Ge.__isPlainTextParser===!0){X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X);continue}let Ct=Ge.processChunk(Ie);if(Ct instanceof Promise)Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null&&on.trim()!=="")X.content=on,f(X);else if(!Rt&&!Ie.trim().startsWith("<")){let Sn=u,Yt=Sn&&Sn.id===X.id?Sn:X;Yt.id===X.id&&(Yt.content=Ne!==void 0?Ie:Yt.content+Xe,re.delete(Yt.id),ne.delete(Yt.id),Yt.rawContent=void 0,f(Yt))}}).catch(()=>{X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X)});else{let Mt=typeof Ct=="string"?Ct:(ss=Ct==null?void 0:Ct.text)!=null?ss:null;Mt!==null&&Mt.trim()!==""?(X.content=Mt,f(X)):!Rt&&!Ie.trim().startsWith("<")&&(X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X))}}if(A.isComplete){let Ne=(fo=(go=A.result)==null?void 0:go.response)!=null?fo:X.content;if(Ne){let Ze=re.get(X.id),Ie=Ze!=null?Ze:te(Ne);X.rawContent=Ie;let Ge=ne.get(X.id),Rt=null,nn=!1;if(Ge&&(Rt=Ge.getExtractedText(),Rt===null&&(Rt=Cr(Ie)),Rt===null)){let Ct=Ge.processChunk(Ie);Ct instanceof Promise?(nn=!0,Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null){let Sn=u;Sn&&Sn.id===X.id&&(Sn.content=on,Sn.streaming=!1,ne.delete(Sn.id),re.delete(Sn.id),f(Sn))}})):Rt=typeof Ct=="string"?Ct:(ho=Ct==null?void 0:Ct.text)!=null?ho:null}if(!nn){Rt!==null&&Rt.trim()!==""?X.content=Rt:re.has(X.id)||(X.content=te(Ne));let Ct=ne.get(X.id);if(Ct){let Mt=(Wo=Ct.close)==null?void 0:Wo.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),ne.delete(X.id)}re.delete(X.id),X.streaming=!1,f(X)}}}}else if(je==="step_complete"){let U=A.stepType,W=A.executionType;if(U==="tool"||W==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((ra=(lr=A.id)!=null?lr:Z.stepId)!=null?ra:"");if(Ne){let Ze=S(Z.toolId,Ne);for(let[Ie,Ge]of D)Ie.startsWith(Ze)&&Ge.streaming!==!1&&(Ge.streaming=!1,f(Ge));B.delete(`${Z.toolId}::${Ne}`)}continue}let G=A.stopReason;if(I){if(u!==null){let Ie=u;G&&(Ie.stopReason=G),ne.delete(Ie.id),re.delete(Ie.id),Ie.streaming!==!1&&(Ie.streaming=!1,f(Ie))}let Ne=(as=A.result)==null?void 0:as.response,Ze=le;Ze&&(G&&(Ze.stopReason=G),Ne!=null?Be(Ze,Ne):(ne.delete(Ze.id),re.delete(Ze.id))),le=null;continue}let X=(sa=A.result)==null?void 0:sa.response,Xe=ge();if(G&&(Xe.stopReason=G),X!=null){let Ne=ne.get(Xe.id),Ze=!1,Ie=!1;if(Ne){let Ge=Ne.getExtractedText(),Rt=re.get(Xe.id),nn=Rt!=null?Rt:te(X);if(Xe.rawContent=nn,Ge!==null&&Ge.trim()!=="")Xe.content=Ge,Ze=!0;else{let Ct=Cr(nn);if(Ct!==null)Xe.content=Ct,Ze=!0;else{let Mt=Ne.processChunk(nn);if(Mt instanceof Promise)Ie=!0,Mt.then(on=>{var Sn;let un=typeof on=="string"?on:(Sn=on==null?void 0:on.text)!=null?Sn:null;if(un!==null&&un.trim()!==""){let Yt=u;Yt&&Yt.id===Xe.id&&(Yt.content=un,Yt.streaming=!1,ne.delete(Yt.id),re.delete(Yt.id),f(Yt))}else{let Yt=Ne.getExtractedText(),so=u;so&&so.id===Xe.id&&(Yt!==null&&Yt.trim()!==""?so.content=Yt:re.has(so.id)||(so.content=te(X)),so.streaming=!1,ne.delete(so.id),re.delete(so.id),f(so))}});else{let on=typeof Mt=="string"?Mt:(Pr=Mt==null?void 0:Mt.text)!=null?Pr:null;if(on!==null&&on.trim()!=="")Xe.content=on,Ze=!0;else{let un=Ne.getExtractedText();un!==null&&un.trim()!==""&&(Xe.content=un,Ze=!0)}}}}}if(!Ie){if(!Xe.rawContent){let Ge=re.get(Xe.id);Xe.rawContent=Ge!=null?Ge:te(X)}if(!Ze&&!re.has(Xe.id)&&(Xe.content=te(X)),Ne){let Ge=(mt=Ne.close)==null?void 0:mt.call(Ne);Ge instanceof Promise&&Ge.catch(()=>{})}ne.delete(Xe.id),re.delete(Xe.id),Xe.streaming=!1,f(Xe)}}else ne.delete(Xe.id),re.delete(Xe.id),Xe.streaming=!1,f(Xe)}else if(je==="flow_complete"){let U=(is=A.result)==null?void 0:is.response;if(I){if(u!==null){let W=u;ne.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}}else if(U!=null){let W=ge(),Z=re.get(W.id),G=Z!=null?Z:te(U);W.rawContent=G;let X=te(U),Xe=ne.get(W.id);if(Xe){let Ie=Cr(G);if(Ie!==null)X=Ie;else{let Ge=Xe.processChunk(G);Ge instanceof Promise&&Ge.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(W.content=Ct,W.streaming=!1,f(W))});let Rt=Xe.getExtractedText();Rt!==null&&(X=Rt)}}ne.delete(W.id),re.delete(W.id);let Ne=X!==W.content,Ze=W.streaming!==!1;Ne&&(W.content=X),W.streaming=!1,(Ne||Ze)&&f(W)}else if(u!==null){let W=u;ne.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}n({type:"status",status:"idle"})}else if(je==="agent_start")ae={executionId:A.executionId,agentId:(ro=A.agentId)!=null?ro:"virtual",agentName:(Rn=A.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(aa=A.maxTurns)!=null?aa:1,startedAt:Ue(A.startedAt)};else if(je==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Nt==="separate"&&A.iteration>1){let U=u;U&&(U.streaming=!1,f(U),Ln.set(A.iteration-1,U),u=null)}}else if(je==="agent_turn_start")w=null;else if(je==="agent_turn_delta"){if(A.contentType==="text"){let U=ge();U.content+=(ia=A.delta)!=null?ia:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},w=U,f(U)}else if(A.contentType==="thinking"){let U=(Wr=A.turnId)!=null?Wr:`agent-think-${A.iteration}`,W=Fe(U);W.reasoning=(Bo=W.reasoning)!=null?Bo:{id:U,status:"streaming",chunks:[]},W.reasoning.chunks.push((la=A.delta)!=null?la:""),W.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(W)}else if(A.contentType==="tool_input"){let U=(cr=A.toolCallId)!=null?cr:x.lastId;if(U){let W=H.get(U);W!=null&&W.toolCall&&(W.toolCall.chunks=(ls=W.toolCall.chunks)!=null?ls:[],W.toolCall.chunks.push((Ho=A.delta)!=null?Ho:""),f(W))}}}else if(je==="agent_turn_complete"){let U=A.turnId;if(U){let G=R.get(U);if(G!=null&&G.reasoning){G.reasoning.status="complete",G.reasoning.completedAt=Ue(A.completedAt);let X=(cs=G.reasoning.startedAt)!=null?cs:Date.now();G.reasoning.durationMs=Math.max(0,((Go=G.reasoning.completedAt)!=null?Go:Date.now())-X),G.streaming=!1,f(G)}}let W=A.stopReason,Z=u!=null?u:w;if(W&&Z!==null){let G=A.turnId;(!G||((Yo=Z.agentMetadata)==null?void 0:Yo.turnId)===G)&&(Z.stopReason=W,f(Z))}}else if(je==="agent_tool_start"){u&&(u.streaming=!1,f(u),u=null);let U=(ca=A.toolCallId)!=null?ca:`agent-tool-${l()}`;ve(j(A),U);let W=we(U),Z=(da=W.toolCall)!=null?da:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(dr=($i=A.toolName)!=null?$i:A.name)!=null?dr:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=Ue((Xo=A.startedAt)!=null?Xo:A.timestamp),W.toolCall=Z,W.streaming=!0,W.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(W)}else if(je==="agent_tool_delta"){let U=(pa=A.toolCallId)!=null?pa:x.lastId;if(U){let W=(ds=H.get(U))!=null?ds:we(U);W.toolCall&&(W.toolCall.chunks=(Qo=W.toolCall.chunks)!=null?Qo:[],W.toolCall.chunks.push((ua=A.delta)!=null?ua:""),W.toolCall.status="running",W.streaming=!0,f(W))}}else if(je==="agent_tool_complete"){let U=(ps=A.toolCallId)!=null?ps:x.lastId;if(U){let W=(Jo=H.get(U))!=null?Jo:we(U);if(W.toolCall){W.toolCall.status="complete",A.result!==void 0&&(W.toolCall.result=A.result),typeof A.executionTime=="number"&&(W.toolCall.durationMs=A.executionTime),W.toolCall.completedAt=Ue((us=A.completedAt)!=null?us:A.timestamp),W.streaming=!1,f(W);let Z=j(A);Z&&x.byCall.delete(Z)}}}else if(je==="agent_media"){let U=Array.isArray(A.media)?A.media:[],W=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let G=Z,X=typeof G.type=="string"?G.type:void 0,Xe=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",Ne=null,Ze="";if(X==="media"){let Ie=typeof G.data=="string"?G.data:void 0;if(!Ie)continue;Ze=Xe.length>0?Xe:"application/octet-stream",Ne=`data:${Ze};base64,${Ie}`}else if(X==="image-url"){let Ie=typeof G.url=="string"?G.url:void 0;if(!Ie)continue;Ze=Xe,Ne=Ie}else if(X==="file-url"){let Ie=typeof G.url=="string"?G.url:void 0;if(!Ie)continue;Ze=Xe,Ne=Ie}else continue;if(Ne)if(X==="image-url"||Ze.startsWith("image/"))W.push({type:"image",image:Ne,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))W.push({type:"audio",audio:Ne,mimeType:Ze});else if(Ze.startsWith("video/"))W.push({type:"video",video:Ne,mimeType:Ze});else{let Ie=Ze||"application/octet-stream";W.push({type:"file",data:Ne,mimeType:Ie,filename:Kf(Ie)})}}if(W.length>0){let Z=l(),G=A.toolCallId,Xe={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Xe);let Ne=u;Ne&&(Ne.streaming=!1,f(Ne)),u=null,C.current=null}}else if(je!=="agent_iteration_complete"){if(je==="agent_reflection"||je==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,W={id:U,role:"assistant",content:(ma=A.reflection)!=null?ma:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Do=A.reflection)!=null?Do:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(W)}else if(je==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=Ue(A.completedAt),ae.stopReason=A.stopReason);let U=u;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(je==="agent_error"){let U=typeof A.error=="string"?A.error:(Zo=(ga=A.error)==null?void 0:ga.message)!=null?Zo:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(je!=="agent_ping"){if(je==="agent_approval_start"){let U=(Bt=A.approvalId)!=null?Bt:`approval-${l()}`,W={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Br=ae==null?void 0:ae.agentId)!=null?Br:"virtual",executionId:(ms=(Hr=A.executionId)!=null?Hr:ae==null?void 0:ae.executionId)!=null?ms:"",toolName:(Ao=A.toolName)!=null?Ao:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(fa=A.toolName)!=null?fa:"tool"}`,parameters:A.parameters}};f(W)}else if(je==="step_await"&&A.awaitReason==="approval_required"){let U=(fs=A.approvalId)!=null?fs:`approval-${l()}`,W={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ha=ae==null?void 0:ae.agentId)!=null?ha:"virtual",executionId:(Fr=(Dr=A.executionId)!=null?Dr:ae==null?void 0:ae.executionId)!=null?Fr:"",toolName:(pr=A.toolName)!=null?pr:"",toolType:A.toolType,description:(ya=A.description)!=null?ya:`Execute ${(ba=A.toolName)!=null?ba:"tool"}`,parameters:A.parameters}};f(W)}else if(je==="agent_approval_complete"){let U=A.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(hs=A.decision)!=null?hs:"approved",agentId:(bs=ae==null?void 0:ae.agentId)!=null?bs:"virtual",executionId:(vs=(ys=A.executionId)!=null?ys:ae==null?void 0:ae.executionId)!=null?vs:"",toolName:(Cn=A.toolName)!=null?Cn:"",description:(Gn=A.description)!=null?Gn:"",resolvedAt:Date.now()}};f(Z)}}else if(je==="artifact_start"||je==="artifact_delta"||je==="artifact_update"||je==="artifact_complete"){if(je==="artifact_start"){let U=A.artifactType,W=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:W,artifactType:U,title:Z,component:typeof A.component=="string"?A.component:void 0}),xe.set(W,{markdown:"",title:Z}),!Y.has(W)){Y.add(W);let G={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Z,artifactType:U,status:"streaming"}})};Le.set(W,G),f(G)}}else if(je==="artifact_delta"){let U=String(A.id),W=typeof A.delta=="string"?A.delta:String((Fo=A.delta)!=null?Fo:"");n({type:"artifact_delta",id:U,artDelta:W});let Z=xe.get(U);Z&&(Z.markdown+=W)}else if(je==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(je==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let W=Le.get(U);if(W){W.streaming=!1;try{let Z=JSON.parse((rt=W.rawContent)!=null?rt:"{}");if(Z.props){Z.props.status="complete";let G=xe.get(U);G!=null&&G.markdown&&(Z.props.markdown=G.markdown)}W.rawContent=JSON.stringify(Z)}catch{}xe.delete(U),f(W),Le.delete(U)}}}else if(je==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let W=String((xs=U.id)!=null?xs:`msg-${l()}`),Z=U.role,X={id:W,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(X),X.rawContent)try{let Xe=JSON.parse(X.rawContent),Ne=(ur=Xe==null?void 0:Xe.props)==null?void 0:ur.artifactId;typeof Ne=="string"&&Y.add(Ne)}catch{}u=null,C.current=null,ne.delete(W),re.delete(W)}else if(je==="error"||je==="step_error"||je==="dispatch_error"||je==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(je==="dispatch_error"){let W=(bo=A.message)!=null?bo:A.error;W!=null&&W!==""&&(U=new Error(String(W)))}else if(je==="step_error"||je==="flow_error"){let W=A.error;typeof W=="string"&&W!==""?U=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&(U=new Error(String((va=W.message)!=null?va:W)))}else je==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let W=u;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:_,value:ke}=await r.read();if(_)break;a+=s.decode(ke,{stream:!0});let He=a.split(`
10
10
 
11
- `);a=(ln=He.pop())!=null?ln:"";for(let Xe of He){let Oe=Xe.split(`
12
- `),Ne="message",ot="";for(let jt of Oe)jt.startsWith("event:")?Ne=jt.replace("event:","").trim():jt.startsWith("data:")&&(ot+=jt.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(jt){n({type:"error",error:jt instanceof Error?jt:new Error("Failed to parse chat stream payload")});continue}let Nt=Ne!=="message"?Ne:(Dn=St.type)!=null?Dn:"message";if((Jn=this.onSSEEvent)==null||Jn.call(this,Nt,St),this.parseSSEEvent){x.current=f;let jt=await this.handleCustomSSEEvent(St,n,x,p,l,C);if(x.current&&x.current!==f&&(f=x.current),jt)continue}Ct.push(Nt,St),Y()}}Ct.flushPending(),Y(),Ct.destroy()}};function Ga(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ws(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ya="[Image]";function il(e){return{type:"text",text:e}}var Iu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Xf=["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=[...Iu,...Xf];function Qf(e){return Iu.includes(e)||e.startsWith("image/")}function Xa(e){return Qf(e.type)}async function Ru(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Xa(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 Pu(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 Jf(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wu(e,t){let n=Jf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Qa=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let 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 Ja=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 Bs=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 Ja;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=W=>{x||(x=!0,clearTimeout(M),g(new Error(W)))},M=setTimeout(()=>C("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",W=>{if(!W.wasClean&&!x){let L=W.code!==1006?` (code ${W.code})`:"";C("WebSocket connection failed"+L+"."+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 Qa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,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 Cr=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 Hs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(e.runtype);case"browser":if(!Cr.isSupported())throw new Error("Browser speech recognition not supported");return new Cr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Hs({type:"runtype",runtype:e.runtype});if(Cr.isSupported())return Hs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ll(e){try{return Bu(e),!0}catch{return!1}}function Hu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let 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}
11
+ `);a=(Dn=He.pop())!=null?Dn:"";for(let De of He){let Ve=De.split(`
12
+ `),dt="message",ot="";for(let q of Ve)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(ot+=q.replace("data:","").trim());if(!ot)continue;let At;try{At=JSON.parse(ot)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Vt=dt!=="message"?dt:(Jn=At.type)!=null?Jn:"message";if((ze=this.onSSEEvent)==null||ze.call(this,Vt,At),this.parseSSEEvent){C.current=u;let q=await this.handleCustomSSEEvent(At,n,C,f,l,M);if(C.current&&C.current!==u&&(u=C.current),q)continue}pe.push(Vt,At),_e()}}pe.flushPending(),_e(),pe.destroy()}};function Ya(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ws(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Xa="[Image]";function ll(e){return{type:"text",text:e}}var Iu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Xf=["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=[...Iu,...Xf];function Qf(e){return Iu.includes(e)||e.startsWith("image/")}function Qa(e){return Qf(e.type)}async function Ru(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Qa(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 Pu(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 Jf(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wu(e,t){let n=Jf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ja=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let 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 Za=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 p=0;p<a.length;p++)i+=a[p]*a[p];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 Bs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Za;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,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 p=`${s}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let w=!1,C=I=>{w||(w=!0,clearTimeout(M),u(new Error(I)))},M=setTimeout(()=>C("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!w){let R=I.code!==1006?` (code ${I.code})`:"";C("WebSocket connection failed"+R+"."+m)}},{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 Ja(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,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 p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(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 Sr=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 Hs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(e.runtype);case"browser":if(!Sr.isSupported())throw new Error("Browser speech recognition not supported");return new Sr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Hs({type:"runtype",runtype:e.runtype});if(Sr.isSupported())return Hs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function cl(e){try{return Bu(e),!0}catch{return!1}}function Hu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let 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 Za=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)&&rl(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 Ps(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 ll((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=Hs(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 M=(C=this.pendingVoiceAssistantMessageId)!=null?C:(x=[...this.messages].reverse().find(W=>W.role==="assistant"))==null?void 0:x.id;M&&this.ttsSpokenMessageIds.add(M)}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 Ps(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"?Ga():n==="assistant"?Ws():`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"?Ga():r==="assistant"?Ws():`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=Ga(),s=Ws(),a={id:r,role:"user",content:o||Ya,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 M=Hu(x,this.config.errorMessage);if(M){let W={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(W)}}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=Ws();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=Hu(l,this.config.errorMessage);if(p){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(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,M,W,L,H,D,B;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 E=typeof((M=w[0])==null?void 0:M.question)=="string"?w[0].question:"";E&&(a={[E]:n})}}this.markAskUserQuestionResolved(t,a),(W=this.abortController)==null||W.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.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,E])=>`${w}: ${Array.isArray(E)?E.join(", "):E}`).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,E)=>{let S=typeof(w==null?void 0:w.question)=="string"?w.question:"";if(!S)return;let k=v[S],F=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,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 w=await v.json().catch(()=>null);throw new Error((H=w==null?void 0:w.error)!=null?H:`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||(B=(D=this.callbacks).onError)==null||B.call(D,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 L,H,D,B,v,w,E;let p=(L=u.toolCall)==null?void 0:L.name,f=(H=u.toolCall)==null?void 0:H.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=(B=(D=u.agentMetadata)==null?void 0:D.webMcpToolCallId)!=null?B:p,M=this.client.executeWebMcpToolCall(p,(v=u.toolCall)==null?void 0:v.args,x.signal),W;if(!M)W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{W=await M}catch(S){return S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"))||(E=(w=this.callbacks).onError)==null||E.call(w,S instanceof Error?S:new Error(String(S))),this.webMcpInflightKeys.delete(g),null}return x.signal.aborted?(this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:C,output:W}}));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,M,W,L,H,D,B;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){(M=(C=this.callbacks).onError)==null||M.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=(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 w=(H=(L=t.agentMetadata)==null?void 0:L.webMcpToolCallId)!=null?H: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"))||(B=(D=this.callbacks).onError)==null||B.call(D,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&&rl(i)&&d&&l&&((x=n.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let M=`${d}:${l}`;(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))&&(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},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as Zf,ArrowDown as eh,ArrowUp as th,ArrowUpRight as nh,Bot as oh,ChevronDown as rh,ChevronUp as sh,ChevronRight as ah,ChevronLeft as ih,Check as lh,Clipboard as ch,ClipboardCopy as dh,Copy as ph,File as uh,FileCode as mh,FileSpreadsheet as gh,FileText as fh,ImagePlus as hh,Loader as bh,LoaderCircle as yh,Mic as vh,Paperclip as xh,RefreshCw as wh,Search as Ch,Send as Sh,ShieldAlert as Ah,ShieldCheck as Th,ShieldX as kh,Square as Eh,ThumbsDown as Mh,ThumbsUp as Lh,Upload as Ih,Volume2 as Rh,X as Ph,User as Wh,Mail as Bh,Phone as Hh,Calendar as Dh,Clock as Fh,Building as Oh,MapPin as Nh,Lock as _h,Key as Vh,CreditCard as $h,AtSign as Uh,Hash as zh,Globe as qh,Link as jh,CircleCheck as Kh,CircleX as Gh,TriangleAlert as Yh,Info as Xh,Ban as Qh,Shield as Jh,ArrowLeft as Zh,ArrowRight as eb,ExternalLink as tb,Ellipsis as nb,EllipsisVertical as ob,Menu as rb,House as sb,Plus as ab,Minus as ib,Pencil as lb,Trash as cb,Trash2 as db,Save as pb,Download as ub,Share as mb,Funnel as gb,Settings as fb,RotateCw as hb,Maximize as bb,Minimize as yb,ShoppingCart as vb,ShoppingBag as xb,Package as wb,Truck as Cb,Tag as Sb,Gift as Ab,Receipt as Tb,Wallet as kb,Store as Eb,DollarSign as Mb,Percent as Lb,Play as Ib,Pause as Rb,VolumeX as Pb,Camera as Wb,Image as Bb,Film as Hb,Headphones as Db,MessageCircle as Fb,MessageSquare as Ob,Bell as Nb,Heart as _b,Star as Vb,Eye as $b,EyeOff as Ub,Bookmark as zb,CalendarDays as qb,History as jb,Timer as Kb,Folder as Gb,FolderOpen as Yb,Files as Xb,Sparkles as Qb,Zap as Jb,Sun as Zb,Moon as ey,Flag as ty,Monitor as ny,Smartphone as oy}from"lucide";var ry={activity:Zf,"arrow-down":eh,"arrow-up":th,"arrow-up-right":nh,bot:oh,"chevron-down":rh,"chevron-up":sh,"chevron-right":ah,"chevron-left":ih,check:lh,clipboard:ch,"clipboard-copy":dh,copy:ph,file:uh,"file-code":mh,"file-spreadsheet":gh,"file-text":fh,"image-plus":hh,loader:bh,"loader-circle":yh,mic:vh,paperclip:xh,"refresh-cw":wh,search:Ch,send:Sh,"shield-alert":Ah,"shield-check":Th,"shield-x":kh,square:Eh,"thumbs-down":Mh,"thumbs-up":Lh,upload:Ih,"volume-2":Rh,x:Ph,user:Wh,mail:Bh,phone:Hh,calendar:Dh,clock:Fh,building:Oh,"map-pin":Nh,lock:_h,key:Vh,"credit-card":$h,"at-sign":Uh,hash:zh,globe:qh,link:jh,"circle-check":Kh,"circle-x":Gh,"triangle-alert":Yh,info:Xh,ban:Qh,shield:Jh,"arrow-left":Zh,"arrow-right":eb,"external-link":tb,ellipsis:nb,"ellipsis-vertical":ob,menu:rb,house:sb,plus:ab,minus:ib,pencil:lb,trash:cb,"trash-2":db,save:pb,download:ub,share:mb,funnel:gb,settings:fb,"rotate-cw":hb,maximize:bb,minimize:yb,"shopping-cart":vb,"shopping-bag":xb,package:wb,truck:Cb,tag:Sb,gift:Ab,receipt:Tb,wallet:kb,store:Eb,"dollar-sign":Mb,percent:Lb,play:Ib,pause:Rb,"volume-x":Pb,camera:Wb,image:Bb,film:Hb,headphones:Db,"message-circle":Fb,"message-square":Ob,bell:Nb,heart:_b,star:Vb,eye:$b,"eye-off":Ub,bookmark:zb,"calendar-days":qb,history:jb,timer:Kb,folder:Gb,"folder-open":Yb,files:Xb,sparkles:Qb,zap:Jb,sun:Zb,moon:ey,flag:ty,monitor:ny,smartphone:oy},Se=(e,t=24,n="currentColor",o=2)=>{let r=ry[e];return r?sy(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 sy(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 ei={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(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 Ds=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ei.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:ei.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:ei.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ei.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,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=Pu(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 Ru(l),f=Xa(l)?URL.createObjectURL(l):null,g={id:ay(),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=Xa(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=iy(t.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Wu(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=Se("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})}};import{Idiomorph as ly}from"idiomorph";var ti=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;ly.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 ni={index:-1,draft:""};function Du(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:{...ni}}}function Fu(e,t){var n,o,r,s,a,i,d,l,u,p,f,g,x,C,M,W,L,H,D,B,v,w,E,S,k,F,$,q,me,re,be,ie,we,We,ye,Z,Ee,X;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:"",(M=(C=e.toolCall)==null?void 0:C.name)!=null?M:"",(H=(L=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:L.length)!=null?H:0,(w=(v=(B=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?w:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:F.length)!=null?$:0,(be=(re=(me=(q=e.reasoning)==null?void 0:q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:re.length)!=null?be:0,(ye=(We=(we=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:we[e.reasoning.chunks.length-1])==null?void 0:We.slice(-32))!=null?ye:"",(Ee=(Z=e.contentParts)==null?void 0:Z.length)!=null?Ee:0,(X=e.stopReason)!=null?X:"",t].join("\0")}function Ou(){return new Map}function Nu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function _u(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Vu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function oi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Os(e,t){return Fs(e)-e.scrollTop<=t}function ri(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 si(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 hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},bn=1e5,nr=bn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},cy=["pre","code","a","script","style"],ai=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ns.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ns.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ns.buffer}},dy=[{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"}],Uu=new Map;for(let e of dy)Uu.set(e.name,e);var _s=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Uu.get(e))!=null?o:null},ii=(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},py=(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},uy=(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},cl=/\s/,my=(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},gy=(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(cl.test(s[i])){let l=i;for(;l<s.length&&cl.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&&!cl.test(s[u]);)l.appendChild(py(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}r.replaceChild(a,e)},fy=(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(uy(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Vs=(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:cy).map(g=>g.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)my(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},u=t==="char"?gy:fy;for(let g of i)u(g,n,l);return r.innerHTML},li=(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},$s=(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},$u=new WeakMap,hy=(e,t)=>{var s;if(!e.styles)return;let n=$u.get(t);if(n||(n=new Set,$u.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)},dl=new WeakMap,by=(e,t)=>{if(!e.onAttach)return;let n=dl.get(t);if(n||(n=new Map,dl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},zu=e=>{let t=dl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},pl=(e,t)=>{hy(e,t),by(e,t)};function ul(e,t=bn){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 Us=0,or=null;function ml(e=document){var n;if(Us++,Us===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;or={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,Us=Math.max(0,Us-1),Us===0&&or)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=or.originalOverflow,r.style.position=or.originalPosition,r.style.top=or.originalTop,r.style.width=or.originalWidth,s.scrollTo(0,or.scrollY),or=null}}}var ci={side:"right",width:"420px",animate:!0,reveal:"resize"},un=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},zs=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Mo=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:ci.side,width:(r=t==null?void 0:t.width)!=null?r:ci.width,animate:(s=t==null?void 0:t.animate)!=null?s:ci.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:ci.reveal}};var xo={"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 qs=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:o}var ei=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 p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&sl(p.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 p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var 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 Ps(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 cl((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=Hs(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 p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,f,u,w,C;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((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}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(C=this.pendingVoiceAssistantMessageId)!=null?C:(w=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:w.id;M&&this.ttsSpokenMessageIds.add(M)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(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,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((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:(p=t.browser)==null?void 0:p.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 Ps(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:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?Ya():n==="assistant"?Ws():`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},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:f,rawContent:u}=o,C={id:d!=null?d:r==="user"?Ya():r==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};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,p,m,f,u;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=Ya(),s=Ws(),a={id:r,role:"user",content:o||Xa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(w){let C=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!C){let M=Hu(w,this.config.errorMessage);if(M){let I={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(I)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(w instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,w):(u=(f=this.callbacks).onError)==null||u.call(f,new Error(String(w))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Ws();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 p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Hu(l,this.config.errorMessage);if(m){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var 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,p,m;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 u=null;if(f instanceof Response){if(!f.ok){let w=await f.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${f.status}`)}u=f.body}else f instanceof ReadableStream&&(u=f);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let u=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,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 p,m,f,u,w,C,M,I,R,H,D,B;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let r=(m=t.agentMetadata)==null?void 0:m.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(w=(u=this.callbacks).onError)==null||w.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(C=t.toolCall)==null?void 0:C.args,x=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(x.length===1){let k=typeof((M=x[0])==null?void 0:M.question)=="string"?x[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(I=this.abortController)==null||I.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(R=t.toolCall)==null?void 0:R.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(([x,k])=>`${x}: ${Array.isArray(k)?k.join(", "):k}`).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((x,k)=>{let S=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!S)return;let E=v[S],F=Array.isArray(E)?E.join(", "):typeof E=="string"?E:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,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 x=await v.json().catch(()=>null);throw new Error((H=x==null?void 0:x.error)!=null?H:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(B=(D=this.callbacks).onError)==null||B.call(D,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 p=>{var R,H,D,B,v,x,k;let m=(R=p.toolCall)==null?void 0:R.name,f=(H=p.toolCall)==null?void 0:H.id;if(!m||!f)return null;let u=`${t}:${f}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u))return null;this.webMcpInflightKeys.add(u),o.push(u),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let w=new AbortController;this.webMcpResolveControllers.add(w),r.push(w);let C=(B=(D=p.agentMetadata)==null?void 0:D.webMcpToolCallId)!=null?B:m,M=this.client.executeWebMcpToolCall(m,(v=p.toolCall)==null?void 0:v.args,w.signal),I;if(!M)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await M}catch(S){return S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"))||(k=(x=this.callbacks).onError)==null||k.call(x,S instanceof Error?S:new Error(String(S))),this.webMcpInflightKeys.delete(u),null}return w.signal.aborted?(this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:C,output:I}}));try{let p=a.filter(u=>u!==null);if(p.length===0)return;let m={};for(let u of p)m[u.resumeKey]=u.output;let f=await this.client.resumeFlow(t,m,{signal:s.signal});if(!f.ok){let u=await f.json().catch(()=>null);throw new Error((i=u==null?void 0:u.error)!=null?i:`Resume failed: ${f.status}`)}for(let u of p)this.webMcpResolvedKeys.add(u.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,m,f,u,w,C,M,I,R,H,D,B;let n=(p=t.agentMetadata)==null?void 0:p.executionId,o=(m=t.toolCall)==null?void 0:m.name,r=(f=t.toolCall)==null?void 0:f.id;if(!n){(w=(u=this.callbacks).onError)==null||w.call(u,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(x){(M=(C=this.callbacks).onError)==null||M.call(C,x instanceof Error?x:new Error(String(x)))}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=(I=t.toolCall)==null?void 0:I.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 x=(H=(R=t.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?H:o;await this.resumeWithToolOutput(n,x,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(v){v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"))||(B=(D=this.callbacks).onError)==null||B.call(D,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 p,m,f,u,w,C;if(s!==o)return r;let a={...r,...n};((p=r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&sl(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let M=`${d}:${l}`;(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))&&(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},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as Zf,ArrowDown as eh,ArrowUp as th,ArrowUpRight as nh,Bot as oh,ChevronDown as rh,ChevronUp as sh,ChevronRight as ah,ChevronLeft as ih,Check as lh,Clipboard as ch,ClipboardCopy as dh,Copy as ph,File as uh,FileCode as mh,FileSpreadsheet as gh,FileText as fh,ImagePlus as hh,Loader as bh,LoaderCircle as yh,Mic as vh,Paperclip as xh,RefreshCw as wh,Search as Ch,Send as Sh,ShieldAlert as Ah,ShieldCheck as Th,ShieldX as kh,Square as Eh,ThumbsDown as Mh,ThumbsUp as Lh,Upload as Ih,Volume2 as Rh,X as Ph,User as Wh,Mail as Bh,Phone as Hh,Calendar as Dh,Clock as Fh,Building as Oh,MapPin as Nh,Lock as _h,Key as Vh,CreditCard as $h,AtSign as Uh,Hash as zh,Globe as qh,Link as jh,CircleCheck as Kh,CircleX as Gh,TriangleAlert as Yh,Info as Xh,Ban as Qh,Shield as Jh,ArrowLeft as Zh,ArrowRight as eb,ExternalLink as tb,Ellipsis as nb,EllipsisVertical as ob,Menu as rb,House as sb,Plus as ab,Minus as ib,Pencil as lb,Trash as cb,Trash2 as db,Save as pb,Download as ub,Share as mb,Funnel as gb,Settings as fb,RotateCw as hb,Maximize as bb,Minimize as yb,ShoppingCart as vb,ShoppingBag as xb,Package as wb,Truck as Cb,Tag as Sb,Gift as Ab,Receipt as Tb,Wallet as kb,Store as Eb,DollarSign as Mb,Percent as Lb,Play as Ib,Pause as Rb,VolumeX as Pb,Camera as Wb,Image as Bb,Film as Hb,Headphones as Db,MessageCircle as Fb,MessageSquare as Ob,Bell as Nb,Heart as _b,Star as Vb,Eye as $b,EyeOff as Ub,Bookmark as zb,CalendarDays as qb,History as jb,Timer as Kb,Folder as Gb,FolderOpen as Yb,Files as Xb,Sparkles as Qb,Zap as Jb,Sun as Zb,Moon as ey,Flag as ty,Monitor as ny,Smartphone as oy}from"lucide";var ry={activity:Zf,"arrow-down":eh,"arrow-up":th,"arrow-up-right":nh,bot:oh,"chevron-down":rh,"chevron-up":sh,"chevron-right":ah,"chevron-left":ih,check:lh,clipboard:ch,"clipboard-copy":dh,copy:ph,file:uh,"file-code":mh,"file-spreadsheet":gh,"file-text":fh,"image-plus":hh,loader:bh,"loader-circle":yh,mic:vh,paperclip:xh,"refresh-cw":wh,search:Ch,send:Sh,"shield-alert":Ah,"shield-check":Th,"shield-x":kh,square:Eh,"thumbs-down":Mh,"thumbs-up":Lh,upload:Ih,"volume-2":Rh,x:Ph,user:Wh,mail:Bh,phone:Hh,calendar:Dh,clock:Fh,building:Oh,"map-pin":Nh,lock:_h,key:Vh,"credit-card":$h,"at-sign":Uh,hash:zh,globe:qh,link:jh,"circle-check":Kh,"circle-x":Gh,"triangle-alert":Yh,info:Xh,ban:Qh,shield:Jh,"arrow-left":Zh,"arrow-right":eb,"external-link":tb,ellipsis:nb,"ellipsis-vertical":ob,menu:rb,house:sb,plus:ab,minus:ib,pencil:lb,trash:cb,"trash-2":db,save:pb,download:ub,share:mb,funnel:gb,settings:fb,"rotate-cw":hb,maximize:bb,minimize:yb,"shopping-cart":vb,"shopping-bag":xb,package:wb,truck:Cb,tag:Sb,gift:Ab,receipt:Tb,wallet:kb,store:Eb,"dollar-sign":Mb,percent:Lb,play:Ib,pause:Rb,"volume-x":Pb,camera:Wb,image:Bb,film:Hb,headphones:Db,"message-circle":Fb,"message-square":Ob,bell:Nb,heart:_b,star:Vb,eye:$b,"eye-off":Ub,bookmark:zb,"calendar-days":qb,history:jb,timer:Kb,folder:Gb,"folder-open":Yb,files:Xb,sparkles:Qb,zap:Jb,sun:Zb,moon:ey,flag:ty,monitor:ny,smartphone:oy},Te=(e,t=24,n="currentColor",o=2)=>{let r=ry[e];return r?sy(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 sy(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,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),r.appendChild(d)}),r}var ti={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(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 Ds=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ti.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:ti.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:ti.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ti.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,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 p=Pu(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(r=p.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,m);continue}try{let m=await Ru(l),f=Qa(l)?URL.createObjectURL(l):null,u={id:ay(),file:l,previewUrl:f,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var 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=Qa(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=iy(t.file.type),d=Te(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Wu(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=Te("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})}};import{Idiomorph as ly}from"idiomorph";var ni=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;ly.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 oi={index:-1,draft:""};function Du(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:{...oi}}}function Fu(e,t){var n,o,r,s,a,i,d,l,p,m,f,u,w,C,M,I,R,H,D,B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve,J,Le,Y;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,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(f=(m=e.approval)==null?void 0:m.status)!=null?f:"",(w=(u=e.toolCall)==null?void 0:u.status)!=null?w:"",(M=(C=e.toolCall)==null?void 0:C.name)!=null?M:"",(H=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?H:0,(x=(v=(B=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?x:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(E=e.reasoning)==null?void 0:E.chunks)==null?void 0:F.length)!=null?$:0,(ge=(se=(me=(j=e.reasoning)==null?void 0:j.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:se.length)!=null?ge:0,(ve=(Fe=(be=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Fe.slice(-32))!=null?ve:"",(Le=(J=e.contentParts)==null?void 0:J.length)!=null?Le:0,(Y=e.stopReason)!=null?Y:"",t].join("\0")}function Ou(){return new Map}function Nu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function _u(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Vu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ri(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Os(e,t){return Fs(e)-e.scrollTop<=t}function si(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,p=n-o;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function ai(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 fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,or=hn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},cy=["pre","code","a","script","style"],ii=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ns.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ns.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ns.buffer}},dy=[{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"}],Uu=new Map;for(let e of dy)Uu.set(e.name,e);var _s=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Uu.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},py=(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},uy=(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},dl=/\s/,my=(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},gy=(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(dl.test(s[i])){let l=i;for(;l<s.length&&dl.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 p=i;for(;p<s.length&&!dl.test(s[p]);)l.appendChild(py(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}r.replaceChild(a,e)},fy=(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(uy(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Vs=(e,t,n,o)=>{var m,f;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((m=o==null?void 0:o.skipTags)!=null?m:cy).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)my(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},p=t==="char"?gy:fy;for(let u of i)p(u,n,l);return r.innerHTML},ci=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},$s=(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},$u=new WeakMap,hy=(e,t)=>{var s;if(!e.styles)return;let n=$u.get(t);if(n||(n=new Set,$u.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)},pl=new WeakMap,by=(e,t)=>{if(!e.onAttach)return;let n=pl.get(t);if(n||(n=new Map,pl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},zu=e=>{let t=pl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ul=(e,t)=>{hy(e,t),by(e,t)};function ml(e,t=hn){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 Us=0,rr=null;function gl(e=document){var n;if(Us++,Us===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;rr={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,Us=Math.max(0,Us-1),Us===0&&rr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=rr.originalOverflow,r.style.position=rr.originalPosition,r.style.top=rr.originalTop,r.style.width=rr.originalWidth,s.scrollTo(0,rr.scrollY),rr=null}}}var di={side:"right",width:"420px",animate:!0,reveal:"resize"},pn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},zs=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Mo=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:di.side,width:(r=t==null?void 0:t.width)!=null?r:di.width,animate:(s=t==null?void 0:t.animate)!=null?s:di.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:di.reveal}};var xo={"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 qs=(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 Za=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 H,D,B,v,w,E,S,k,F,$,q,me,re,be;let a=(H=s.launcher)!=null?H:{},i=un(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}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 ie=(v=a.agentIconSize)!=null?v:"40px";if(p.style.height=ie,p.style.width=ie,p.innerHTML="",a.agentIconName){let we=parseFloat(ie)||24,We=Se(a.agentIconName,we*.6,"var(--persona-text-inverse, #ffffff)",2);We?(p.appendChild(We),p.style.display=""):(p.textContent=(w=a.agentIconText)!=null?w:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ie=(S=a.agentIconSize)!=null?S:"40px";f.style.height=ie,f.style.width=ie,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 ie=(k=a.callToActionIconSize)!=null?k:"32px";g.style.height=ie,g.style.width=ie,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 we=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,we=(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 We=parseFloat(ie)||24,ye=Math.max(We-we,8),Z=Se(a.callToActionIconName,ye,"currentColor",2);Z?g.appendChild(Z):g.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else g.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let x=a.position&&xo[a.position]?xo[a.position]:xo["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",M="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?M:`${C} ${x}`,i||(n.style.zIndex=String((q=a.zIndex)!=null?q:bn));let W="1px solid var(--persona-border, #e5e7eb)",L="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=(me=a.border)!=null?me:W,n.style.boxShadow=(re=a.shadow)!=null?re:L,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=(be=a.collapsedMaxWidth)!=null?be:"",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 yy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",di=(e,t={})=>{var C,M,W,L,H,D;let{showClose:n=!0,wrapperClassName:o=yy,buttonSize:r,iconSize:s="28px"}=t,a=(C=e==null?void 0:e.launcher)!=null?C:{},i=(M=r!=null?r:a.closeButtonSize)!=null?M:"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=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(H=a.closeButtonIconName)!=null?H:"x",g=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let x=Se(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 B=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${B} 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 B=null,v=()=>{if(B)return;let E=l.ownerDocument,S=E.body;if(!S)return;B=Eo(E,"div","persona-clear-chat-tooltip"),B.textContent=u;let k=Eo(E,"div");k.className="persona-clear-chat-tooltip-arrow",B.appendChild(k);let F=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(nr),B.style.left=`${F.left+F.width/2}px`,B.style.top=`${F.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},w=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=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}},vy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pi=(e,t={})=>{var B,v,w,E,S,k,F,$,q,me,re,be,ie;let{wrapperClassName:n=vy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?v:{},i=(w=o!=null?o:a.size)!=null?w:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(S=a.iconColor)!=null?S:"",u=(k=a.backgroundColor)!=null?k:"",p=(F=a.borderWidth)!=null?F:"",f=($=a.borderColor)!=null?$:"",g=(q=a.borderRadius)!=null?q:"",x=(me=a.paddingX)!=null?me:"",C=(re=a.paddingY)!=null?re:"",M=(be=a.tooltipText)!=null?be:"Clear chat",W=(ie=a.showTooltip)!=null?ie:!0,L=b("div",n),H=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");H.style.height=i,H.style.width=i,H.type="button",H.setAttribute("aria-label",M),H.style.color=l||Mn.actionIconColor;let D=Se(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),u&&(H.style.backgroundColor=u,H.classList.remove("hover:persona-bg-gray-100")),p||f){let we=p||"0px",We=f||"transparent";H.style.border=`${we} solid ${We}`,H.classList.remove("persona-border-none")}if(g&&(H.style.borderRadius=g,H.classList.remove("persona-rounded-full")),x&&(H.style.paddingLeft=x,H.style.paddingRight=x),C&&(H.style.paddingTop=C,H.style.paddingBottom=C),L.appendChild(H),W&&M){let we=null,We=()=>{if(we)return;let Z=H.ownerDocument,Ee=Z.body;if(!Ee)return;we=Eo(Z,"div","persona-clear-chat-tooltip"),we.textContent=M;let X=Eo(Z,"div");X.className="persona-clear-chat-tooltip-arrow",we.appendChild(X);let Ae=H.getBoundingClientRect();we.style.position="fixed",we.style.zIndex=String(nr),we.style.left=`${Ae.left+Ae.width/2}px`,we.style.top=`${Ae.top-8}px`,we.style.transform="translate(-50%, -100%)",Ee.appendChild(we)},ye=()=>{we&&we.parentNode&&(we.parentNode.removeChild(we),we=null)};L.addEventListener("mouseenter",We),L.addEventListener("mouseleave",ye),H.addEventListener("focus",We),H.addEventListener("blur",ye),L._cleanupTooltip=()=>{ye(),L.removeEventListener("mouseenter",We),L.removeEventListener("mouseleave",ye),H.removeEventListener("focus",We),H.removeEventListener("blur",ye)}}return{button:H,wrapper:L}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Sr=e=>{var B,v,w,E,S,k,F,$,q,me,re,be,ie,we,We,ye;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=(B=t==null?void 0:t.launcher)!=null?B:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(w=r.closeButtonPlacement)!=null?w:"inline",i=(E=r.headerIconHidden)!=null?E:!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 Z=parseFloat(s)||24,Ee=Se(d,Z*.6,"currentColor",1);Ee?l.replaceChildren(Ee):l.textContent=(k=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?k:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let Z=b("img");Z.src=t.launcher.iconUrl,Z.alt="",Z.className="persona-rounded-xl persona-object-cover",Z.style.height=s,Z.style.width=s,l.replaceChildren(Z)}else l.textContent=(q=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?q:"\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=Mn.titleColor,p.textContent=(re=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?re:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Mn.subtitleColor,f.textContent=(ie=(be=t==null?void 0:t.launcher)==null?void 0:be.subtitle)!=null?ie:"Here to help you get answers fast",u.append(p,f),i?o.append(u):o.append(l,u);let g=(we=r.clearChat)!=null?we:{},x=(We=g.enabled)!=null?We:!0,C=(ye=g.placement)!=null?ye:"inline",M=null,W=null;if(x){let Ee=pi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Ee.button,W=Ee.wrapper,C==="top-right"&&(W.style.right="48px"),C==="inline"&&o.appendChild(W)}let L=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:H,wrapper:D}=di(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:W}},js=(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 jr(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(nr)):(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 M=document.createElement("hr");a.appendChild(M)}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 M=Se(g.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let C=document.createElement("span");C.textContent=g.label,x.appendChild(C),x.addEventListener("click",M=>{M.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 yn(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=Se(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 gl(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=Se(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 qu(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=Se(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,M;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=jr({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 M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"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 xy=e=>{var o;let t=Sr({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 wy(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=Se(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=jr({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 Cy=e=>{var L,H,D,B,v,w,E,S,k;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},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=qu({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,u=(D=l.querySelector(".persona-combo-btn-label"))!=null?D: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=Mn.titleColor,u.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(u),wy(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 $=r.onTitleClick;l.addEventListener("click",q=>{q.target.closest("button")||$()}),l.addEventListener("keydown",q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),$())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(w=F.borderRadius)!=null?w:"10px",l.style.padding=(E=F.padding)!=null?E:"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 $,q;l.style.backgroundColor=($=F.background)!=null?$:"",l.style.borderColor=(q=F.border)!=null?q:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(S=a.closeButtonSize)!=null?S:"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||Mn.actionIconColor;let x=(k=a.closeButtonIconName)!=null?k:"x",C=Se(x,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),f.appendChild(g),i.appendChild(f);let M=b("div");M.style.display="none";let W=b("span");return W.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:W,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ju={default:xy,minimal:Cy},Sy=e=>{var t;return(t=ju[e])!=null?t:ju.default},ui=(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=Sy(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 mi=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}},gi=e=>{var B,v,w,E,S,k,F,$,q,me,re,be;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(v=t.useIcon)!=null?v:!1,o=(w=t.iconText)!=null?w:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=($=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?$:"Send",l=(me=(q=e==null?void 0:e.copy)==null?void 0:q.stopButtonLabel)!=null?me:"Stop",u=(re=t.showTooltip)!=null?re:!1,p=(be=t.size)!=null?be:"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 M=null,W=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 ie=parseFloat(p)||24,we=(g==null?void 0:g.trim())||"currentColor";r?(M=Se(r,ie,we,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,W=Se(s,ie,we,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 L=null;u&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,x.appendChild(L)),C.setAttribute("aria-label",a),x.appendChild(C);let H="send";return{button:C,wrapper:x,setMode:ie=>{if(ie===H)return;H=ie;let we=ie==="stop"?i:a;if(C.setAttribute("aria-label",we),L&&(L.textContent=we),n){if(M&&W){let We=ie==="stop"?W:M;C.replaceChildren(We)}}else C.textContent=ie==="stop"?l:d}}},fi=e=>{var L,H,D,B,v,w,E,S,k,F,$,q;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(o||r))return null;let a=(B=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?B:"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=(S=t.backgroundColor)!=null?S:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,g=(F=t.iconColor)!=null?F:(k=e==null?void 0:e.sendButton)==null?void 0:k.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=Se(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 M=($=t.tooltipText)!=null?$:"Start voice recognition";if(((q=t.showTooltip)!=null?q:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},hi=e=>{var x,C,M,W,L,H,D,B;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(M=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?M:"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=((L=t.maxFiles)!=null?L: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",(H=t.buttonTooltipText)!=null?H:"Attach file");let i=(D=t.buttonIconName)!=null?D:"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=Se(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=(B=t.buttonTooltipText)!=null?B:"Attach file",g=b("div","persona-send-button-tooltip");return g.textContent=f,s.appendChild(g),{button:a,wrapper:s,input:r,previewsContainer:o}},bi=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},yi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var vi=e=>{var x,C,M,W,L,H;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=yi(),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}=mi(t);a();let i=gi(t),d=fi(t),l=hi(t),u=bi(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",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.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:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(W=l==null?void 0:l.wrapper)!=null?W:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Ku=()=>{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=Se("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=Se("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Gu=e=>{var x,C,M,W,L,H;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=yi();o.style.display="none";let r=bi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=mi(t);s.style.maxHeight="100px",a();let i=gi(t),d=fi(t),l=hi(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",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.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:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(W=l==null?void 0:l.wrapper)!=null?W:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Yu=e=>{var u,p,f,g,x,C,M,W,L,H,D,B,v,w,E,S,k;let t=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,n=un(e);if(zs(e)){let F=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(x=F.expandedSize)!=null?x:"anchored",$.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:bn);let q=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");q.style.width="100%",$.appendChild(q);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(W=F.expandedSize)!=null?W:"anchored",me.style.zIndex=String((H=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?H:bn),{wrapper:$,panel:q,pillRoot:me}}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"),$=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($),{wrapper:F,panel:$}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),q=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?B:"100%";return F.style.width=q,$.style.width="100%",F.appendChild($),{wrapper:F,panel:$}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&xo[r.position]?xo[r.position]:xo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((E=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?E:bn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?k:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ay=(e,t)=>{var D,B,v,w,E,S,k,F,$;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}=di(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=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:B.enabled)!=null?v:!0,a=null,i=null;if(s){let q=pi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=q.button,i=q.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=(E=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?E:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(k=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",u.append(p,f);let g=b("div","persona-flex persona-flex-col persona-gap-3"),x=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;x&&(g.style.maxWidth=x,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let W=Gu({config:e}),{root:L,textNode:H}=Ku();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:g,composerOverlay:M,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:f,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:L,peekTextNode:H}},Xu=(e,t=!0)=>{var M,W,L,H,D,B,v,w,E;if(zs(e))return Ay(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=(M=e==null?void 0:e.layout)==null?void 0:M.header,r=((W=e==null?void 0:e.layout)==null?void 0:W.showHeader)!==!1,s=o?ui(e,o,{showClose:t}):Sr({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=un(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=(H=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?H:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(B=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?B:"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=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?js(n,s,e):(s.header.style.display="none",js(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 Ty=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}},ky=(e,t)=>{if(!e)return null;let n=Ty(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ey=(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},My=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},fl=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(":"))},hl=320,Ju=320,Ly=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Iy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Wy=(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=`${hl}px`,l.style.maxHeight=`${Ju}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,l.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{u=!0}),My(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}},By=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(!fl(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=`${hl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Hy=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(!fl(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=`${hl}px`,r.style.maxHeight=`${Ju}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}},Dy=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(!fl(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}},Ks=()=>{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},Fy=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ks};if(t){let r=t(o);if(r!==null)return r}return Ks()},Oy=(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},Qu=(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},Ny=(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},_y=(e,t,n)=>{var g,x,C,M,W,L;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 H=b("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(M=t.visibility)!=null?M:"hover",i=(W=t.align)!=null?W:"right",d=(L=t.layout)!=null?L:"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=(H,D,B)=>{let v=yn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",B),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},bl=(e,t,n,o,r,s)=>{var Z,Ee,X,Ae,fe,le,ue,je,j,oe,Re,tt,ge,ce,_e,Le,de;let a=n!=null?n:{},i=(Z=a.layout)!=null?Z:"bubble",d=a.avatar,l=a.timestamp,u=(Ee=d==null?void 0:d.show)!=null?Ee:!1,p=(X=l==null?void 0:l.show)!=null?X:!1,f=(Ae=d==null?void 0:d.position)!=null?Ae:"left",g=(fe=l==null?void 0:l.position)!=null?fe:"below",x=Ny(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 M=Ly(e),W=(ue=(le=e.content)==null?void 0:le.trim())!=null?ue:"",H=M.length>0&&W===Ya,D=ai((j=(je=s==null?void 0:s.widgetConfig)==null?void 0:je.features)==null?void 0:j.streamAnimation),B=(tt=(Re=(oe=s==null?void 0:s.widgetConfig)==null?void 0:oe.features)==null?void 0:Re.streamAnimation)==null?void 0:tt.plugins,v=e.role==="assistant"&&D.type!=="none"?_s(D.type,B):null,w=e.role==="assistant"&&((ge=v==null?void 0:v.isAnimating)==null?void 0:ge.call(v,e))===!0,E=e.role==="assistant"&&v!==null&&(!!e.streaming||w);E&&(v!=null&&v.bubbleClass)&&C.classList.add(v.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),E&&v&&(v.containerClass&&S.classList.add(v.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let k=E?ii((ce=e.content)!=null?ce:"",D.buffer,v,e,!!e.streaming):(_e=e.content)!=null?_e:"",F=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;E&&(v==null?void 0:v.wrap)==="char"?$=Vs(F,"char",e.id,{skipTags:v.skipTags}):E&&(v==null?void 0:v.wrap)==="word"&&($=Vs(F,"word",e.id,{skipTags:v.skipTags}));let q=null;if(H?(q=document.createElement("div"),q.innerHTML=$,q.style.display="none",S.appendChild(q)):S.innerHTML=$,E&&(v!=null&&v.useCaret)&&!H&&W){let Y=li(),Ve=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ct=Ve[Ve.length-1];if(Ct!=null&&Ct.parentNode)Ct.parentNode.insertBefore(Y,Ct.nextSibling);else{let Q=S.lastElementChild;Q?Q.appendChild(Y):S.appendChild(Y)}}if(p&&g==="inline"&&e.createdAt){let Y=Qu(e,l);Y.classList.add("persona-ml-2","persona-inline"),S.appendChild(Y)}if(M.length>0){let Y=Wy(M,!H&&!!W,()=>{H&&q&&(q.style.display="")});Y?C.appendChild(Y):H&&q&&(q.style.display="")}let me=Iy(e);if(me.length>0){let Y=By(me);Y&&C.appendChild(Y)}let re=Ry(e);if(re.length>0){let Y=Hy(re);Y&&C.appendChild(Y)}let be=Py(e);if(be.length>0){let Y=Dy(be);Y&&C.appendChild(Y)}if(C.appendChild(S),p&&g==="below"&&e.createdAt){let Y=Qu(e,l);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let ie=e.role==="assistant"?ky(e.stopReason,(de=(Le=s==null?void 0:s.widgetConfig)==null?void 0:Le.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),Ve=D.placeholder==="skeleton",Ct=Ve&&D.buffer==="line"&&Y;if(Y)Ct&&C.appendChild($s());else if(Ve)C.appendChild($s());else{let Q=Fy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Q&&C.appendChild(Q)}}if(ie&&e.stopReason&&!e.streaming&&(W||(S.style.display="none"),C.appendChild(Ey(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Y=_y(e,o,r);C.appendChild(Y)}if(!u||e.role==="system")return C;let We=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ye=Oy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?We.append(C,ye):We.append(ye,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),We};var Kr=new Set,Vy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$y=(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
- `):""},Zu=(e,t)=>{let n=Kr.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=Se(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")},yl=(e,t)=>{var re,be,ie,we,We,ye,Z,Ee,X,Ae,fe;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=(be=(re=t==null?void 0:t.features)==null?void 0:re.reasoningDisplay)!=null?be:{},s=r.expandable!==!1,a=s&&Kr.has(e.id),i=n.status!=="complete",d=$y(e,(ie=r.previewMaxLines)!=null?ie: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=(we=t==null?void 0:t.reasoning)!=null?we:{},x=String((We=n.startedAt)!=null?We:Date.now()),C=()=>{let le=b("span","");return le.setAttribute("data-tool-elapsed",x),le.textContent=za(n),le},M=(ye=g.renderCollapsedSummary)==null?void 0:ye.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:za(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(p.textContent=M,u.appendChild(p)):M instanceof HTMLElement?u.appendChild(M):(p.textContent=f,u.appendChild(p));let W=b("span","persona-text-xs persona-text-persona-primary");W.textContent=Su(n),u.appendChild(W);let L=(Z=r.loadingAnimation)!=null?Z:"none",H=g.activeTextTemplate,D=g.completeTextTemplate,B=i?H:D,v=M instanceof HTMLElement,w=(le,ue,je)=>{let j=je;for(let oe of ue){let Re=b("span","persona-tool-char");Re.style.setProperty("--char-index",String(j)),Re.textContent=oe===" "?"\xA0":oe,le.appendChild(Re),j++}return j},E=(le,ue)=>{p.textContent="";let je=qa(le,""),j=0;for(let oe of je){let Re=oe.styles.length>0?(()=>{let tt=b("span",oe.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return p.appendChild(tt),tt})():p;if(oe.isDuration&&i)Re.appendChild(C());else{let tt=oe.isDuration?za(n):oe.text;ue?j=w(Re,tt,j):Re.appendChild(document.createTextNode(tt))}}};if(!v&&B)if(W.style.display="none",p.style.display="",i&&L!=="none"){let le=(Ee=g.loadingAnimationDuration)!=null?Ee:2e3;p.setAttribute("data-preserve-animation","true"),L==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`),E(B,!1)):(p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`),L==="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)),E(B,!0))}else E(B,!1);else if(!v&&i&&L!=="none"){p.style.display="";let le=(X=g.loadingAnimationDuration)!=null?X:2e3;if(p.setAttribute("data-preserve-animation","true"),L==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`);else{p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`),L==="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 ue=p.textContent||f;p.textContent="",w(p,ue,0)}n.status==="complete"&&(p.style.display="none")}else v||(n.status==="complete"?p.style.display="none":p.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let ue=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ue?S.appendChild(ue):S.textContent=a?"Hide":"Show";let je=b("div","persona-flex persona-items-center persona-ml-auto");je.append(S),l.append(u,je)}else l.append(u);let k=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let le=(fe=(Ae=t==null?void 0:t.reasoning)==null?void 0:Ae.renderCollapsedPreview)==null?void 0:fe.call(Ae,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Vy(k,le)||(k.textContent=d),k.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,k),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 $=n.chunks.join(""),q=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return q.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(q),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let ue=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ue?S.appendChild(ue):S.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(l,k,F),o};var Gr=new Set,Uy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zy=(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 H,D,B,v,x,k,S,E,F,$,j,me,se,ge;let a=(H=s.launcher)!=null?H:{},i=pn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(m.style.height=ie,m.style.width=ie,m.innerHTML="",a.agentIconName){let be=parseFloat(ie)||24,Fe=Te(a.agentIconName,be*.6,"var(--persona-text-inverse, #ffffff)",2);Fe?(m.appendChild(Fe),m.style.display=""):(m.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",m.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ie=(S=a.agentIconSize)!=null?S:"40px";f.style.height=ie,f.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ie=(E=a.callToActionIconSize)!=null?E:"32px";u.style.height=ie,u.style.width=ie,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let be=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,be=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Fe=parseFloat(ie)||24,ve=Math.max(Fe-be,8),J=Te(a.callToActionIconName,ve,"currentColor",2);J?u.appendChild(J):u.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else u.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let w=a.position&&xo[a.position]?xo[a.position]:xo["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",M="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?M:`${C} ${w}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:hn));let I="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(me=a.border)!=null?me:I,n.style.boxShadow=(se=a.shadow)!=null?se:R,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ge=a.collapsedMaxWidth)!=null?ge:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var yy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",pi=(e,t={})=>{var C,M,I,R,H,D;let{showClose:n=!0,wrapperClassName:o=yy,buttonSize:r,iconSize:s="28px"}=t,a=(C=e==null?void 0:e.launcher)!=null?C:{},i=(M=r!=null?r:a.closeButtonSize)!=null?M:"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 p=(I=a.closeButtonTooltipText)!=null?I:"Close chat",m=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(H=a.closeButtonIconName)!=null?H:"x",u=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let w=Te(f,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let B=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${B} 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),m&&p){let B=null,v=()=>{if(B)return;let k=l.ownerDocument,S=k.body;if(!S)return;B=Eo(k,"div","persona-clear-chat-tooltip"),B.textContent=p;let E=Eo(k,"div");E.className="persona-clear-chat-tooltip-arrow",B.appendChild(E);let F=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(or),B.style.left=`${F.left+F.width/2}px`,B.style.top=`${F.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},x=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",x),l.addEventListener("focus",v),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",v),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},vy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ui=(e,t={})=>{var B,v,x,k,S,E,F,$,j,me,se,ge,ie;let{wrapperClassName:n=vy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?v:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(S=a.iconColor)!=null?S:"",p=(E=a.backgroundColor)!=null?E:"",m=(F=a.borderWidth)!=null?F:"",f=($=a.borderColor)!=null?$:"",u=(j=a.borderRadius)!=null?j:"",w=(me=a.paddingX)!=null?me:"",C=(se=a.paddingY)!=null?se:"",M=(ge=a.tooltipText)!=null?ge:"Clear chat",I=(ie=a.showTooltip)!=null?ie:!0,R=b("div",n),H=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");H.style.height=i,H.style.width=i,H.type="button",H.setAttribute("aria-label",M),H.style.color=l||Mn.actionIconColor;let D=Te(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),p&&(H.style.backgroundColor=p,H.classList.remove("hover:persona-bg-gray-100")),m||f){let be=m||"0px",Fe=f||"transparent";H.style.border=`${be} solid ${Fe}`,H.classList.remove("persona-border-none")}if(u&&(H.style.borderRadius=u,H.classList.remove("persona-rounded-full")),w&&(H.style.paddingLeft=w,H.style.paddingRight=w),C&&(H.style.paddingTop=C,H.style.paddingBottom=C),R.appendChild(H),I&&M){let be=null,Fe=()=>{if(be)return;let J=H.ownerDocument,Le=J.body;if(!Le)return;be=Eo(J,"div","persona-clear-chat-tooltip"),be.textContent=M;let Y=Eo(J,"div");Y.className="persona-clear-chat-tooltip-arrow",be.appendChild(Y);let xe=H.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(or),be.style.left=`${xe.left+xe.width/2}px`,be.style.top=`${xe.top-8}px`,be.style.transform="translate(-50%, -100%)",Le.appendChild(be)},ve=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};R.addEventListener("mouseenter",Fe),R.addEventListener("mouseleave",ve),H.addEventListener("focus",Fe),H.addEventListener("blur",ve),R._cleanupTooltip=()=>{ve(),R.removeEventListener("mouseenter",Fe),R.removeEventListener("mouseleave",ve),H.removeEventListener("focus",Fe),H.removeEventListener("blur",ve)}}return{button:H,wrapper:R}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ar=e=>{var B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,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=(B=t==null?void 0:t.launcher)!=null?B:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(k=r.headerIconHidden)!=null?k:!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 J=parseFloat(s)||24,Le=Te(d,J*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(E=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?E:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let J=b("img");J.src=t.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=s,J.style.width=s,l.replaceChildren(J)}else l.textContent=(j=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?j:"\u{1F4AC}";let p=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=b("span","persona-text-base persona-font-semibold");m.style.color=Mn.titleColor,m.textContent=(se=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?se:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Mn.subtitleColor,f.textContent=(ie=(ge=t==null?void 0:t.launcher)==null?void 0:ge.subtitle)!=null?ie:"Here to help you get answers fast",p.append(m,f),i?o.append(p):o.append(l,p);let u=(be=r.clearChat)!=null?be:{},w=(Fe=u.enabled)!=null?Fe:!0,C=(ve=u.placement)!=null?ve:"inline",M=null,I=null;if(w){let Le=ui(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Le.button,I=Le.wrapper,C==="top-right"&&(I.style.right="48px"),C==="inline"&&o.appendChild(I)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&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:H,wrapper:D}=pi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:m,headerSubtitle:f,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},js=(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 jr(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(or)):(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 u of t){if(u.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",u.id),u.destructive&&w.setAttribute("data-destructive",""),u.icon){let M=Te(u.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let C=document.createElement("span");C.textContent=u.label,w.appendChild(C),w.addEventListener("click",M=>{M.stopPropagation(),p(),n(u.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let u=o.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=w=>{!a.contains(w.target)&&!o.contains(w.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:f}}function bn(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=Te(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function fl(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 p=b("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=Te(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let m=b("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[f,u]of Object.entries(d))p.setAttribute(f,u);return p}function qu(e){var u,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 p=b("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=Te(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(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 C,M;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=jr({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 M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{p.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 xy=e=>{var o;let t=Ar({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 wy(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=Te(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=jr({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Cy=e=>{var R,H,D,B,v,x,k,S,E;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(R=t==null?void 0:t.launcher)!=null?R:{},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,p;if(d)l=qu({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(D=l.querySelector(".persona-combo-btn-label"))!=null?D:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=b("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(p),wy(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 $=r.onTitleClick;l.addEventListener("click",j=>{j.target.closest("button")||$()}),l.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),$())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(x=F.borderRadius)!=null?x:"10px",l.style.padding=(k=F.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,j;l.style.backgroundColor=($=F.background)!=null?$:"",l.style.borderColor=(j=F.border)!=null?j:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(S=a.closeButtonSize)!=null?S:"32px",f=b("div",""),u=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");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||Mn.actionIconColor;let w=(E=a.closeButtonIconName)!=null?E:"x",C=Te(w,"28px","currentColor",1);C?u.appendChild(C):u.textContent="\xD7",o&&u.addEventListener("click",o),f.appendChild(u),i.appendChild(f);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:I,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ju={default:xy,minimal:Cy},Sy=e=>{var t;return(t=ju[e])!=null?t:ju.default},mi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=b("div");p.style.display="none";let m=b("span"),f=b("span"),u=b("button");u.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:f,closeButton:u,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Sy(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 gi=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}},fi=e=>{var B,v,x,k,S,E,F,$,j,me,se,ge;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(v=t.useIcon)!=null?v:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(E=t.stopTooltipText)!=null?E:"Stop generating",d=($=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?$:"Send",l=(me=(j=e==null?void 0:e.copy)==null?void 0:j.stopButtonLabel)!=null?me:"Stop",p=(se=t.showTooltip)!=null?se:!1,m=(ge=t.size)!=null?ge:"40px",f=t.backgroundColor,u=t.textColor,w=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 M=null,I=null;if(n){C.style.width=m,C.style.height=m,C.style.minWidth=m,C.style.minHeight=m,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",u?C.style.color=u:C.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(m)||24,be=(u==null?void 0:u.trim())||"currentColor";r?(M=Te(r,ie,be,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,I=Te(s,ie,be,2),f?C.style.backgroundColor=f:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,u?C.style.color=u: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 R=null;p&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,w.appendChild(R)),C.setAttribute("aria-label",a),w.appendChild(C);let H="send";return{button:C,wrapper:w,setMode:ie=>{if(ie===H)return;H=ie;let be=ie==="stop"?i:a;if(C.setAttribute("aria-label",be),R&&(R.textContent=be),n){if(M&&I){let Fe=ie==="stop"?I:M;C.replaceChildren(Fe)}}else C.textContent=ie==="stop"?l:d}}},hi=e=>{var R,H,D,B,v,x,k,S,E,F,$,j;let t=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(o||r))return null;let a=(B=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?B:"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",p=(x=t.iconSize)!=null?x:a,m=parseFloat(p)||24,f=(S=t.backgroundColor)!=null?S:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,u=(F=t.iconColor)!=null?F:(E=e==null?void 0:e.sendButton)==null?void 0:E.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let C=Te(l,m,u||"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 M=($=t.tooltipText)!=null?$:"Start voice recognition";if(((j=t.showTooltip)!=null?j:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},bi=e=>{var w,C,M,I,R,H,D,B;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(M=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?M:"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=((I=t.allowedTypes)!=null?I:_o).join(","),r.multiple=((R=t.maxFiles)!=null?R: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",(H=t.buttonTooltipText)!=null?H:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=Te(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let f=(B=t.buttonTooltipText)!=null?B:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=f,s.appendChild(u),{button:a,wrapper:s,input:r,previewsContainer:o}},yi=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},vi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var xi=e=>{var w,C,M,I,R,H;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=vi(),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}=gi(t);a();let i=fi(t),d=hi(t),l=bi(t),p=yi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let m=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"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(f,u),r.append(m),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,p),{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:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:p,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Ku=()=>{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=Te("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=Te("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Gu=e=>{var w,C,M,I,R,H;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=vi();o.style.display="none";let r=yi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=gi(t);s.style.maxHeight="100px",a();let i=fi(t),d=hi(t),l=bi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=b("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.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),p.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(m,s,f),l&&n.append(l.previewsContainer),n.append(p,o,r);let u=p;return{footer:n,suggestions:o,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:r,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:u,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var Yu=e=>{var p,m,f,u,w,C,M,I,R,H,D,B,v,x,k,S,E;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=pn(e);if(zs(e)){let F=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?u:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(w=F.expandedSize)!=null?w:"anchored",$.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:hn);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%",$.appendChild(j);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(I=F.expandedSize)!=null?I:"anchored",me.style.zIndex=String((H=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?H:hn),{wrapper:$,panel:j,pillRoot:me}}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"),$=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($),{wrapper:F,panel:$}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),j=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?B:"100%";return F.style.width=j,$.style.width="100%",F.appendChild($),{wrapper:F,panel:$}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&xo[r.position]?xo[r.position]:xo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(E=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?E:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ay=(e,t)=>{var D,B,v,x,k,S,E,F,$;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=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:B.enabled)!=null?v:!0,a=null,i=null;if(s){let j=ui(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 p=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(E=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",p.append(m,f);let u=b("div","persona-flex persona-flex-col persona-gap-3"),w=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;w&&(u.style.maxWidth=w,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=Gu({config:e}),{root:R,textNode:H}=Ku();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:M,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,introTitle:m,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode,peekBanner:R,peekTextNode:H}},Xu=(e,t=!0)=>{var M,I,R,H,D,B,v,x,k;if(zs(e))return Ay(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=(M=e==null?void 0:e.layout)==null?void 0:M.header,r=((I=e==null?void 0:e.layout)==null?void 0:I.showHeader)!==!1,s=o?mi(e,o,{showClose:t}):Ar({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=pn(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=(H=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?H:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(B=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",i.append(d,l);let p=b("div","persona-flex persona-flex-col persona-gap-3"),m=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((x=e==null?void 0:e.copy)==null?void 0:x.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=xi({config:e}),w=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?js(n,s,e):(s.header.style.display="none",js(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",w||(u.footer.style.display="none"),n.append(u.footer),n.append(C),{container:n,body:a,messagesWrapper:p,composerOverlay:C,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Ty=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}},ky=(e,t)=>{if(!e)return null;let n=Ty(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ey=(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},My=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},hl=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(":"))},bl=320,Ju=320,Ly=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Iy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Wy=(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 m;let l=b("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${bl}px`,l.style.maxHeight=`${Ju}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,l.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{p=!0}),My(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},By=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(!hl(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=`${bl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Hy=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(!hl(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=`${bl}px`,r.style.maxHeight=`${Ju}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}},Dy=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(!hl(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}},Ks=()=>{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},Fy=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ks};if(t){let r=t(o);if(r!==null)return r}return Ks()},Oy=(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},Qu=(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},Ny=(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},_y=(e,t,n)=>{var u,w,C,M,I,R;let o=(u=t.showCopy)!=null?u:!0,r=(w=t.showUpvote)!=null?w:!0,s=(C=t.showDownvote)!=null?C:!0;if(!o&&!r&&!s){let H=b("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(M=t.visibility)!=null?M:"hover",i=(I=t.align)!=null?I:"right",d=(R=t.layout)!=null?R:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let f=(H,D,B)=>{let v=bn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",B),v};return o&&m.appendChild(f("copy","Copy message","copy")),r&&m.appendChild(f("thumbs-up","Upvote","upvote")),s&&m.appendChild(f("thumbs-down","Downvote","downvote")),m},yl=(e,t,n,o,r,s)=>{var J,Le,Y,xe,Se,de,we,Ue,te,ne,re,nt,ye,le,$e,Be,ce;let a=n!=null?n:{},i=(J=a.layout)!=null?J:"bubble",d=a.avatar,l=a.timestamp,p=(Le=d==null?void 0:d.show)!=null?Le:!1,m=(Y=l==null?void 0:l.show)!=null?Y:!1,f=(xe=d==null?void 0:d.position)!=null?xe:"left",u=(Se=l==null?void 0:l.position)!=null?Se:"below",w=Ny(e.role,i),C=b("div",w.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 M=Ly(e),I=(we=(de=e.content)==null?void 0:de.trim())!=null?we:"",H=M.length>0&&I===Xa,D=ii((te=(Ue=s==null?void 0:s.widgetConfig)==null?void 0:Ue.features)==null?void 0:te.streamAnimation),B=(nt=(re=(ne=s==null?void 0:s.widgetConfig)==null?void 0:ne.features)==null?void 0:re.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&D.type!=="none"?_s(D.type,B):null,x=e.role==="assistant"&&((ye=v==null?void 0:v.isAnimating)==null?void 0:ye.call(v,e))===!0,k=e.role==="assistant"&&v!==null&&(!!e.streaming||x);k&&(v!=null&&v.bubbleClass)&&C.classList.add(v.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),k&&v&&(v.containerClass&&S.classList.add(v.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let E=k?li((le=e.content)!=null?le:"",D.buffer,v,e,!!e.streaming):($e=e.content)!=null?$e:"",F=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;k&&(v==null?void 0:v.wrap)==="char"?$=Vs(F,"char",e.id,{skipTags:v.skipTags}):k&&(v==null?void 0:v.wrap)==="word"&&($=Vs(F,"word",e.id,{skipTags:v.skipTags}));let j=null;if(H?(j=document.createElement("div"),j.innerHTML=$,j.style.display="none",S.appendChild(j)):S.innerHTML=$,k&&(v!=null&&v.useCaret)&&!H&&I){let K=ci(),_e=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=_e[_e.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(K,Et.nextSibling);else{let pe=S.lastElementChild;pe?pe.appendChild(K):S.appendChild(K)}}if(m&&u==="inline"&&e.createdAt){let K=Qu(e,l);K.classList.add("persona-ml-2","persona-inline"),S.appendChild(K)}if(M.length>0){let K=Wy(M,!H&&!!I,()=>{H&&j&&(j.style.display="")});K?C.appendChild(K):H&&j&&(j.style.display="")}let me=Iy(e);if(me.length>0){let K=By(me);K&&C.appendChild(K)}let se=Ry(e);if(se.length>0){let K=Hy(se);K&&C.appendChild(K)}let ge=Py(e);if(ge.length>0){let K=Dy(ge);K&&C.appendChild(K)}if(C.appendChild(S),m&&u==="below"&&e.createdAt){let K=Qu(e,l);K.classList.add("persona-mt-1"),C.appendChild(K)}let ie=e.role==="assistant"?ky(e.stopReason,(ce=(Be=s==null?void 0:s.widgetConfig)==null?void 0:Be.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let K=!!(E&&E.trim()),_e=D.placeholder==="skeleton",Et=_e&&D.buffer==="line"&&K;if(K)Et&&C.appendChild($s());else if(_e)C.appendChild($s());else{let pe=Fy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);pe&&C.appendChild(pe)}}if(ie&&e.stopReason&&!e.streaming&&(I||(S.style.display="none"),C.appendChild(Ey(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let K=_y(e,o,r);C.appendChild(K)}if(!p||e.role==="system")return C;let Fe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=Oy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Fe.append(C,ve):Fe.append(ve,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Fe};var Kr=new Set,Vy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$y=(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
+ `):""},Zu=(e,t)=>{let n=Kr.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=Te(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")},vl=(e,t)=>{var se,ge,ie,be,Fe,ve,J,Le,Y,xe,Se;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=(ge=(se=t==null?void 0:t.features)==null?void 0:se.reasoningDisplay)!=null?ge:{},s=r.expandable!==!1,a=s&&Kr.has(e.id),i=n.status!=="complete",d=$y(e,(ie=r.previewMaxLines)!=null?ie: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 p=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",u=(be=t==null?void 0:t.reasoning)!=null?be:{},w=String((Fe=n.startedAt)!=null?Fe:Date.now()),C=()=>{let de=b("span","");return de.setAttribute("data-tool-elapsed",w),de.textContent=qa(n),de},M=(ve=u.renderCollapsedSummary)==null?void 0:ve.call(u,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:qa(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(m.textContent=M,p.appendChild(m)):M instanceof HTMLElement?p.appendChild(M):(m.textContent=f,p.appendChild(m));let I=b("span","persona-text-xs persona-text-persona-primary");I.textContent=Su(n),p.appendChild(I);let R=(J=r.loadingAnimation)!=null?J:"none",H=u.activeTextTemplate,D=u.completeTextTemplate,B=i?H:D,v=M instanceof HTMLElement,x=(de,we,Ue)=>{let te=Ue;for(let ne of we){let re=b("span","persona-tool-char");re.style.setProperty("--char-index",String(te)),re.textContent=ne===" "?"\xA0":ne,de.appendChild(re),te++}return te},k=(de,we)=>{m.textContent="";let Ue=ja(de,""),te=0;for(let ne of Ue){let re=ne.styles.length>0?(()=>{let nt=b("span",ne.styles.map(ye=>`persona-tool-text-${ye}`).join(" "));return m.appendChild(nt),nt})():m;if(ne.isDuration&&i)re.appendChild(C());else{let nt=ne.isDuration?qa(n):ne.text;we?te=x(re,nt,te):re.appendChild(document.createTextNode(nt))}}};if(!v&&B)if(I.style.display="none",m.style.display="",i&&R!=="none"){let de=(Le=u.loadingAnimationDuration)!=null?Le:2e3;m.setAttribute("data-preserve-animation","true"),R==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),k(B,!1)):(m.classList.add(`persona-tool-loading-${R}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),R==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),k(B,!0))}else k(B,!1);else if(!v&&i&&R!=="none"){m.style.display="";let de=(Y=u.loadingAnimationDuration)!=null?Y:2e3;if(m.setAttribute("data-preserve-animation","true"),R==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{m.classList.add(`persona-tool-loading-${R}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),R==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let we=m.textContent||f;m.textContent="",x(m,we,0)}n.status==="complete"&&(m.style.display="none")}else v||(n.status==="complete"?m.style.display="none":m.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let we=Te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?S.appendChild(we):S.textContent=a?"Hide":"Show";let Ue=b("div","persona-flex persona-items-center persona-ml-auto");Ue.append(S),l.append(p,Ue)}else l.append(p);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 de=(Se=(xe=t==null?void 0:t.reasoning)==null?void 0:xe.renderCollapsedPreview)==null?void 0:Se.call(xe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Vy(E,de)||(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 $=n.chunks.join(""),j=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return j.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(j),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let we=Te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?S.appendChild(we):S.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 Gr=new Set,Uy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zy=(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=qr(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},qy=(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=zy(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Au(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=sl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=sl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},em=(e,t,n)=>{var u;let o=Gr.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=Se(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")},vl=(e,t)=>{var $,q,me,re,be,ie,we,We,ye;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},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=(me=(q=t==null?void 0:t.features)==null?void 0:q.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Gr.has(e.id),{summary:d,previewText:l,isActive:u}=qy(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((re=n.startedAt)!=null?re:Date.now()),C=()=>{let Z=b("span","");return Z.setAttribute("data-tool-elapsed",x),Z.textContent=Rs(n),Z},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(be=s.collapsedMode)!=null?be:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Rs(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(g.textContent=M,f.appendChild(g)):M instanceof HTMLElement?f.appendChild(M):(g.textContent=d,f.appendChild(g));let W=(we=s.loadingAnimation)!=null?we:"none",L=o.activeTextTemplate,H=o.completeTextTemplate,D=u?L:H,B=M instanceof HTMLElement,v=(Z,Ee,X)=>{let Ae=X;for(let fe of Ee){let le=b("span","persona-tool-char");le.style.setProperty("--char-index",String(Ae)),le.textContent=fe===" "?"\xA0":fe,Z.appendChild(le),Ae++}return Ae},w=(Z,Ee)=>{var le;g.textContent="";let X=((le=n.name)==null?void 0:le.trim())||"tool",Ae=qa(Z,X),fe=0;for(let ue of Ae){let je=ue.styles.length>0?(()=>{let j=b("span",ue.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return g.appendChild(j),j})():g;if(ue.isDuration&&u)je.appendChild(C());else{let j=ue.isDuration?Rs(n):ue.text;Ee?fe=v(je,j,fe):je.appendChild(document.createTextNode(j))}}};if(!B)if(u&&W!=="none"){let Z=(We=o.loadingAnimationDuration)!=null?We:2e3;if(g.setAttribute("data-preserve-animation","true"),W==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),D&&w(D,!1);else if(g.classList.add(`persona-tool-loading-${W}`),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),W==="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)),D)w(D,!0);else{let Ee=g.textContent||d;g.textContent="",v(g,Ee,0)}}else D&&w(D,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let Z=o.toggleTextColor||o.headerTextColor||"currentColor",Ee=Se(i?"chevron-up":"chevron-down",16,Z,2);Ee?E.appendChild(Ee):E.textContent=i?"Hide":"Show";let X=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(E),p.append(f,X)}else p.append(f);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let Z=(ye=o.renderCollapsedPreview)==null?void 0:ye.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});Uy(S,Z)||(S.textContent=l),S.style.display=""}if(!i&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,S),r;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),n.name){let Z=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Z.style.color=o.contentTextColor:o.headerTextColor&&(Z.style.color=o.headerTextColor),Z.textContent=n.name,k.appendChild(Z)}if(n.args!==void 0){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Arguments";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=qr(n.args),Z.append(Ee,X),k.appendChild(Z)}if(n.chunks&&n.chunks.length){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Activity";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=n.chunks.join(""),Z.append(Ee,X),k.appendChild(Z)}if(n.status==="complete"&&n.result!==void 0){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Result";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=qr(n.result),Z.append(Ee,X),k.appendChild(Z)}if(n.status==="complete"&&typeof n.duration=="number"){let Z=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Z.style.color=o.contentTextColor),Z.textContent=`Duration: ${n.duration}ms`,k.appendChild(Z)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let Z=o.toggleTextColor||o.headerTextColor||"currentColor",Ee=Se(i?"chevron-up":"chevron-down",16,Z,2);Ee?E.appendChild(Ee):E.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(p,S,k),r};import{parse as jy,ARR as Ky,OBJ as Gy,STR as Yy}from"partial-json";var Xy="ask_user_question",xl=8,Yr="data-persona-ask-sheet-for",Qy="Other",Jy="Other\u2026",nm="Type your own answer here",om="Send",Zy="Next",ev="Back",tv="Submit all",nv="Skip",ov=3,wl="data-ask-current-index",Cl="data-ask-question-count",rm="data-ask-answers",Sl="data-ask-grouped",sm="data-ask-layout",rv=e=>e.layout==="pills"?"pills":"rows",sv=e=>e.getAttribute(sm)==="pills"?"pills":"rows",tm=!1,am=e=>e.replace(/["\\]/g,"\\$&"),Ar=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xy,Al=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=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=jy(r,Yy|Gy|Ky);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>xl&&!tm&&(tm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${xl}.`)),t.slice(0,xl)},av=e=>{var t;return(t=Gs(e)[0])!=null?t:null},iv=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},lv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},im=(e,t,n)=>{if(e!=="rows")return null;let 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},cv=(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=im(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},dv=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},pv=(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<ov;g++)s.appendChild(dv(o));return s}if(d.forEach((g,x)=>{s.appendChild(cv(g,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=o==="rows"?Qy:Jy;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"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(u=t.freeTextPlaceholder)!=null?u:nm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:g),C.appendChild(M),x.appendChild(C);let W=im(o,a,d.length);W&&x.appendChild(W),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},lm=(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:nm,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:om,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},uv=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:om,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},mv=(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:ev,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:nv,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:tv:(f=n.nextLabel)!=null?f:Zy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Tr=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(wl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gv=(e,t)=>{e.setAttribute(wl,String(Math.max(0,Math.floor(t))))},Qr=e=>{var n;let t=Number((n=e.getAttribute(Cl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},rr=e=>e.getAttribute(Sl)==="true",fv=(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},hv=(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)))},xi=(e,t)=>{let{payload:n}=Xr(t),o=Gs(n),r=Tr(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},dm=e=>{let t=Tr(e),n=lo(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=""},pm=e=>{if(!rr(e))return;let t=Tr(e),n=lo(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}},Tl=(e,t,n)=>{let o=Al(n),r=sv(e),{payload:s,complete:a}=Xr(t),i=rr(e),d=lo(e),l=Qr(e),u=i?iv(s,d):av(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 L=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=L,x.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let L=pv(u,o,a,r);C.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(lm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!M?e.appendChild(uv(o)):(!p||i)&&M&&M.remove(),e.setAttribute("data-multi-select",p?"true":"false");let W=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=mv(d,l,o);W?W.replaceWith(L):e.appendChild(L)}else W&&W.remove();dm(e),pm(e)},bv=(e,t,n)=>{let o=Al(t),r=rv(o),s=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=fv(e,a),u=d?hv(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Yr,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Cl,String(i)),p.setAttribute(wl,String(u)),p.setAttribute(Sl,d?"true":"false"),p.setAttribute(sm,r),cm(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`),lv(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 M=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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),p.appendChild(M),r!=="rows"&&p.appendChild(lm(o,r)),Tl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},yv=(e,t,n)=>{let{payload:o}=Xr(t),r=Math.max(1,Gs(o).length);r>Qr(e)&&(e.setAttribute(Cl,String(r)),r>1&&!rr(e)&&e.setAttribute(Sl,"true")),Tl(e,t,n)};var wi=(e,t,n)=>{if(!n||!Ar(e)||Al(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Yr}]`).forEach(l=>{l.getAttribute(Yr)!==r&&l.remove()});let a=n.querySelector(`[${Yr}="${am(r)}"]`);if(a){yv(a,e,t);return}let{payload:i}=Xr(e),d=bv(e,t,i);n.appendChild(d)},Jr=(e,t)=>{if(!e)return;let n=t?`[${Yr}="${am(t)}"]`:`[${Yr}]`;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)})},kl=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),sr=(e,t)=>{let n=Tr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,cm(e,n),dm(e),pm(e)},Ci=(e,t,n,o)=>{let r=Qr(e),s=Math.max(0,Math.min(r-1,o));gv(e,s),Tl(e,t,n)};var El=(e,t)=>{var C,M,W,L,H,D,B,v,w,E,S,k;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=(M=o==null?void 0:o.borderColor)!=null?M:"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=Se(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=(L=o==null?void 0:o.title)!=null?L:"Approval Required",f.appendChild(g),!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"),f.appendChild(F)}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 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=qr(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 $=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");$.type="button",$.style.backgroundColor=(H=o==null?void 0:o.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",$.style.color=(D=o==null?void 0:o.approveButtonTextColor)!=null?D:"#ffffff",$.setAttribute("data-approval-action","approve");let q=Se("shield-check",14,(B=o==null?void 0:o.approveButtonTextColor)!=null?B:"#ffffff",2);q&&(q.style.marginRight="4px",$.appendChild(q));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);let re=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");re.type="button",re.style.backgroundColor=(w=o==null?void 0:o.denyButtonColor)!=null?w:"transparent",re.style.color=(E=o==null?void 0:o.denyButtonTextColor)!=null?E:"var(--persona-feedback-error, #dc2626)",re.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,re.setAttribute("data-approval-action","deny");let be=Se("shield-x",14,(S=o==null?void 0:o.denyButtonTextColor)!=null?S:"var(--persona-feedback-error, #dc2626)",2);be&&(be.style.marginRight="4px",re.appendChild(be));let ie=document.createTextNode((k=o==null?void 0:o.denyLabel)!=null?k:"Deny");re.appendChild(ie),F.append($,re),p.appendChild(F)}return a.append(i,p),s.appendChild(a),s};var um=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 Ys=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 Xs=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 vv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),xv=new Set(["step_start","execution_start"]),wv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cv=new Set(["step_complete","agent_turn_complete"]),Sv=new Set(["flow_complete","agent_complete"]),mm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),fm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,kr=(e,t)=>{let n=e[t];return fm(n)?n:void 0};function Ml(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Av(e,t){return typeof t.type=="string"?t.type:e}function Tv(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 kv(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 gm(e){var o,r,s,a,i;let t=kr(e,"result"),n=[kr(e,"tokens"),kr(e,"totalTokens"),t?kr(t,"tokens"):void 0,kr(e,"usage"),t?kr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Qn(d.output))!=null?o:Qn(d.outputTokens))!=null?r:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function Ev(e){var n,o,r,s,a;let t=kr(e,"result");return(a=(r=(o=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?o:Qn(e.execution_time))!=null?r:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function Mv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=Mv){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:Si(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(!fm(n)){mm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Av(t,n),r=this.now();if(vv.has(o)){this.startRun(r);return}if(xv.has(o)){this.run||this.startRun(r);return}if(wv.has(o)){if(!kv(o,n))return;let a=Tv(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+Ml(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Si(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cv.has(o)){if(!this.run)return;let a=this.run,i=gm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ml(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Si(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Sv.has(o)){if(!this.run)return;let a=this.run,i=gm(n),d=i!=null?i:a.exactOutputTokens+Ml(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Si(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(mm.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=Ev(n);return s!=null?s:o-t.startedAt}};function Zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Lv={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)"}},Iv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Rv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Pv=100;function Wv(e,t){let n={...Lv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Iv}function Bv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Hv(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 Dv(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 Fv(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 Ov(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 Nv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function _v(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 Vv(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 Ll(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");Zr(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 $,q;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"),M=Se(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&C.appendChild(M);let W=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=($=o.timestampFormat)!=null?$:"relative";W.textContent=L==="relative"?Bv(e.timestamp,n):Hv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let D=Wv(e.type,o.badgeColors),B=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");B.style.backgroundColor=D.bg,B.style.color=D.text,B.style.borderColor=D.text+"50",B.textContent=e.type;let v=(q=o.descriptionFields)!=null?q:Rv,w=Dv(e.payload,v),E=null;w&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=w);let S=b("div","persona-flex-1 persona-min-w-0"),k=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=Se("clipboard","12px","currentColor",1.5);return F&&k.appendChild(F),k.addEventListener("click",async me=>{me.stopPropagation(),await Fv(Ov(e)),k.innerHTML="";let re=Se("check","12px","currentColor",1.5);re&&k.appendChild(re),setTimeout(()=>{k.innerHTML="";let be=Se("clipboard","12px","currentColor",1.5);be&&k.appendChild(be)},1500)}),x.appendChild(C),x.appendChild(W),H&&x.appendChild(H),x.appendChild(B),E&&x.appendChild(E),x.appendChild(S),x.appendChild(k),g.appendChild(x),d&&g.appendChild(Vv(e,a,i)),g}}function hm(e){var x,C,M,W,L;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=(M=i==null?void 0:i.label)!=null?M:"",p=(L=(W=r==null?void 0:r.features)==null?void 0:W.eventStream)!=null?L:{},f=s.find(H=>H.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let H=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return g();function g(){let H=p.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Zr(D,H==null?void 0:H.panel);let B=[],v="",w="",E=null,S=[],k={},F=0,$=oi(),q=0,me=0,re=!1,be=null,ie=!1,we=0,We=new Set,ye=new Map,Z="",Ee="",X=null,Ae,fe,le,ue,je,j=null,oe=null,Re=null;function tt(){let ae=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ve=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");Zr(ve,H==null?void 0:H.headerBar);let wt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(wt.textContent="Events",Ae=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"),Ae.textContent="0",a){oe=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),oe.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",j=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"),j.textContent="-- tok/s",Re=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"),Re.style.display="none",Re.style.pointerEvents="none";let Zn=oe,xn=Re,On=()=>{if(!xn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=ae.getBoundingClientRect();xn.style.left=`${wo.left-Nn.left}px`,xn.style.top=`${wo.bottom-Nn.top+4}px`,xn.style.display="block"},ut=()=>{xn.style.display="none"};oe.addEventListener("mouseenter",On),oe.addEventListener("mouseleave",ut),oe.appendChild(Fn),oe.appendChild(j)}let _t=b("div","persona-flex-1");fe=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 Jt=b("option","");Jt.value="",Jt.textContent="All events",fe.appendChild(Jt),le=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"),le.type="button",le.title="Copy All";let Et=Se("clipboard-copy","12px","currentColor",1.5);Et&&le.appendChild(Et);let At=b("span","persona-text-xs");At.textContent="Copy All",le.appendChild(At),ve.appendChild(wt),ve.appendChild(Ae),oe&&ve.appendChild(oe),ve.appendChild(_t),ve.appendChild(fe),ve.appendChild(le);let ht=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Zr(ht,H==null?void 0:H.searchBar);let yt=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),Ut=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");yt&&Ut.appendChild(yt),ue=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"),Zr(ue,H==null?void 0:H.searchInput),ue.type="text",ue.placeholder="Search event payloads...",je=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"),je.type="button",je.style.display="none";let Ze=Se("x","12px","currentColor",2);return Ze&&je.appendChild(Ze),ht.appendChild(Ut),ht.appendChild(ue),ht.appendChild(je),ae.appendChild(ve),ae.appendChild(ht),Re&&ae.appendChild(Re),ae}let ge,ce=s.find(ae=>ae.renderEventStreamToolbar);if(ce!=null&&ce.renderEventStreamToolbar&&r){let ae=ce.renderEventStreamToolbar({config:r,defaultRenderer:()=>tt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ve=>{v=ve,Dn(),se()},onSearchChange:ve=>{w=ve,Dn(),se()}});ge=ae!=null?ae:tt()}else ge=tt();let _e=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");_e.style.display="none";function Le(){if(!a||!j||!oe)return;let ae=a();j.textContent=Nv(ae);let ve=_v(ae);Re&&(Re.textContent=ve,ve||(Re.style.display="none")),ve?oe.setAttribute("aria-label",ve):oe.removeAttribute("aria-label")}let de=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let Ve=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");Zr(Ve,H==null?void 0:H.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Ct=Se(l,"14px","currentColor",2);Ct&&Ve.appendChild(Ct);let Q=b("span","");Q.textContent=u,Ve.appendChild(Q);let Fe=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Fe.style.display="none",de.appendChild(Y),de.appendChild(Fe),de.appendChild(Ve),D.setAttribute("tabindex","0"),D.appendChild(ge),D.appendChild(_e),D.appendChild(de);function Ln(){let ae=t.getAll(),ve={};for(let At of ae)ve[At.type]=(ve[At.type]||0)+1;let wt=Object.keys(ve).sort(),_t=wt.length!==S.length||!wt.every((At,ht)=>At===S[ht]),Jt=!_t&&wt.some(At=>ve[At]!==k[At]),vn=ae.length!==Object.values(k).reduce((At,ht)=>At+ht,0);if(!_t&&!Jt&&!vn||(S=wt,k=ve,!fe))return;let Et=fe.value;if(fe.options[0].textContent="All events",_t){for(;fe.options.length>1;)fe.remove(1);for(let At of wt){let ht=b("option","");ht.value=At,ht.textContent=`${At} (${ve[At]||0})`,fe.appendChild(ht)}Et&&wt.includes(Et)?fe.value=Et:Et&&(fe.value="",v="")}else for(let At=1;At<fe.options.length;At++){let ht=fe.options[At];ht.textContent=`${ht.value} (${ve[ht.value]||0})`}}function Ft(){let ae=t.getAll();if(v&&(ae=ae.filter(ve=>ve.type===v)),w){let ve=w.toLowerCase();ae=ae.filter(wt=>wt.type.toLowerCase().includes(ve)||wt.payload.toLowerCase().includes(ve))}return ae}function ln(){return v!==""||w!==""}function Dn(){F=0,q=0,$.resume(),Ve.style.display="none"}function Jn(ae){We.has(ae)?We.delete(ae):We.add(ae),X=ae;let ve=Y.scrollTop,wt=$.isFollowing();ie=!0,$.pause(),se(),Y.scrollTop=ve,wt&&$.resume(),ie=!1}function N(){return Os(Y,50)}function se(){me=Date.now(),re=!1,Le(),Ln();let ae=t.getEvictedCount();ae>0?(_e.textContent=`${ae.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",B=Ft();let ve=B.length,wt=t.getSize()>0;Ae&&(Ae.textContent=String(t.getSize())),ve===0&&wt&&ln()?(Fe.textContent=w?`No events matching '${w}'`:"No events matching filter",Fe.style.display="",Y.style.display="none"):(Fe.style.display="none",Y.style.display=""),le&&(le.title=ln()?`Copy Filtered (${ve})`:"Copy All"),d&&!$.isFollowing()&&ve>F&&(q+=ve-F,Q.textContent=u?`${u}${q>0?` (${q})`:""}`:"",Ve.style.display=""),F=ve;let _t=t.getAll(),Jt=_t.length>0?_t[0].timestamp:0,vn=new Set(B.map(ht=>ht.id));for(let ht of We)vn.has(ht)||We.delete(ht);let Et=v!==Z||w!==Ee,At=ye.size===0&&B.length>0;if(Et||At||B.length===0){Y.innerHTML="",ye.clear();let ht=document.createDocumentFragment();for(let yt=0;yt<B.length;yt++){let Ut=Ll(B[yt],yt,Jt,p,We,Jn,s,r);ye.set(B[yt].id,Ut),ht.appendChild(Ut)}Y.appendChild(ht),Z=v,Ee=w,X=null}else{if(X!==null){let yt=ye.get(X);if(yt&&yt.parentNode===Y){let Ut=B.findIndex(Ze=>Ze.id===X);if(Ut>=0){let Ze=Ll(B[Ut],Ut,Jt,p,We,Jn,s,r);Y.insertBefore(Ze,yt),yt.remove(),ye.set(X,Ze)}}X=null}let ht=new Set(B.map(yt=>yt.id));for(let[yt,Ut]of ye)ht.has(yt)||(Ut.remove(),ye.delete(yt));for(let yt=0;yt<B.length;yt++){let Ut=B[yt];if(!ye.has(Ut.id)){let Ze=Ll(Ut,yt,Jt,p,We,Jn,s,r);ye.set(Ut.id,Ze),Y.appendChild(Ze)}}}$.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function He(){if(Date.now()-me>=Pv){be!==null&&(cancelAnimationFrame(be),be=null),se();return}re||(re=!0,be=requestAnimationFrame(()=>{be=null,se()}))}let Xe=(ae,ve)=>{if(!le)return;le.innerHTML="";let wt=Se(ae,"12px","currentColor",1.5);wt&&le.appendChild(wt);let _t=b("span","persona-text-xs");_t.textContent="Copy All",le.appendChild(_t),setTimeout(()=>{le.innerHTML="";let Jt=Se("clipboard-copy","12px","currentColor",1.5);Jt&&le.appendChild(Jt);let vn=b("span","persona-text-xs");vn.textContent="Copy All",le.appendChild(vn),le.disabled=!1},ve)},Oe=async()=>{if(le){le.disabled=!0;try{let ae;ln()?ae=B:n?(ae=await n(),ae.length===0&&(ae=t.getAll())):ae=t.getAll();let ve=ae.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(ve,null,2)),Xe("check",1500)}catch{Xe("x",1500)}}},Ne=()=>{fe&&(v=fe.value,Dn(),se())},ot=()=>{!ue||!je||(je.style.display=ue.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{w=ue.value,Dn(),se()},150))},St=()=>{!ue||!je||(ue.value="",w="",je.style.display="none",E&&clearTimeout(E),Dn(),se())},Nt=()=>{if(ie)return;let ae=Y.scrollTop,{action:ve,nextLastScrollTop:wt}=ri({following:$.isFollowing(),currentScrollTop:ae,lastScrollTop:we,nearBottom:N(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});we=wt,ve==="resume"?($.resume(),q=0,Ve.style.display="none"):ve==="pause"&&($.pause(),d&&(Q.textContent=u,Ve.style.display=""))},jt=ae=>{let ve=si({following:$.isFollowing(),deltaY:ae.deltaY,nearBottom:N(),resumeWhenNearBottom:!0});ve==="pause"?($.pause(),d&&(Q.textContent=u,Ve.style.display="")):ve==="resume"&&($.resume(),q=0,Ve.style.display="none")},K=()=>{d&&(Y.scrollTop=Y.scrollHeight,$.resume(),q=0,Ve.style.display="none")},gt=ae=>{let ve=ae.target;if(!ve||ve.closest("button"))return;let wt=ve.closest("[data-event-id]");if(!wt)return;let _t=wt.getAttribute("data-event-id");_t&&Jn(_t)},nt=ae=>{if((ae.metaKey||ae.ctrlKey)&&ae.key==="f"){ae.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}ae.key==="Escape"&&(ue&&document.activeElement===ue?(St(),ue.blur(),D.focus()):o&&o())};le&&le.addEventListener("click",Oe),fe&&fe.addEventListener("change",Ne),ue&&ue.addEventListener("input",ot),je&&je.addEventListener("click",St),Y.addEventListener("scroll",Nt),Y.addEventListener("wheel",jt,{passive:!0}),Y.addEventListener("click",gt),Ve.addEventListener("click",K),D.addEventListener("keydown",nt);function $t(){E&&clearTimeout(E),be!==null&&(cancelAnimationFrame(be),be=null),re=!1,ye.clear(),le&&le.removeEventListener("click",Oe),fe&&fe.removeEventListener("change",Ne),ue&&ue.removeEventListener("input",ot),je&&je.removeEventListener("click",St),Y.removeEventListener("scroll",Nt),Y.removeEventListener("wheel",jt),Y.removeEventListener("click",gt),Ve.removeEventListener("click",K),D.removeEventListener("keydown",nt)}return{element:D,update:He,destroy:$t}}}function bm(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 ym=(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:()=>bm(e,t)});if(u)return u}return bm(e,t)};var Il=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)})}},Er=new Il;Er.register("PersonaArtifactCard",ym);function $v(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 vm(e,t){var fe,le,ue,je;let n=(le=(fe=e.features)==null?void 0:fe.artifacts)==null?void 0:le.layout,r=((ue=n==null?void 0:n.toolbarPreset)!=null?ue:"default")==="document",s=(je=n==null?void 0:n.panePadding)==null?void 0:je.trim(),a=e.markdown?Na(e.markdown):null,i=_a(e.sanitize),d=j=>{let oe=a?a(j):Ls(j);return i?i(oe):oe},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 j;u(),(j=t.onDismiss)==null||j.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 j;u(),(j=t.onDismiss)==null||j.call(t)});let C="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),W=r?yn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yn({icon:"eye",label:"Rendered view"}),L=r?yn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,w=!!(B&&v&&v.length>0),E=null,S,k=null,F=null;if(r&&(D||B)&&!w){if(S=D?gl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let j=Se("chevron-down",14,"currentColor",2);j&&S.appendChild(j)}}else r&&w?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?gl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yn({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"}}),E.append(S,k)):r?S=yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=yn({icon:"copy",label:"Copy"});let $=r?yn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yn({icon:"refresh-cw",label:"Refresh"}),q=r?yn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yn({icon:"x",label:"Close"}),me=()=>{var ge,ce,_e;let j=(ge=ye.find(Le=>Le.id===Z))!=null?ge:ye[ye.length-1],oe=(ce=j==null?void 0:j.id)!=null?ce:null,Re=(j==null?void 0:j.artifactType)==="markdown"&&(_e=j.markdown)!=null?_e:"",tt=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:Re,jsonPayload:tt,id:oe}},re=async()=>{var ge;let{markdown:j,jsonPayload:oe}=me(),Re=(ge=ye.find(ce=>ce.id===Z))!=null?ge:ye[ye.length-1],tt=(Re==null?void 0:Re.artifactType)==="markdown"?j:Re?oe:"";try{await navigator.clipboard.writeText(tt)}catch{}};if(S.addEventListener("click",async()=>{let j=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(j&&w){let{markdown:oe,jsonPayload:Re,id:tt}=me();try{await j({actionId:"primary",artifactId:tt,markdown:oe,jsonPayload:Re})}catch{}return}await re()}),k&&(v!=null&&v.length)){let j=()=>{var Re;return(Re=p.closest("[data-persona-root]"))!=null?Re:document.body},oe=()=>{F=jr({items:v.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:tt,jsonPayload:ge,id:ce}=me(),_e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:Re,artifactId:ce,markdown:tt,jsonPayload:ge}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(tt):Re==="json"||Re==="source"?await navigator.clipboard.writeText(ge):await navigator.clipboard.writeText(tt||ge)}catch{}},anchor:E!=null?E:k,position:"bottom-right",portal:j()})};p.isConnected?oe():requestAnimationFrame(oe),k.addEventListener("click",Re=>{Re.stopPropagation(),F==null||F.toggle()})}$.addEventListener("click",async()=>{var j;try{await((j=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:j.call(n))}catch{}X()}),q.addEventListener("click",()=>{var j;u(),(j=t.onDismiss)==null||j.call(t)});let be=()=>{r&&(W.setAttribute("aria-pressed",C==="rendered"?"true":"false"),L.setAttribute("aria-pressed",C==="source"?"true":"false"))};W.addEventListener("click",()=>{C="rendered",be(),X()}),L.addEventListener("click",()=>{C="source",be(),X()});let ie=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(),M.append(W,L),E?H.append(E,$,q):H.append(S,$,q),f.append(M,ie,H),be()):(f.appendChild(g),f.appendChild(x)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let we=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"),We=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(we.style.paddingLeft=s,we.style.paddingRight=s,We.style.padding=s),p.appendChild(f),p.appendChild(we),p.appendChild(We);let ye=[],Z=null,Ee=!1,X=()=>{var tt,ge,ce,_e;let j=r&&ye.length<=1;we.classList.toggle("persona-hidden",j),we.replaceChildren();for(let Le of ye){let de=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");de.type="button",de.textContent=Le.title||Le.id.slice(0,8),Le.id===Z&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>t.onSelect(Le.id)),we.appendChild(de)}We.replaceChildren();let oe=Z&&ye.find(Le=>Le.id===Z)||ye[ye.length-1];if(!oe)return;if(r){let Le=oe.artifactType==="markdown"?"MD":(tt=oe.component)!=null?tt:"Component",Y=(oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${Y} \xB7 ${Le}`}else g.textContent="Artifacts";if(oe.artifactType==="markdown"){if(r&&C==="source"){let de=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(ge=oe.markdown)!=null?ge:"",We.appendChild(de);return}let Le=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Le.innerHTML=d((ce=oe.markdown)!=null?ce:""),We.appendChild(Le);return}let Re=oe.component?Er.get(oe.component):void 0;if(Re){let de={message:{id:oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=Re((_e=oe.props)!=null?_e:{},de);if(Y){We.appendChild(Y);return}}catch{}}We.appendChild($v(oe))},Ae=()=>{var oe;let j=ye.length>0;if(p.classList.toggle("persona-hidden",!j),l){let Re=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,ge=((oe=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&ge&&Ee?(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(j){var oe,Re,tt;ye=j.artifacts,Z=(tt=(Re=j.selectedId)!=null?Re:(oe=j.artifacts[j.artifacts.length-1])==null?void 0:oe.id)!=null?tt:null,ye.length>0&&(Ee=!0),X(),Ae()},setMobileOpen(j){Ee=j,!j&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):Ae()}}}function co(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 xm(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"),!co(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 Uv(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 Ai(e,t){var d,l,u,p,f,g,x,C,M,W;if(!co(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"),Uv(e),xm(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=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.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"),xm(e,t)}var wm=["panel","seamless"];function Ti(e,t){var i,d,l,u,p,f;for(let g of wm)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"),!co(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=wm.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 Cm(e,t){var n,o,r;return!t||!co(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function zv(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 qv(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 jv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Kv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Sm(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 Am(e,t,n,o,r,s){let a=zv(r,200),i=Kv(t,n,o,200);i=Math.max(a,i);let d=qv(s);return d!==null&&(i=Math.min(i,d)),jv(e,a,i)}var Tm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Rl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var x,C,M;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(C=Tm[a])!=null?C:Tm.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,w;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${W.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=W.label,L.appendChild(H);let D=(v=W.type)!=null?v:"text",B;D==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=D),B.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",B.id=`${t.id}-${a}-${W.name}`,B.name=W.name,B.placeholder=(w=W.placeholder)!=null?w:"",W.required&&(B.required=!0),L.appendChild(B),u.appendChild(L)});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=(M=i.submitLabel)!=null?M:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),s.replaceChildren(d,u),u.addEventListener("submit",async W=>{var B,v;W.preventDefault();let L=(B=n.formEndpoint)!=null?B:"/form",H=new FormData(u),D={};H.forEach((w,E)=>{D[E]=w}),D.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let w=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!w.ok)throw new Error(`Form submission failed (${w.status})`);let E=await w.json();f.textContent=(v=E.message)!=null?v:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(w){f.textContent=w instanceof Error?w.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Pl=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()}},Wl=new Pl;var km=()=>{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 Gv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Yv=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},Hl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Gv(e),n=Yv(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}},Bl=e=>typeof e=="string"?e:e==null?"":String(e),Js={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Bl(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:Bl(n.text)}}},Em=e=>Array.isArray(e)?e.map(t=>String(t)):[],Dl=e=>{let t=new Set(Em(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Em(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 Xv=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}},Qv=e=>e.map(t=>({...t,streaming:!1})),Jv=e=>e.map(t=>({...t,status:"complete"})),Mm=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Xv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Qv(n.messages):void 0,artifacts:n.artifacts?Jv(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)}}}};import{parse as j0,STR as K0,OBJ as G0}from"partial-json";function Lm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Er.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 Im(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 Rm(e){let t=Im(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 Pm(e){let t=Im(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 Zv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Wm(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=Zv}=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 M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let W=[];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=`
26
+ `):""},qy=(e,t)=>{var p,m,f,u,w;let n=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,r=(m=o==null?void 0:o.collapsedMode)!=null?m:"tool-call",s=zy(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Au(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},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=al(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=al(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},em=(e,t,n)=>{var p;let o=Gr.has(e),r=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",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 m=r.toggleTextColor||r.headerTextColor||"currentColor",f=Te(o?"chevron-up":"chevron-down",16,m,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")},xl=(e,t)=>{var $,j,me,se,ge,ie,be,Fe,ve;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},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=(me=(j=t==null?void 0:t.features)==null?void 0:j.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Gr.has(e.id),{summary:d,previewText:l,isActive:p}=qy(e,t),m=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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(u.style.color=o.headerTextColor);let w=String((se=n.startedAt)!=null?se:Date.now()),C=()=>{let J=b("span","");return J.setAttribute("data-tool-elapsed",w),J.textContent=Rs(n),J},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ge=s.collapsedMode)!=null?ge:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Rs(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,f.appendChild(u)):M instanceof HTMLElement?f.appendChild(M):(u.textContent=d,f.appendChild(u));let I=(be=s.loadingAnimation)!=null?be:"none",R=o.activeTextTemplate,H=o.completeTextTemplate,D=p?R:H,B=M instanceof HTMLElement,v=(J,Le,Y)=>{let xe=Y;for(let Se of Le){let de=b("span","persona-tool-char");de.style.setProperty("--char-index",String(xe)),de.textContent=Se===" "?"\xA0":Se,J.appendChild(de),xe++}return xe},x=(J,Le)=>{var de;u.textContent="";let Y=((de=n.name)==null?void 0:de.trim())||"tool",xe=ja(J,Y),Se=0;for(let we of xe){let Ue=we.styles.length>0?(()=>{let te=b("span",we.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(te),te})():u;if(we.isDuration&&p)Ue.appendChild(C());else{let te=we.isDuration?Rs(n):we.text;Le?Se=v(Ue,te,Se):Ue.appendChild(document.createTextNode(te))}}};if(!B)if(p&&I!=="none"){let J=(Fe=o.loadingAnimationDuration)!=null?Fe:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${J}ms`),D&&x(D,!1);else if(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${J}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let Le=u.textContent||d;u.textContent="",v(u,Le,0)}}else D&&x(D,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let J=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,J,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show";let Y=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(k),m.append(f,Y)}else m.append(f);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let J=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Uy(S,J)||(S.textContent=l),S.style.display=""}if(!i&&p&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(m,S),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 J=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?J.style.color=o.contentTextColor:o.headerTextColor&&(J.style.color=o.headerTextColor),J.textContent=n.name,E.appendChild(J)}if(n.args!==void 0){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Arguments";let Y=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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=qr(n.args),J.append(Le,Y),E.appendChild(J)}if(n.chunks&&n.chunks.length){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Activity";let Y=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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=n.chunks.join(""),J.append(Le,Y),E.appendChild(J)}if(n.status==="complete"&&n.result!==void 0){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Result";let Y=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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=qr(n.result),J.append(Le,Y),E.appendChild(J)}if(n.status==="complete"&&typeof n.duration=="number"){let J=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(J.style.color=o.contentTextColor),J.textContent=`Duration: ${n.duration}ms`,E.appendChild(J)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let J=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,J,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show"}E.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(m,S,E),r};import{parse as jy,ARR as Ky,OBJ as Gy,STR as Yy}from"partial-json";var Xy="ask_user_question",wl=8,Yr="data-persona-ask-sheet-for",Qy="Other",Jy="Other\u2026",nm="Type your own answer here",om="Send",Zy="Next",ev="Back",tv="Submit all",nv="Skip",ov=3,Cl="data-ask-current-index",Sl="data-ask-question-count",rm="data-ask-answers",Al="data-ask-grouped",sm="data-ask-layout",rv=e=>e.layout==="pills"?"pills":"rows",sv=e=>e.getAttribute(sm)==="pills"?"pills":"rows",tm=!1,am=e=>e.replace(/["\\]/g,"\\$&"),Tr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xy,Tl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=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=jy(r,Yy|Gy|Ky);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>wl&&!tm&&(tm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${wl}.`)),t.slice(0,wl)},av=e=>{var t;return(t=Gs(e)[0])!=null?t:null},iv=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},lv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},im=(e,t,n)=>{if(e!=="rows")return null;let 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},cv=(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=im(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},dv=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},pv=(e,t,n,o)=>{var p,m,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(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<ov;u++)s.appendChild(dv(o));return s}if(d.forEach((u,w)=>{s.appendChild(cv(u,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?Qy:Jy;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 C=b("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(p=t.freeTextPlaceholder)!=null?p:nm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),C.appendChild(M),w.appendChild(C);let I=im(o,a,d.length);I&&w.appendChild(I),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=(f=t.freeTextLabel)!=null?f:u,s.appendChild(w)}}return s},lm=(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:nm,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:om,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},uv=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:om,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},mv=(e,t,n)=>{var l,p,m,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:ev,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=(p=n.skipLabel)!=null?p:nv,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?(m=n.submitAllLabel)!=null?m:tv:(f=n.nextLabel)!=null?f:Zy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},kr=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(Cl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gv=(e,t)=>{e.setAttribute(Cl,String(Math.max(0,Math.floor(t))))},Qr=e=>{var n;let t=Number((n=e.getAttribute(Sl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},sr=e=>e.getAttribute(Al)==="true",fv=(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},hv=(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)))},wi=(e,t)=>{let{payload:n}=Xr(t),o=Gs(n),r=kr(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},dm=e=>{let t=kr(e),n=lo(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 m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=r.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof 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=""},pm=e=>{if(!sr(e))return;let t=kr(e),n=lo(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}},kl=(e,t,n)=>{let o=Tl(n),r=sv(e),{payload:s,complete:a}=Xr(t),i=sr(e),d=lo(e),l=Qr(e),p=i?iv(s,d):av(s),m=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let R=typeof(p==null?void 0:p.question)=="string"?p.question:"";w.textContent=R,w.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let R=pv(p,o,a,r);C.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(lm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!M?e.appendChild(uv(o)):(!m||i)&&M&&M.remove(),e.setAttribute("data-multi-select",m?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=mv(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();dm(e),pm(e)},bv=(e,t,n)=>{let o=Tl(t),r=rv(o),s=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=fv(e,a),p=d?hv(e,i):0,m=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Yr,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(Sl,String(i)),m.setAttribute(Cl,String(p)),m.setAttribute(Al,d?"true":"false"),m.setAttribute(sm,r),cm(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),lv(m,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",f.appendChild(u);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",f.appendChild(w),m.appendChild(f);let M=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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),r!=="rows"&&m.appendChild(lm(o,r)),kl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},yv=(e,t,n)=>{let{payload:o}=Xr(t),r=Math.max(1,Gs(o).length);r>Qr(e)&&(e.setAttribute(Sl,String(r)),r>1&&!sr(e)&&e.setAttribute(Al,"true")),kl(e,t,n)};var Ci=(e,t,n)=>{if(!n||!Tr(e)||Tl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Yr}]`).forEach(l=>{l.getAttribute(Yr)!==r&&l.remove()});let a=n.querySelector(`[${Yr}="${am(r)}"]`);if(a){yv(a,e,t);return}let{payload:i}=Xr(e),d=bv(e,t,i);n.appendChild(d)},Jr=(e,t)=>{if(!e)return;let n=t?`[${Yr}="${am(t)}"]`:`[${Yr}]`;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)})},El=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),ar=(e,t)=>{let n=kr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,cm(e,n),dm(e),pm(e)},Si=(e,t,n,o)=>{let r=Qr(e),s=Math.max(0,Math.min(r-1,o));gv(e,s),kl(e,t,n)};var Ml=(e,t)=>{var C,M,I,R,H,D,B,v,x,k,S,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=(M=o==null?void 0:o.borderColor)!=null?M:"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)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",p=Te(d,20,l,2);p&&i.appendChild(p);let m=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(u.style.color=o.titleColor),u.textContent=(R=o==null?void 0:o.title)!=null?R:"Approval Required",f.appendChild(u),!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"),f.appendChild(F)}m.appendChild(f);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,m.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=qr(n.parameters),m.appendChild(F)}if(r){let F=b("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let $=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");$.type="button",$.style.backgroundColor=(H=o==null?void 0:o.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",$.style.color=(D=o==null?void 0:o.approveButtonTextColor)!=null?D:"#ffffff",$.setAttribute("data-approval-action","approve");let j=Te("shield-check",14,(B=o==null?void 0:o.approveButtonTextColor)!=null?B:"#ffffff",2);j&&(j.style.marginRight="4px",$.appendChild(j));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);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=(x=o==null?void 0:o.denyButtonColor)!=null?x:"transparent",se.style.color=(k=o==null?void 0:o.denyButtonTextColor)!=null?k:"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 ge=Te("shield-x",14,(S=o==null?void 0:o.denyButtonTextColor)!=null?S:"var(--persona-feedback-error, #dc2626)",2);ge&&(ge.style.marginRight="4px",se.appendChild(ge));let ie=document.createTextNode((E=o==null?void 0:o.denyLabel)!=null?E:"Deny");se.appendChild(ie),F.append($,se),m.appendChild(F)}return a.append(i,m),s.appendChild(a),s};var um=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(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=r?r.isStreaming():!1,f=u=>{switch(u){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(u=>{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=u,w.disabled=m,i!=null&&i.fontFamily&&(w.style.fontFamily=f(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(u))}),p.appendChild(w),t.push(w)}),e.appendChild(p)}}};var Ys=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 Xs=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 vv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),xv=new Set(["step_start","execution_start"]),wv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cv=new Set(["step_complete","agent_turn_complete"]),Sv=new Set(["flow_complete","agent_complete"]),mm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),fm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Er=(e,t)=>{let n=e[t];return fm(n)?n:void 0};function Ll(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ai(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Av(e,t){return typeof t.type=="string"?t.type:e}function Tv(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 kv(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 gm(e){var o,r,s,a,i;let t=Er(e,"result"),n=[Er(e,"tokens"),Er(e,"totalTokens"),t?Er(t,"tokens"):void 0,Er(e,"usage"),t?Er(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Qn(d.output))!=null?o:Qn(d.outputTokens))!=null?r:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function Ev(e){var n,o,r,s,a;let t=Er(e,"result");return(a=(r=(o=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?o:Qn(e.execution_time))!=null?r:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function Mv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=Mv){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:Ai(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(!fm(n)){mm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Av(t,n),r=this.now();if(vv.has(o)){this.startRun(r);return}if(xv.has(o)){this.run||this.startRun(r);return}if(wv.has(o)){if(!kv(o,n))return;let a=Tv(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+Ll(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ai(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cv.has(o)){if(!this.run)return;let a=this.run,i=gm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ll(a.visibleCharCount),p=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ai(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Sv.has(o)){if(!this.run)return;let a=this.run,i=gm(n),d=i!=null?i:a.exactOutputTokens+Ll(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ai(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(mm.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=Ev(n);return s!=null?s:o-t.startedAt}};function Zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Lv={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)"}},Iv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Rv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Pv=100;function Wv(e,t){let n={...Lv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Iv}function Bv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Hv(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 Dv(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 Fv(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 Ov(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 Nv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function _v(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 Vv(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 Il(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");Zr(l,(f=o.classNames)==null?void 0:f.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var $,j;let u=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 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"),M=Te(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&C.appendChild(M);let I=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=($=o.timestampFormat)!=null?$:"relative";I.textContent=R==="relative"?Bv(e.timestamp,n):Hv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let D=Wv(e.type,o.badgeColors),B=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");B.style.backgroundColor=D.bg,B.style.color=D.text,B.style.borderColor=D.text+"50",B.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Rv,x=Dv(e.payload,v),k=null;x&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=x);let S=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=Te("clipboard","12px","currentColor",1.5);return F&&E.appendChild(F),E.addEventListener("click",async me=>{me.stopPropagation(),await Fv(Ov(e)),E.innerHTML="";let se=Te("check","12px","currentColor",1.5);se&&E.appendChild(se),setTimeout(()=>{E.innerHTML="";let ge=Te("clipboard","12px","currentColor",1.5);ge&&E.appendChild(ge)},1500)}),w.appendChild(C),w.appendChild(I),H&&w.appendChild(H),w.appendChild(B),k&&w.appendChild(k),w.appendChild(S),w.appendChild(E),u.appendChild(w),d&&u.appendChild(Vv(e,a,i)),u}}function hm(e){var w,C,M,I,R;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=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",p=(M=i==null?void 0:i.label)!=null?M:"",m=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},f=s.find(H=>H.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let H=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return u();function u(){let H=m.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Zr(D,H==null?void 0:H.panel);let B=[],v="",x="",k=null,S=[],E={},F=0,$=ri(),j=0,me=0,se=!1,ge=null,ie=!1,be=0,Fe=new Set,ve=new Map,J="",Le="",Y=null,xe,Se,de,we,Ue,te=null,ne=null,re=null;function nt(){let oe=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),fe=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");Zr(fe,H==null?void 0:H.headerBar);let xt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(xt.textContent="Events",xe=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"),xe.textContent="0",a){ne=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",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 persona-tabular-nums"),te.textContent="-- tok/s",re=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"),re.style.display="none",re.style.pointerEvents="none";let Zn=ne,vn=re,On=()=>{if(!vn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=oe.getBoundingClientRect();vn.style.left=`${wo.left-Nn.left}px`,vn.style.top=`${wo.bottom-Nn.top+4}px`,vn.style.display="block"},ut=()=>{vn.style.display="none"};ne.addEventListener("mouseenter",On),ne.addEventListener("mouseleave",ut),ne.appendChild(Fn),ne.appendChild(te)}let $t=b("div","persona-flex-1");Se=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 Jt=b("option","");Jt.value="",Jt.textContent="All events",Se.appendChild(Jt),de=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"),de.type="button",de.title="Copy All";let Tt=Te("clipboard-copy","12px","currentColor",1.5);Tt&&de.appendChild(Tt);let wt=b("span","persona-text-xs");wt.textContent="Copy All",de.appendChild(wt),fe.appendChild(xt),fe.appendChild(xe),ne&&fe.appendChild(ne),fe.appendChild($t),fe.appendChild(Se),fe.appendChild(de);let ft=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Zr(ft,H==null?void 0:H.searchBar);let bt=Te("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");bt&&zt.appendChild(bt),we=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"),Zr(we,H==null?void 0:H.searchInput),we.type="text",we.placeholder="Search event payloads...",Ue=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"),Ue.type="button",Ue.style.display="none";let et=Te("x","12px","currentColor",2);return et&&Ue.appendChild(et),ft.appendChild(zt),ft.appendChild(we),ft.appendChild(Ue),oe.appendChild(fe),oe.appendChild(ft),re&&oe.appendChild(re),oe}let ye,le=s.find(oe=>oe.renderEventStreamToolbar);if(le!=null&&le.renderEventStreamToolbar&&r){let oe=le.renderEventStreamToolbar({config:r,defaultRenderer:()=>nt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:fe=>{v=fe,Dn(),_()},onSearchChange:fe=>{x=fe,Dn(),_()}});ye=oe!=null?oe:nt()}else ye=nt();let $e=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");$e.style.display="none";function Be(){if(!a||!te||!ne)return;let oe=a();te.textContent=Nv(oe);let fe=_v(oe);re&&(re.textContent=fe,fe||(re.style.display="none")),fe?ne.setAttribute("aria-label",fe):ne.removeAttribute("aria-label")}let ce=b("div","persona-flex-1 persona-min-h-0 persona-relative"),K=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");K.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");Zr(_e,H==null?void 0:H.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Et=Te(l,"14px","currentColor",2);Et&&_e.appendChild(Et);let pe=b("span","");pe.textContent=p,_e.appendChild(pe);let ae=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(K),ce.appendChild(ae),ce.appendChild(_e),D.setAttribute("tabindex","0"),D.appendChild(ye),D.appendChild($e),D.appendChild(ce);function Ln(){let oe=t.getAll(),fe={};for(let wt of oe)fe[wt.type]=(fe[wt.type]||0)+1;let xt=Object.keys(fe).sort(),$t=xt.length!==S.length||!xt.every((wt,ft)=>wt===S[ft]),Jt=!$t&&xt.some(wt=>fe[wt]!==E[wt]),yn=oe.length!==Object.values(E).reduce((wt,ft)=>wt+ft,0);if(!$t&&!Jt&&!yn||(S=xt,E=fe,!Se))return;let Tt=Se.value;if(Se.options[0].textContent="All events",$t){for(;Se.options.length>1;)Se.remove(1);for(let wt of xt){let ft=b("option","");ft.value=wt,ft.textContent=`${wt} (${fe[wt]||0})`,Se.appendChild(ft)}Tt&&xt.includes(Tt)?Se.value=Tt:Tt&&(Se.value="",v="")}else for(let wt=1;wt<Se.options.length;wt++){let ft=Se.options[wt];ft.textContent=`${ft.value} (${fe[ft.value]||0})`}}function Nt(){let oe=t.getAll();if(v&&(oe=oe.filter(fe=>fe.type===v)),x){let fe=x.toLowerCase();oe=oe.filter(xt=>xt.type.toLowerCase().includes(fe)||xt.payload.toLowerCase().includes(fe))}return oe}function ln(){return v!==""||x!==""}function Dn(){F=0,j=0,$.resume(),_e.style.display="none"}function Jn(oe){Fe.has(oe)?Fe.delete(oe):Fe.add(oe),Y=oe;let fe=K.scrollTop,xt=$.isFollowing();ie=!0,$.pause(),_(),K.scrollTop=fe,xt&&$.resume(),ie=!1}function ze(){return Os(K,50)}function _(){me=Date.now(),se=!1,Be(),Ln();let oe=t.getEvictedCount();oe>0?($e.textContent=`${oe.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",B=Nt();let fe=B.length,xt=t.getSize()>0;xe&&(xe.textContent=String(t.getSize())),fe===0&&xt&&ln()?(ae.textContent=x?`No events matching '${x}'`:"No events matching filter",ae.style.display="",K.style.display="none"):(ae.style.display="none",K.style.display=""),de&&(de.title=ln()?`Copy Filtered (${fe})`:"Copy All"),d&&!$.isFollowing()&&fe>F&&(j+=fe-F,pe.textContent=p?`${p}${j>0?` (${j})`:""}`:"",_e.style.display=""),F=fe;let $t=t.getAll(),Jt=$t.length>0?$t[0].timestamp:0,yn=new Set(B.map(ft=>ft.id));for(let ft of Fe)yn.has(ft)||Fe.delete(ft);let Tt=v!==J||x!==Le,wt=ve.size===0&&B.length>0;if(Tt||wt||B.length===0){K.innerHTML="",ve.clear();let ft=document.createDocumentFragment();for(let bt=0;bt<B.length;bt++){let zt=Il(B[bt],bt,Jt,m,Fe,Jn,s,r);ve.set(B[bt].id,zt),ft.appendChild(zt)}K.appendChild(ft),J=v,Le=x,Y=null}else{if(Y!==null){let bt=ve.get(Y);if(bt&&bt.parentNode===K){let zt=B.findIndex(et=>et.id===Y);if(zt>=0){let et=Il(B[zt],zt,Jt,m,Fe,Jn,s,r);K.insertBefore(et,bt),bt.remove(),ve.set(Y,et)}}Y=null}let ft=new Set(B.map(bt=>bt.id));for(let[bt,zt]of ve)ft.has(bt)||(zt.remove(),ve.delete(bt));for(let bt=0;bt<B.length;bt++){let zt=B[bt];if(!ve.has(zt.id)){let et=Il(zt,bt,Jt,m,Fe,Jn,s,r);ve.set(zt.id,et),K.appendChild(et)}}}$.isFollowing()&&(K.scrollTop=K.scrollHeight)}function ke(){if(Date.now()-me>=Pv){ge!==null&&(cancelAnimationFrame(ge),ge=null),_();return}se||(se=!0,ge=requestAnimationFrame(()=>{ge=null,_()}))}let He=(oe,fe)=>{if(!de)return;de.innerHTML="";let xt=Te(oe,"12px","currentColor",1.5);xt&&de.appendChild(xt);let $t=b("span","persona-text-xs");$t.textContent="Copy All",de.appendChild($t),setTimeout(()=>{de.innerHTML="";let Jt=Te("clipboard-copy","12px","currentColor",1.5);Jt&&de.appendChild(Jt);let yn=b("span","persona-text-xs");yn.textContent="Copy All",de.appendChild(yn),de.disabled=!1},fe)},De=async()=>{if(de){de.disabled=!0;try{let oe;ln()?oe=B:n?(oe=await n(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let fe=oe.map(xt=>{try{return JSON.parse(xt.payload)}catch{return xt.payload}});await navigator.clipboard.writeText(JSON.stringify(fe,null,2)),He("check",1500)}catch{He("x",1500)}}},Ve=()=>{Se&&(v=Se.value,Dn(),_())},dt=()=>{!we||!Ue||(Ue.style.display=we.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=we.value,Dn(),_()},150))},ot=()=>{!we||!Ue||(we.value="",x="",Ue.style.display="none",k&&clearTimeout(k),Dn(),_())},At=()=>{if(ie)return;let oe=K.scrollTop,{action:fe,nextLastScrollTop:xt}=si({following:$.isFollowing(),currentScrollTop:oe,lastScrollTop:be,nearBottom:ze(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=xt,fe==="resume"?($.resume(),j=0,_e.style.display="none"):fe==="pause"&&($.pause(),d&&(pe.textContent=p,_e.style.display=""))},Vt=oe=>{let fe=ai({following:$.isFollowing(),deltaY:oe.deltaY,nearBottom:ze(),resumeWhenNearBottom:!0});fe==="pause"?($.pause(),d&&(pe.textContent=p,_e.style.display="")):fe==="resume"&&($.resume(),j=0,_e.style.display="none")},q=()=>{d&&(K.scrollTop=K.scrollHeight,$.resume(),j=0,_e.style.display="none")},_t=oe=>{let fe=oe.target;if(!fe||fe.closest("button"))return;let xt=fe.closest("[data-event-id]");if(!xt)return;let $t=xt.getAttribute("data-event-id");$t&&Jn($t)},Qe=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),we==null||we.focus(),we==null||we.select();return}oe.key==="Escape"&&(we&&document.activeElement===we?(ot(),we.blur(),D.focus()):o&&o())};de&&de.addEventListener("click",De),Se&&Se.addEventListener("change",Ve),we&&we.addEventListener("input",dt),Ue&&Ue.addEventListener("click",ot),K.addEventListener("scroll",At),K.addEventListener("wheel",Vt,{passive:!0}),K.addEventListener("click",_t),_e.addEventListener("click",q),D.addEventListener("keydown",Qe);function Ft(){k&&clearTimeout(k),ge!==null&&(cancelAnimationFrame(ge),ge=null),se=!1,ve.clear(),de&&de.removeEventListener("click",De),Se&&Se.removeEventListener("change",Ve),we&&we.removeEventListener("input",dt),Ue&&Ue.removeEventListener("click",ot),K.removeEventListener("scroll",At),K.removeEventListener("wheel",Vt),K.removeEventListener("click",_t),_e.removeEventListener("click",q),D.removeEventListener("keydown",Qe)}return{element:D,update:ke,destroy:Ft}}}function bm(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 p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",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",m.appendChild(f);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),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 ym=(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",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>bm(e,t)});if(p)return p}return bm(e,t)};var Rl=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)})}},Mr=new Rl;Mr.register("PersonaArtifactCard",ym);function $v(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 vm(e,t){var Se,de,we,Ue;let n=(de=(Se=e.features)==null?void 0:Se.artifacts)==null?void 0:de.layout,r=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",s=(Ue=n==null?void 0:n.panePadding)==null?void 0:Ue.trim(),a=e.markdown?_a(e.markdown):null,i=Va(e.sanitize),d=te=>{let ne=a?a(te):Ls(te);return i?i(ne):ne},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,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),r&&m.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 u=b("span","persona-text-xs persona-font-medium persona-truncate");u.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 te;p(),(te=t.onDismiss)==null||te.call(t)});let C="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?bn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):bn({icon:"eye",label:"Rendered view"}),R=r?bn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):bn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(B&&v&&v.length>0),k=null,S,E=null,F=null;if(r&&(D||B)&&!x){if(S=D?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let te=Te("chevron-down",14,"currentColor",2);te&&S.appendChild(te)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=bn({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"}}),k.append(S,E)):r?S=bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=bn({icon:"copy",label:"Copy"});let $=r?bn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):bn({icon:"refresh-cw",label:"Refresh"}),j=r?bn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):bn({icon:"x",label:"Close"}),me=()=>{var ye,le,$e;let te=(ye=ve.find(Be=>Be.id===J))!=null?ye:ve[ve.length-1],ne=(le=te==null?void 0:te.id)!=null?le:null,re=(te==null?void 0:te.artifactType)==="markdown"&&($e=te.markdown)!=null?$e:"",nt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:re,jsonPayload:nt,id:ne}},se=async()=>{var ye;let{markdown:te,jsonPayload:ne}=me(),re=(ye=ve.find(le=>le.id===J))!=null?ye:ve[ve.length-1],nt=(re==null?void 0:re.artifactType)==="markdown"?te:re?ne:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(S.addEventListener("click",async()=>{let te=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(te&&x){let{markdown:ne,jsonPayload:re,id:nt}=me();try{await te({actionId:"primary",artifactId:nt,markdown:ne,jsonPayload:re})}catch{}return}await se()}),E&&(v!=null&&v.length)){let te=()=>{var re;return(re=m.closest("[data-persona-root]"))!=null?re:document.body},ne=()=>{F=jr({items:v.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:nt,jsonPayload:ye,id:le}=me(),$e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:re,artifactId:le,markdown:nt,jsonPayload:ye}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(nt):re==="json"||re==="source"?await navigator.clipboard.writeText(ye):await navigator.clipboard.writeText(nt||ye)}catch{}},anchor:k!=null?k:E,position:"bottom-right",portal:te()})};m.isConnected?ne():requestAnimationFrame(ne),E.addEventListener("click",re=>{re.stopPropagation(),F==null||F.toggle()})}$.addEventListener("click",async()=>{var te;try{await((te=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:te.call(n))}catch{}Y()}),j.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let ge=()=>{r&&(I.setAttribute("aria-pressed",C==="rendered"?"true":"false"),R.setAttribute("aria-pressed",C==="source"?"true":"false"))};I.addEventListener("click",()=>{C="rendered",ge(),Y()}),R.addEventListener("click",()=>{C="source",ge(),Y()});let ie=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(),M.append(I,R),k?H.append(k,$,j):H.append(S,$,j),f.append(M,ie,H),ge()):(f.appendChild(u),f.appendChild(w)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let be=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"),Fe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,Fe.style.padding=s),m.appendChild(f),m.appendChild(be),m.appendChild(Fe);let ve=[],J=null,Le=!1,Y=()=>{var nt,ye,le,$e;let te=r&&ve.length<=1;be.classList.toggle("persona-hidden",te),be.replaceChildren();for(let Be of ve){let ce=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");ce.type="button",ce.textContent=Be.title||Be.id.slice(0,8),Be.id===J&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(Be.id)),be.appendChild(ce)}Fe.replaceChildren();let ne=J&&ve.find(Be=>Be.id===J)||ve[ve.length-1];if(!ne)return;if(r){let Be=ne.artifactType==="markdown"?"MD":(nt=ne.component)!=null?nt:"Component",K=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${K} \xB7 ${Be}`}else u.textContent="Artifacts";if(ne.artifactType==="markdown"){if(r&&C==="source"){let ce=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ye=ne.markdown)!=null?ye:"",Fe.appendChild(ce);return}let Be=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Be.innerHTML=d((le=ne.markdown)!=null?le:""),Fe.appendChild(Be);return}let re=ne.component?Mr.get(ne.component):void 0;if(re){let ce={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let K=re(($e=ne.props)!=null?$e:{},ce);if(K){Fe.appendChild(K);return}}catch{}}Fe.appendChild($v(ne))},xe=()=>{var ne;let te=ve.length>0;if(m.classList.toggle("persona-hidden",!te),l){let re=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,ye=((ne=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&ye&&Le?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(te){var ne,re,nt;ve=te.artifacts,J=(nt=(re=te.selectedId)!=null?re:(ne=te.artifacts[te.artifacts.length-1])==null?void 0:ne.id)!=null?nt:null,ve.length>0&&(Le=!0),Y(),xe()},setMobileOpen(te){Le=te,!te&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):xe()}}}function co(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 xm(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"),!co(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 Uv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ti(e,t){var d,l,p,m,f,u,w,C,M,I;if(!co(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"),Uv(e),xm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(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=(u=n==null?void 0:n.paneBackground)==null?void 0:u.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=(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=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(I=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:I.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),xm(e,t)}var wm=["panel","seamless"];function ki(e,t){var i,d,l,p,m,f;for(let u of wm)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!co(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=wm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Cm(e,t){var n,o,r;return!t||!co(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function zv(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 qv(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 jv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Kv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Sm(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 Am(e,t,n,o,r,s){let a=zv(r,200),i=Kv(t,n,o,200);i=Math.max(a,i);let d=qv(s);return d!==null&&(i=Math.min(i,d)),jv(e,a,i)}var Tm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Pl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,C,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(C=Tm[a])!=null?C:Tm.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 I=b("p","persona-text-sm persona-text-persona-muted");I.textContent=i.description,d.appendChild(I)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var v,x;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=I.label,R.appendChild(H);let D=(v=I.type)!=null?v:"text",B;D==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=D),B.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",B.id=`${t.id}-${a}-${I.name}`,B.name=I.name,B.placeholder=(x=I.placeholder)!=null?x:"",I.required&&(B.required=!0),R.appendChild(B),p.appendChild(R)});let m=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]"),u=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");u.type="submit",u.textContent=(M=i.submitLabel)!=null?M:"Submit",m.appendChild(f),m.appendChild(u),p.appendChild(m),s.replaceChildren(d,p),p.addEventListener("submit",async I=>{var B,v;I.preventDefault();let R=(B=n.formEndpoint)!=null?B:"/form",H=new FormData(p),D={};H.forEach((x,k)=>{D[k]=x}),D.type=a,u.disabled=!0,f.textContent="Submitting\u2026";try{let x=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let k=await x.json();f.textContent=(v=k.message)!=null?v:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(x){f.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Wl=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()}},Bl=new Wl;var km=()=>{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 Gv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Yv=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},Dl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Gv(e),n=Yv(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}},Hl=e=>typeof e=="string"?e:e==null?"":String(e),Js={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Hl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Hl(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:Hl(n.text)}}},Em=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fl=e=>{let t=new Set(Em(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Em(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,p)=>l||(p==null?void 0:p({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 p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let f=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:f,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Xv=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}},Qv=e=>e.map(t=>({...t,streaming:!1})),Jv=e=>e.map(t=>({...t,status:"complete"})),Mm=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Xv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Qv(n.messages):void 0,artifacts:n.artifacts?Jv(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)}}}};import{parse as j0,STR as K0,OBJ as G0}from"partial-json";function Lm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Mr.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 Im(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 Rm(e){let t=Im(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 Pm(e){let t=Im(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 Zv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Wm(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=Zv}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,u.appendChild(w);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,u.appendChild(C),f.appendChild(u);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let I=[];for(let v=1;v<=5;v++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),x.title=l[v-1],x.dataset.rating=String(v),x.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
29
29
  </svg>
30
- `,w.addEventListener("click",()=>{p=v,W.forEach((E,S)=>{let k=S<v;E.classList.toggle("selected",k),E.setAttribute("aria-checked",S===v-1?"true":"false")})}),W.push(w),M.appendChild(w)}f.appendChild(M);let L=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),v.appendChild(L),f.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),u.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(p===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let v=(L==null?void 0:L.value.trim())||void 0;await t(p,v),u.remove()}catch(v){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(B),f.appendChild(H),u.appendChild(f),u}function Bm(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 M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,x.appendChild(M),g.appendChild(x);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 L=document.createElement("div");L.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=u,L.appendChild(H),L.appendChild(D);let B=document.createElement("div");B.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=F,v.forEach((q,me)=>{q.classList.toggle("selected",me===F),q.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),B.appendChild($)}W.appendChild(L),W.appendChild(B),g.appendChild(W);let w=null;if(d){let F=document.createElement("div");F.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"),F.appendChild(w),g.appendChild(F)}let E=document.createElement("div");E.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let F=(w==null?void 0:w.value.trim())||void 0;await t(f,F),p.remove()}catch(F){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),E.appendChild(S),E.appendChild(k),g.appendChild(E),p.appendChild(g),p}var es="persona-chat-history",ex=30*1e3,tx={"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 nx(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=tx[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 ki(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 ox(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 rx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Fl=e=>!e||typeof e!="object"?{}:{...e},Hm=e=>e.map(t=>({...t,streaming:!1})),Dm=(e,t,n)=>{let o=e!=null&&e.markdown?Na(e.markdown):null,r=_a(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=Ls(a),r?r(d):d}};function Fm(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=Se(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 Om=(e,t,n)=>{var sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Qp(t),r=Wl.getForInstance(o.plugins);o.components&&Er.registerAll(o.components);let s=km(),i=o.persistState===!1?null:(sc=o.storageAdapter)!=null?sc:Mm(),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=Fl(h.metadata)),(ac=h.messages)!=null&&ac.length&&(o={...o,initialMessages:h.messages}),(ic=h.artifacts)!=null&&ic.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(lc=h.selectedArtifactId)!=null?lc: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:{}});(cc=c.messages)!=null&&cc.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:{},Pr()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hl],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick],M=Dl({parsers:x,handlers:C,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let W=(pc=(dc=o.launcher)==null?void 0:dc.enabled)!=null?pc:!0,L=(mc=(uc=o.launcher)==null?void 0:uc.autoExpand)!=null?mc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=L,B=W,v=(hc=(fc=o.layout)==null?void 0:fc.header)==null?void 0:hc.layout,w=!1,E=()=>zs(o),S=()=>W||E(),k=E()?!1:W?L:!0,F=!1,$=null,q=()=>{F=!0,$&&clearTimeout($),$=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},me=Dm(o,M,q),re=(yc=(bc=o.features)==null?void 0:bc.showReasoning)!=null?yc:!0,be=(xc=(vc=o.features)==null?void 0:vc.showToolCalls)!=null?xc:!0,ie=(Cc=(wc=o.features)==null?void 0:wc.showEventStreamToggle)!=null?Cc:!1,we=(Ac=(Sc=o.features)==null?void 0:Sc.scrollToBottom)!=null?Ac:{},ye=`${(kc=typeof o.persistState=="object"?(Tc=o.persistState)==null?void 0:Tc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,Z=ie?new Xs(ye):null,Ee=(Lc=(Mc=(Ec=o.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.maxEvents)!=null?Lc:2e3,X=ie?new Ys(Ee,Z):null,Ae=ie?new Qs:null,fe=null,le=!1,ue=null,je=0;Z==null||Z.open().then(()=>X==null?void 0:X.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let j={onCopy:c=>{var m,h;s.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.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),T!=null&&T.isClientTokenMode()&&T.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)}},oe=(Ic=o.statusIndicator)!=null?Ic:{},Re=c=>{var m,h,y,P;return c==="idle"?(m=oe.idleText)!=null?m:hn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:hn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:hn.connected:c==="error"?(P=oe.errorText)!=null?P:hn.error:hn[c]};function tt(c,m,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=m,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=m}let{wrapper:ge,panel:ce,pillRoot:_e}=Yu(o),Le=Xu(o,S()),{container:de,body:Y,messagesWrapper:Ve,suggestions:Ct,textarea:Q,sendButton:Fe,sendButtonWrapper:Ln,composerForm:Ft,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:N,iconHolder:se,headerTitle:He,headerSubtitle:Xe,header:Oe,footer:Ne,actionsRow:ot,leftActions:St,rightActions:Nt}=Le,jt=Le.setSendButtonMode,K=Le.micButton,gt=Le.micButtonWrapper,nt=Le.attachmentButton,$t=Le.attachmentButtonWrapper,ae=Le.attachmentInput,ve=Le.attachmentPreviewsContainer;de.classList.add("persona-relative"),Y.classList.add("persona-relative");let wt=12,_t=()=>{var c;return(c=we.label)!=null?c:""},Jt=()=>{var c;return(c=we.iconName)!=null?c:"arrow-down"},vn=()=>we.enabled!==!1,Et=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");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let At=b("span","persona-flex persona-items-center"),ht=b("span","");Et.append(At,ht),de.appendChild(Et);let yt=()=>{let m=Ne.style.display==="none"?0:Ne.offsetHeight;Et.style.bottom=`${m+wt}px`};yt();let Ut=()=>{let c=!!_t();Et.setAttribute("aria-label",_t()||"Jump to latest"),Et.title=_t(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),At.innerHTML="";let m=Se(Jt(),"14px","currentColor",2);m?(At.appendChild(m),At.style.display=""):At.style.display="none",ht.textContent=_t(),ht.style.display=c?"":"none"};Ut();let Ze=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let m=Sr({config:o,showClose:S()});return js(de,m,o),m.header},onClose:()=>Bt(!1,"user")});if(c){let m=de.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Oe=c)}}let xn=()=>{var m,h,y,P;if(!X)return;if(le=!0,!fe&&X&&(fe=hm({buffer:X,getFullHistory:()=>X.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var _;return(_=Ae==null?void 0:Ae.getMetric())!=null?_:{status:"idle"}}})),fe&&(Y.style.display="none",(m=Ne.parentNode)==null||m.insertBefore(fe.element,Ne),fe.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.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(V=>V&&ut.classList.add(V))}let c=()=>{if(!le)return;let _=Date.now();_-je>=200&&(fe==null||fe.update(),je=_),ue=requestAnimationFrame(c)};je=0,ue=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,m,h;if(le){if(le=!1,fe&&fe.element.remove(),Y.style.display="",ut){ut.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(P=>P&&ut.classList.remove(P))}ue!==null&&(cancelAnimationFrame(ue),ue=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Pc=(Rc=o.features)==null?void 0:Rc.eventStream)==null?void 0:Pc.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:"");ut=b("button",m),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=Se("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=Le.clearChatButtonWrapper,P=Le.closeButtonWrapper,_=y||P;_&&_.parentNode===Oe?Oe.insertBefore(ut,_):Oe.appendChild(ut),ut.addEventListener("click",()=>{le?On():xn()})}let wo=c=>{var y,P,_;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 V=c.querySelector("[data-persona-composer-form]");V!=null&&V.parentNode?V.parentNode.insertBefore(h,V):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let V=b("input");V.type="file",V.accept=((y=m.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=m.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(_=m.buttonTooltipText)!=null?_:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,m=Nn.renderComposer({config:o,defaultRenderer:()=>vi({config:o}).footer,onSubmit:h=>{var V;if(!T||T.isStreaming())return;let y=h.trim(),P=(V=Ze==null?void 0:Ze.hasAttachments())!=null?V:!1;if(!y&&!P)return;gs();let _;P&&(_=[],_.push(...Ze.getContentParts()),y&&_.push(il(y))),T.sendMessage(y,{contentParts:_}),P&&Ze.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ae==null||ae.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Wc=o.voiceRecognition)==null?void 0:Wc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});m&&(Ne.replaceWith(m),Ne=m)}let ar=c=>{let m=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]");m&&(Ft=m),h&&(Q=h),y&&(Fe=y),P&&(K=P,gt=P.parentElement),_&&(ln=_);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Ct=V);let z=c.querySelector(".persona-attachment-button");z&&(nt=z,$t=z.parentElement),ae=c.querySelector('input[type="file"]'),ve=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(ot=O)};wo(Ne),ar(Ne);let In=(Oc=(Bc=o.layout)==null?void 0:Bc.contentMaxWidth)!=null?Oc:E()?(Fc=(Dc=(Hc=o.launcher)==null?void 0:Hc.composerBar)==null?void 0:Dc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&(Ve.style.maxWidth=In,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),In&&Ft&&!E()&&(Ft.style.maxWidth=In,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),In&&Ct&&!E()&&(Ct.style.maxWidth=In,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),In&&ve&&!E()&&(ve.style.maxWidth=In,ve.style.marginLeft="auto",ve.style.marginRight="auto"),(Nc=o.attachments)!=null&&Nc.enabled&&ae&&ve){Ze=Ds.fromConfig(o.attachments),Ze.setPreviewsContainer(ve),ae.addEventListener("change",h=>{let y=h.target;Ze==null||Ze.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,m=Fm(c);de.appendChild(m)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},m=_=>{switch(_){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Ct;case"composer":return Ft;case"footer-bottom":return ln;default:return null}},h=(_,V)=>{var z;switch(_){case"header-left":case"header-center":case"header-right":if(_==="header-left")Oe.insertBefore(V,Oe.firstChild);else if(_==="header-right")Oe.appendChild(V);else{let O=Oe.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):Oe.appendChild(V)}break;case"body-top":{let O=Y.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):Y.insertBefore(V,Y.firstChild);break}case"body-bottom":Y.appendChild(V);break;case"footer-top":Ct.replaceWith(V);break;case"footer-bottom":ln.replaceWith(V);break;default:break}};for(let[_,V]of Object.entries(c))if(V)try{let z=V({config:o,defaultContent:()=>m(_)});z&&h(_,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${_}":`,z)}})();let $o=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"?(Kr.has(P)?Kr.delete(P):Kr.add(P),Zu(P,y)):_==="tool"&&(Gr.has(P)?Gr.delete(P):Gr.add(P),em(P,y,o)),mo.delete(P)};Ve.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))}),Ve.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))});let Lo=new Map;Ve.addEventListener("click",c=>{var V;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=T.getMessages().find(Ce=>Ce.id===P);if(O&&j.onCopy){let Ce=O.content||"";navigator.clipboard.writeText(Ce).then(()=>{h.classList.add("persona-message-action-success");let pe=Se("check",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ne=Se("copy",14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),j.onCopy(O)}}else if(_==="upvote"||_==="downvote"){let O=((V=Lo.get(P))!=null?V:null)===_,Ce=_==="upvote"?"thumbs-up":"thumbs-down";if(O){Lo.delete(P),h.classList.remove("persona-message-action-active");let pe=Se(Ce,14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))}else{let pe=_==="upvote"?"downvote":"upvote",ne=y.querySelector(`[data-action="${pe}"]`);if(ne){ne.classList.remove("persona-message-action-active");let Ye=Se(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ye&&(ne.innerHTML="",ne.appendChild(Ye))}Lo.set(P,_),h.classList.add("persona-message-action-active");let he=Se(Ce,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(he)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Be=T.getMessages().find(et=>et.id===P);Be&&j.onFeedback&&j.onFeedback({type:_,messageId:Be.id,message:Be})}}}),Ve.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 V=_==="approve"?"approved":"denied",O=T.getMessages().find(pe=>pe.id===P);if(!(O!=null&&O.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?T.resolveWebMcpApproval(P,V):T.resolveApproval(O.approval,V)});let vt=null,_n=null,Vn={artifacts:[],selectedId:null},wn=!1,Rt={current:null};Ve.addEventListener("click",c=>{var ne,he,Te,Be,et;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Te=(he=(ne=o.features)==null?void 0:ne.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Te.call(he,{type:"download",artifactId:y}))===!0)return;let _=T.getArtifactById(y),V=_==null?void 0:_.markdown,z=(_==null?void 0:_.title)||"artifact";if(!V){let Ye=h.closest("[data-open-artifact]"),it=Ye==null?void 0:Ye.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let Me=T.getMessages().find($e=>$e.id===lt);if(Me!=null&&Me.rawContent)try{let $e=JSON.parse(Me.rawContent);V=(Be=$e==null?void 0:$e.props)==null?void 0:Be.markdown,z=((et=$e==null?void 0:$e.props)==null?void 0:et.title)||z}catch{}}}if(!V)return;let O=new Blob([V],{type:"text/markdown"}),Ce=URL.createObjectURL(O),pe=document.createElement("a");pe.href=Ce,pe.download=`${z}.md`,pe.click(),URL.revokeObjectURL(Ce)}),Ve.addEventListener("click",c=>{var _,V,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(V=(_=o.features)==null?void 0:_.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:z.call(V,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),wn=!1,T.selectArtifact(y),zn())}),Ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let eo=Le.composerOverlay,to=(c,m,h)=>{var z,O,Ce,pe;let y=m.trim();if(!y||!Rt.current)return;let P=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",_=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})),Jr(eo,P);let V=Rt.current.getMessages().find(ne=>{var he;return((he=ne.toolCall)==null?void 0:he.id)===P});(Ce=V==null?void 0:V.agentMetadata)!=null&&Ce.awaitingLocalTool?Rt.current.resolveAskUserQuestion(V,(pe=h.structured)!=null?pe:y):Rt.current.sendMessage(y)},$n=c=>{var P;let m=Rt.current;if(!m)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=m.getMessages().find(_=>{var V;return((V=_.toolCall)==null?void 0:V.id)===h});y&&m.persistAskUserQuestionProgress(y,{answers:xi(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var P,_,V;if(((_=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:_.groupedAutoAdvance)===!1)return;let m=lo(c),h=Qr(c);if(m>=h-1)return;let y=(V=Rt.current)==null?void 0:V.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(Ci(c,y,o,m+1),$n(c))};eo.addEventListener("click",c=>{var _,V,z,O,Ce,pe,ne,he,Te,Be,et,Ye,it,lt;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 Ie=(_=y.getAttribute("data-tool-call-id"))!=null?_:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Jr(eo,Ie);let Me=(V=Rt.current)==null?void 0:V.getMessages().find($e=>{var I;return((I=$e.toolCall)==null?void 0:I.id)===Ie});(z=Me==null?void 0:Me.agentMetadata)!=null&&z.awaitingLocalTool&&((O=Rt.current)==null||O.markAskUserQuestionResolved(Me),(Ce=Rt.current)==null||Ce.resolveAskUserQuestion(Me,"(dismissed)"));return}if(P==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Me=y.getAttribute("data-multi-select")==="true",$e=rr(y);if($e&&Me){let I=Tr(y)[lo(y)],ke=new Set(Array.isArray(I)?I:[]);ke.has(Ie)?ke.delete(Ie):ke.add(Ie),sr(y,Array.from(ke)),$n(y);return}if($e){sr(y,Ie),$n(y),Io(y);return}if(Me){let I=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",I?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!I);let ke=y.querySelector('[data-ask-user-action="submit-multi"]');ke&&(ke.disabled=kl(y).length===0);return}to(y,Ie,{source:"pick",values:[Ie]});return}if(P==="submit-multi"){let Ie=kl(y);if(Ie.length===0)return;to(y,Ie.join(", "),{source:"multi",values:Ie});return}if(P==="open-free-text"){let Ie=y.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Me=Ie.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus()}return}if(P==="focus-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(P==="submit-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]'),Me=(pe=Ie==null?void 0:Ie.value)!=null?pe:"";if(!Me.trim())return;if(rr(y)){sr(y,Me.trim()),$n(y),Io(y);return}to(y,Me,{source:"free-text"});return}if(P==="next"||P==="back"){if(!Rt.current)return;let Ie=(ne=y.getAttribute("data-tool-call-id"))!=null?ne:"",Me=Rt.current.getMessages().find(qe=>{var xe;return((xe=qe.toolCall)==null?void 0:xe.id)===Ie});if(!Me)return;let $e=y.querySelector('[data-ask-free-text-input="true"]'),I=(Te=(he=$e==null?void 0:$e.value)==null?void 0:he.trim())!=null?Te:"";if(I){let qe=Tr(y)[lo(y)];(typeof qe!="string"||qe!==I)&&sr(y,I)}let ke=P==="next"?1:-1,Pe=lo(y)+ke;Ci(y,Me,o,Pe),$n(y);return}if(P==="submit-all"){if(!Rt.current)return;let Ie=(Be=y.getAttribute("data-tool-call-id"))!=null?Be:"",Me=Rt.current.getMessages().find(qe=>{var xe;return((xe=qe.toolCall)==null?void 0:xe.id)===Ie});if(!Me)return;let $e=y.querySelector('[data-ask-free-text-input="true"]'),I=(Ye=(et=$e==null?void 0:$e.value)==null?void 0:et.trim())!=null?Ye:"";I&&sr(y,I);let ke=xi(y,Me);Rt.current.persistAskUserQuestionProgress(Me,{answers:ke,currentIndex:lo(y)});let Pe=Uo(ke);to(y,Pe||"(submitted)",{source:"submit-all",structured:ke});return}if(P==="skip"){if(!Rt.current)return;let Ie=(it=y.getAttribute("data-tool-call-id"))!=null?it:"",Me=Rt.current.getMessages().find(xe=>{var It;return((It=xe.toolCall)==null?void 0:It.id)===Ie});if(!Me)return;let $e=rr(y),I=lo(y),ke=Qr(y),Pe=I>=ke-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Jr(eo,Ie),(lt=Me.agentMetadata)!=null&&lt.awaitingLocalTool&&(Rt.current.markAskUserQuestionResolved(Me),Rt.current.resolveAskUserQuestion(Me,"(dismissed)"));return}sr(y,"");let qe=y.querySelector('[data-ask-free-text-input="true"]');if(qe&&(qe.value=""),Pe){let xe=xi(y,Me),It=Uo(xe);to(y,It||"(skipped)",{source:"submit-all",structured:xe});return}Ci(y,Me,o,I+1),$n(y);return}}),eo.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(rr(y)){sr(y,P.trim()),$n(y),Io(y);return}to(y,P,{source:"free-text"})}});let zo=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=eo.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",zo);let Un=null,Wt=null,Cn=null,no=null,qo=()=>{};function Ro(){no==null||no(),no=null}let jo=()=>{var V;if(!Un||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Wt)return;let P=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${P}px`,Wt.style.zIndex="5";let _=y.offsetWidth-P/2;Wt.style.left=`${Math.max(0,_)}px`},Co=()=>{},zn=()=>{var h,y,P,_,V;if(!vt||!co(o))return;Ai(e,o),Ti(e,o),Co();let c=(_=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?_:520,m=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),vt.update(Vn),wn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(V=vt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),qo()};if(co(o)){ce.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(de),vt=vm(o,{onSelect:h=>{var y;return(y=Rt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{wn=!0,zn()}}),vt.element.classList.add("persona-hidden"),Un=m,m.appendChild(c),m.appendChild(vt.element),vt.backdrop&&ce.appendChild(vt.backdrop),ce.appendChild(m),qo=()=>{var y,P,_,V;if(!Un||!vt)return;if(!(((_=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:_.resizable)===!0)){Cn==null||Cn(),Cn=null,Ro(),Wt&&(Wt.remove(),Wt=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Wt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,Ce=(V=O.defaultView)!=null?V:window,pe=ne=>{var it,lt;if(!vt||ne.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;ne.preventDefault(),Ro();let he=ne.clientX,Te=vt.element.getBoundingClientRect().width,Be=(lt=(it=o.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,et=Ie=>{let Me=Un.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),I=$e?0:Sm(Un,Ce),ke=$e?0:z.getBoundingClientRect().width||6,Pe=Te-(Ie.clientX-he),qe=Am(Pe,Me,I,ke,Be==null?void 0:Be.resizableMinWidth,Be==null?void 0:Be.resizableMaxWidth);vt.element.style.width=`${qe}px`,vt.element.style.maxWidth="none",jo()},Ye=()=>{O.removeEventListener("pointermove",et),O.removeEventListener("pointerup",Ye),O.removeEventListener("pointercancel",Ye),no=null;try{z.releasePointerCapture(ne.pointerId)}catch{}};no=Ye,O.addEventListener("pointermove",et),O.addEventListener("pointerup",Ye),O.addEventListener("pointercancel",Ye);try{z.setPointerCapture(ne.pointerId)}catch{}};z.addEventListener("pointerdown",pe),Wt=z,Un.insertBefore(z,vt.element),Cn=()=>{z.removeEventListener("pointerdown",pe)}}if(Wt){let z=Vn.artifacts.length>0&&!wn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me,$e,I;if(!W||!vt||((pe=(Ce=o.launcher)==null?void 0:Ce.sidebarMode)!=null?pe:!1)||un(o)&&Mo(o).reveal==="emerge")return;let y=(ne=e.ownerDocument.defaultView)!=null?ne:window,P=(Te=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Te:!0,_=(et=(Be=o.launcher)==null?void 0:Be.mobileBreakpoint)!=null?et:640;if(P&&y.innerWidth<=_||!Cm(o,W))return;let V=(lt=(it=(Ye=o.launcher)==null?void 0:Ye.width)!=null?it:o.launcherWidth)!=null?lt:io,z=(I=($e=(Me=(Ie=o.features)==null?void 0:Ie.artifacts)==null?void 0:Me.layout)==null?void 0:$e.expandedPanelWidth)!=null?I:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!wn?(ce.style.width=z,ce.style.maxWidth=z):(ce.style.width=V,ce.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(ce))}else ce.appendChild(de),E()&&_e&&(Le.peekBanner&&_e.appendChild(Le.peekBanner),_e.appendChild(Ne));e.appendChild(ge),_e&&e.appendChild(_e);let po=()=>{var qe,xe,It,st,Xt,dn,Pt,An,pn,Je,ct,Tn,gn,ur,mr,gr,Nr,_r,zt,fr,tr,bt,Pn,Oo,kn,Wn,Ht,Vt;if(E()){ce.style.width="100%",ce.style.maxWidth="100%";let Dt=(xe=(qe=o.launcher)==null?void 0:qe.composerBar)!=null?xe:{},qt=ge.dataset.state==="expanded",Bn=(It=Dt.expandedSize)!=null?It:"anchored";if(!(qt&&Bn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let tn=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=Ta(o),No=(hr,Sa)=>{var Cs;return hr==null||hr===""?Sa:(Cs=Vr(To,hr))!=null?Cs:hr},xa="1px solid var(--persona-border)",wa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ca="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=No(tn==null?void 0:tn.border,xa),de.style.borderRadius=No(tn==null?void 0:tn.borderRadius,Ca),de.style.boxShadow=No(tn==null?void 0:tn.shadow,wa),de.style.overflow="hidden";return}let c=un(o),m=(Pt=(dn=o.launcher)==null?void 0:dn.sidebarMode)!=null?Pt:!1,h=c||m||((pn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?pn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,P=(Tn=(ct=o.theme)==null?void 0:ct.components)==null?void 0:Tn.panel,_=Ta(o),V=(Dt,qt)=>{var Bn;return Dt==null||Dt===""?qt:(Bn=Vr(_,Dt))!=null?Bn:Dt},z=(gn=e.ownerDocument.defaultView)!=null?gn:window,O=(mr=(ur=o.launcher)==null?void 0:ur.mobileFullscreen)!=null?mr:!0,Ce=(Nr=(gr=o.launcher)==null?void 0:gr.mobileBreakpoint)!=null?Nr:640,pe=z.innerWidth<=Ce,ne=O&&pe&&W,he=(zt=(_r=o.launcher)==null?void 0:_r.position)!=null?zt:"bottom-left",Te=he==="bottom-left"||he==="top-left",Be=(tr=(fr=o.launcher)==null?void 0:fr.zIndex)!=null?tr:bn,et=m||ne?"none":"1px solid var(--persona-border)",Ye=ne?"none":m?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ne&&(Ye="none",et="none");let it=m||ne?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=V(P==null?void 0:P.border,et),Ie=V(P==null?void 0:P.shadow,Ye),Me=V(P==null?void 0:P.borderRadius,it),$e=Y.scrollTop;e.style.cssText="",ge.style.cssText="",ce.style.cssText="",de.style.cssText="",Y.style.cssText="",Ne.style.cssText="";let I=()=>{var qt;if($e<=0)return;((qt=Y.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Y.scrollTop===$e)return;let Bn=Y.scrollHeight-Y.clientHeight;Bn<=0||(Y.scrollTop=Math.min($e,Bn))})};if(ne){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
+ `,x.addEventListener("click",()=>{m=v,I.forEach((k,S)=>{let E=S<v;k.classList.toggle("selected",E),k.setAttribute("aria-checked",S===v-1?"true":"false")})}),I.push(x),M.appendChild(x)}f.appendChild(M);let R=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),v.appendChild(R),f.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),p.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let v=(R==null?void 0:R.value.trim())||void 0;await t(m,v),p.remove()}catch(v){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(B),f.appendChild(H),p.appendChild(f),p}function Bm(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:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,w.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,w.appendChild(M),u.appendChild(w);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=p,R.appendChild(H),R.appendChild(D);let B=document.createElement("div");B.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=F,v.forEach((j,me)=>{j.classList.toggle("selected",me===F),j.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),B.appendChild($)}I.appendChild(R),I.appendChild(B),u.appendChild(I);let x=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),F.appendChild(x),u.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),m.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){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let F=(x==null?void 0:x.value.trim())||void 0;await t(f,F),m.remove()}catch(F){E.disabled=!1,E.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),k.appendChild(S),k.appendChild(E),u.appendChild(k),m.appendChild(u),m}var es="persona-chat-history",ex=30*1e3,tx={"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 nx(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=tx[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 Ei(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 ox(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 rx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ol=e=>!e||typeof e!="object"?{}:{...e},Hm=e=>e.map(t=>({...t,streaming:!1})),Dm=(e,t,n)=>{let o=e!=null&&e.markdown?_a(e.markdown):null,r=Va(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,p,m;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(m=i!=null?i:s.text)!=null?m:""}):o?d=o(a):d=Ls(a),r?r(d):d}};function Fm(e){var i,d,l,p;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=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Te(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let m=b("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Om=(e,t,n)=>{var sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Qp(t),r=Bl.getForInstance(o.plugins);o.components&&Mr.registerAll(o.components);let s=km(),i=o.persistState===!1?null:(sc=o.storageAdapter)!=null?sc:Mm(),d={},l=null,p=!1,m=c=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:y}=g;return y&&(p=!0),h}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let h=g!=null?g:{messages:[],metadata:{}};return m(h)});else{let g=c!=null?c:{messages:[],metadata:{}},h=m(g);h.metadata&&(d=Ol(h.metadata)),(ac=h.messages)!=null&&ac.length&&(o={...o,initialMessages:h.messages}),(ic=h.artifacts)!=null&&ic.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(lc=h.selectedArtifactId)!=null?lc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=m({messages:[],metadata:{}});(cc=c.messages)!=null&&cc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,u=c=>{var h;d=(h=c({...d}))!=null?h:{},Wr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick],M=Fl({parsers:w,handlers:C,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(pc=(dc=o.launcher)==null?void 0:dc.enabled)!=null?pc:!0,R=(mc=(uc=o.launcher)==null?void 0:uc.autoExpand)!=null?mc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=R,B=I,v=(hc=(fc=o.layout)==null?void 0:fc.header)==null?void 0:hc.layout,x=!1,k=()=>zs(o),S=()=>I||k(),E=k()?!1:I?R:!0,F=!1,$=null,j=()=>{F=!0,$&&clearTimeout($),$=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},me=Dm(o,M,j),se=(yc=(bc=o.features)==null?void 0:bc.showReasoning)!=null?yc:!0,ge=(xc=(vc=o.features)==null?void 0:vc.showToolCalls)!=null?xc:!0,ie=(Cc=(wc=o.features)==null?void 0:wc.showEventStreamToggle)!=null?Cc:!1,be=(Ac=(Sc=o.features)==null?void 0:Sc.scrollToBottom)!=null?Ac:{},ve=`${(kc=typeof o.persistState=="object"?(Tc=o.persistState)==null?void 0:Tc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,J=ie?new Xs(ve):null,Le=(Lc=(Mc=(Ec=o.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.maxEvents)!=null?Lc:2e3,Y=ie?new Ys(Le,J):null,xe=ie?new Qs:null,Se=null,de=!1,we=null,Ue=0;J==null||J.open().then(()=>Y==null?void 0:Y.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let te={onCopy:c=>{var g,h;s.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onCopy)==null||h.call(g,c)},onFeedback:c=>{var g,h;s.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onFeedback)==null||h.call(g,c)}},ne=(Ic=o.statusIndicator)!=null?Ic:{},re=c=>{var g,h,y,P;return c==="idle"?(g=ne.idleText)!=null?g:fn.idle:c==="connecting"?(h=ne.connectingText)!=null?h:fn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:fn.connected:c==="error"?(P=ne.errorText)!=null?P:fn.error:fn[c]};function nt(c,g,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=g,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=g}let{wrapper:ye,panel:le,pillRoot:$e}=Yu(o),Be=Xu(o,S()),{container:ce,body:K,messagesWrapper:_e,suggestions:Et,textarea:pe,sendButton:ae,sendButtonWrapper:Ln,composerForm:Nt,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:ze,iconHolder:_,headerTitle:ke,headerSubtitle:He,header:De,footer:Ve,actionsRow:dt,leftActions:ot,rightActions:At}=Be,Vt=Be.setSendButtonMode,q=Be.micButton,_t=Be.micButtonWrapper,Qe=Be.attachmentButton,Ft=Be.attachmentButtonWrapper,oe=Be.attachmentInput,fe=Be.attachmentPreviewsContainer;ce.classList.add("persona-relative"),K.classList.add("persona-relative");let xt=12,$t=()=>{var c;return(c=be.label)!=null?c:""},Jt=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},yn=()=>be.enabled!==!1,Tt=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");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let wt=b("span","persona-flex persona-items-center"),ft=b("span","");Tt.append(wt,ft),ce.appendChild(Tt);let bt=()=>{let g=Ve.style.display==="none"?0:Ve.offsetHeight;Tt.style.bottom=`${g+xt}px`};bt();let zt=()=>{let c=!!$t();Tt.setAttribute("aria-label",$t()||"Jump to latest"),Tt.title=$t(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let g=Te(Jt(),"14px","currentColor",2);g?(wt.appendChild(g),wt.style.display=""):wt.style.display="none",ft.textContent=$t(),ft.style.display=c?"":"none"};zt();let et=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let g=Ar({config:o,showClose:S()});return js(ce,g,o),g.header},onClose:()=>Bt(!1,"user")});if(c){let g=ce.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let vn=()=>{var g,h,y,P;if(!Y)return;if(de=!0,!Se&&Y&&(Se=hm({buffer:Y,getFullHistory:()=>Y.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var N;return(N=xe==null?void 0:xe.getMetric())!=null?N:{status:"idle"}}})),Se&&(K.style.display="none",(g=Ve.parentNode)==null||g.insertBefore(Se.element,Ve),Se.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(P=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:P.toggleButtonActive;N&&N.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let c=()=>{if(!de)return;let N=Date.now();N-Ue>=200&&(Se==null||Se.update(),Ue=N),we=requestAnimationFrame(c)};Ue=0,we=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,g,h;if(de){if(de=!1,Se&&Se.element.remove(),K.style.display="",ut){ut.style.boxShadow="";let y=(h=(g=(c=o.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&ut.classList.remove(P))}we!==null&&(cancelAnimationFrame(we),we=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Pc=(Rc=o.features)==null?void 0:Rc.eventStream)==null?void 0:Pc.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=b("button",g),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=Te("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=Be.clearChatButtonWrapper,P=Be.closeButtonWrapper,N=y||P;N&&N.parentNode===De?De.insertBefore(ut,N):De.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}let wo=c=>{var y,P,N;let g=o.attachments;if(!(g!=null&&g.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 V=c.querySelector("[data-persona-composer-form]");V!=null&&V.parentNode?V.parentNode.insertBefore(h,V):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let V=b("input");V.type="file",V.accept=((y=g.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=g.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(N=g.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,g=Nn.renderComposer({config:o,defaultRenderer:()=>xi({config:o}).footer,onSubmit:h=>{var V;if(!T||T.isStreaming())return;let y=h.trim(),P=(V=et==null?void 0:et.hasAttachments())!=null?V:!1;if(!y&&!P)return;gs();let N;P&&(N=[],N.push(...et.getContentParts()),y&&N.push(ll(y))),T.sendMessage(y,{contentParts:N}),P&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{oe==null||oe.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:((Wc=o.voiceRecognition)==null?void 0:Wc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});g&&(Ve.replaceWith(g),Ve=g)}let ir=c=>{let g=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]"),N=c.querySelector("[data-persona-composer-status]");g&&(Nt=g),h&&(pe=h),y&&(ae=y),P&&(q=P,_t=P.parentElement),N&&(ln=N);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Et=V);let z=c.querySelector(".persona-attachment-button");z&&(Qe=z,Ft=z.parentElement),oe=c.querySelector('input[type="file"]'),fe=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(dt=O)};wo(Ve),ir(Ve);let In=(Oc=(Bc=o.layout)==null?void 0:Bc.contentMaxWidth)!=null?Oc:k()?(Fc=(Dc=(Hc=o.launcher)==null?void 0:Hc.composerBar)==null?void 0:Dc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&(_e.style.maxWidth=In,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%"),In&&Nt&&!k()&&(Nt.style.maxWidth=In,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),In&&Et&&!k()&&(Et.style.maxWidth=In,Et.style.marginLeft="auto",Et.style.marginRight="auto"),In&&fe&&!k()&&(fe.style.maxWidth=In,fe.style.marginLeft="auto",fe.style.marginRight="auto"),(Nc=o.attachments)!=null&&Nc.enabled&&oe&&fe){et=Ds.fromConfig(o.attachments),et.setPreviewsContainer(fe),oe.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,g=Fm(c);ce.appendChild(g)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},g=N=>{switch(N){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return _e;case"footer-top":return Et;case"composer":return Nt;case"footer-bottom":return ln;default:return null}},h=(N,V)=>{var z;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")De.insertBefore(V,De.firstChild);else if(N==="header-right")De.appendChild(V);else{let O=De.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):De.appendChild(V)}break;case"body-top":{let O=K.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):K.insertBefore(V,K.firstChild);break}case"body-bottom":K.appendChild(V);break;case"footer-top":Et.replaceWith(V);break;case"footer-bottom":ln.replaceWith(V);break;default:break}};for(let[N,V]of Object.entries(c))if(V)try{let z=V({config:o,defaultContent:()=>g(N)});z&&h(N,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,z)}})();let $o=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 N=h.getAttribute("data-bubble-type");N==="reasoning"?(Kr.has(P)?Kr.delete(P):Kr.add(P),Zu(P,y)):N==="tool"&&(Gr.has(P)?Gr.delete(P):Gr.add(P),em(P,y,o)),mo.delete(P)};_e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))}),_e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))});let Lo=new Map;_e.addEventListener("click",c=>{var V;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 N=h.getAttribute("data-action");if(N==="copy"){let O=T.getMessages().find(Ae=>Ae.id===P);if(O&&te.onCopy){let Ae=O.content||"";navigator.clipboard.writeText(Ae).then(()=>{h.classList.add("persona-message-action-success");let ue=Te("check",14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=Te("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),te.onCopy(O)}}else if(N==="upvote"||N==="downvote"){let O=((V=Lo.get(P))!=null?V:null)===N,Ae=N==="upvote"?"thumbs-up":"thumbs-down";if(O){Lo.delete(P),h.classList.remove("persona-message-action-active");let ue=Te(Ae,14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue))}else{let ue=N==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ue}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ye=Te(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ye&&(ee.innerHTML="",ee.appendChild(Ye))}Lo.set(P,N),h.classList.add("persona-message-action-active");let he=Te(Ae,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(he)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Oe=T.getMessages().find(tt=>tt.id===P);Oe&&te.onFeedback&&te.onFeedback({type:N,messageId:Oe.id,message:Oe})}}}),_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 N=h.getAttribute("data-approval-action");if(!N)return;let V=N==="approve"?"approved":"denied",O=T.getMessages().find(ue=>ue.id===P);if(!(O!=null&&O.approval))return;let Ae=y.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?T.resolveWebMcpApproval(P,V):T.resolveApproval(O.approval,V)});let yt=null,_n=null,Vn={artifacts:[],selectedId:null},xn=!1,It={current:null};_e.addEventListener("click",c=>{var ee,he,Ee,Oe,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||((Ee=(he=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ee.call(he,{type:"download",artifactId:y}))===!0)return;let N=T.getArtifactById(y),V=N==null?void 0:N.markdown,z=(N==null?void 0:N.title)||"artifact";if(!V){let Ye=h.closest("[data-open-artifact]"),at=Ye==null?void 0:Ye.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Re=T.getMessages().find(qe=>qe.id===it);if(Re!=null&&Re.rawContent)try{let qe=JSON.parse(Re.rawContent);V=(Oe=qe==null?void 0:qe.props)==null?void 0:Oe.markdown,z=((tt=qe==null?void 0:qe.props)==null?void 0:tt.title)||z}catch{}}}if(!V)return;let O=new Blob([V],{type:"text/markdown"}),Ae=URL.createObjectURL(O),ue=document.createElement("a");ue.href=Ae,ue.download=`${z}.md`,ue.click(),URL.revokeObjectURL(Ae)}),_e.addEventListener("click",c=>{var N,V,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(V=(N=o.features)==null?void 0:N.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:z.call(V,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,T.selectArtifact(y),zn())}),_e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let eo=Be.composerOverlay,to=(c,g,h)=>{var z,O,Ae,ue;let y=g.trim();if(!y||!It.current)return;let P=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",N=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:N,source:h.source},bubbles:!0,composed:!0})),Jr(eo,P);let V=It.current.getMessages().find(ee=>{var he;return((he=ee.toolCall)==null?void 0:he.id)===P});(Ae=V==null?void 0:V.agentMetadata)!=null&&Ae.awaitingLocalTool?It.current.resolveAskUserQuestion(V,(ue=h.structured)!=null?ue:y):It.current.sendMessage(y)},$n=c=>{var P;let g=It.current;if(!g)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=g.getMessages().find(N=>{var V;return((V=N.toolCall)==null?void 0:V.id)===h});y&&g.persistAskUserQuestionProgress(y,{answers:wi(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var P,N,V;if(((N=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=lo(c),h=Qr(c);if(g>=h-1)return;let y=(V=It.current)==null?void 0:V.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(Si(c,y,o,g+1),$n(c))};eo.addEventListener("click",c=>{var N,V,z,O,Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it;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 Pe=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Jr(eo,Pe);let Re=(V=It.current)==null?void 0:V.getMessages().find(qe=>{var L;return((L=qe.toolCall)==null?void 0:L.id)===Pe});(z=Re==null?void 0:Re.agentMetadata)!=null&&z.awaitingLocalTool&&((O=It.current)==null||O.markAskUserQuestionResolved(Re),(Ae=It.current)==null||Ae.resolveAskUserQuestion(Re,"(dismissed)"));return}if(P==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Re=y.getAttribute("data-multi-select")==="true",qe=sr(y);if(qe&&Re){let L=kr(y)[lo(y)],Me=new Set(Array.isArray(L)?L:[]);Me.has(Pe)?Me.delete(Pe):Me.add(Pe),ar(y,Array.from(Me)),$n(y);return}if(qe){ar(y,Pe),$n(y),Io(y);return}if(Re){let L=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",L?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!L);let Me=y.querySelector('[data-ask-user-action="submit-multi"]');Me&&(Me.disabled=El(y).length===0);return}to(y,Pe,{source:"pick",values:[Pe]});return}if(P==="submit-multi"){let Pe=El(y);if(Pe.length===0)return;to(y,Pe.join(", "),{source:"multi",values:Pe});return}if(P==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Re=Pe.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(P==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(P==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Re=(ue=Pe==null?void 0:Pe.value)!=null?ue:"";if(!Re.trim())return;if(sr(y)){ar(y,Re.trim()),$n(y),Io(y);return}to(y,Re,{source:"free-text"});return}if(P==="next"||P==="back"){if(!It.current)return;let Pe=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Re=It.current.getMessages().find(Ke=>{var Ce;return((Ce=Ke.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),L=(Ee=(he=qe==null?void 0:qe.value)==null?void 0:he.trim())!=null?Ee:"";if(L){let Ke=kr(y)[lo(y)];(typeof Ke!="string"||Ke!==L)&&ar(y,L)}let Me=P==="next"?1:-1,We=lo(y)+Me;Si(y,Re,o,We),$n(y);return}if(P==="submit-all"){if(!It.current)return;let Pe=(Oe=y.getAttribute("data-tool-call-id"))!=null?Oe:"",Re=It.current.getMessages().find(Ke=>{var Ce;return((Ce=Ke.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),L=(Ye=(tt=qe==null?void 0:qe.value)==null?void 0:tt.trim())!=null?Ye:"";L&&ar(y,L);let Me=wi(y,Re);It.current.persistAskUserQuestionProgress(Re,{answers:Me,currentIndex:lo(y)});let We=Uo(Me);to(y,We||"(submitted)",{source:"submit-all",structured:Me});return}if(P==="skip"){if(!It.current)return;let Pe=(at=y.getAttribute("data-tool-call-id"))!=null?at:"",Re=It.current.getMessages().find(Ce=>{var Lt;return((Lt=Ce.toolCall)==null?void 0:Lt.id)===Pe});if(!Re)return;let qe=sr(y),L=lo(y),Me=Qr(y),We=L>=Me-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Jr(eo,Pe),(it=Re.agentMetadata)!=null&&it.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Re),It.current.resolveAskUserQuestion(Re,"(dismissed)"));return}ar(y,"");let Ke=y.querySelector('[data-ask-free-text-input="true"]');if(Ke&&(Ke.value=""),We){let Ce=wi(y,Re),Lt=Uo(Ce);to(y,Lt||"(skipped)",{source:"submit-all",structured:Ce});return}Si(y,Re,o,L+1),$n(y);return}}),eo.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let h=c.target;if(!((N=h.matches)!=null&&N.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(sr(y)){ar(y,P.trim()),$n(y),Io(y);return}to(y,P,{source:"free-text"})}});let zo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let h=eo.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),N=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];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",zo);let Un=null,Wt=null,wn=null,no=null,qo=()=>{};function Ro(){no==null||no(),no=null}let jo=()=>{var V;if(!Un||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Wt)return;let P=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${P}px`,Wt.style.zIndex="5";let N=y.offsetWidth-P/2;Wt.style.left=`${Math.max(0,N)}px`},Co=()=>{},zn=()=>{var h,y,P,N,V;if(!yt||!co(o))return;Ti(e,o),ki(e,o),Co();let c=(N=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?N:520,g=le.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),yt.update(Vn),xn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(V=yt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),qo()};if(co(o)){le.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),yt=vm(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{xn=!0,zn()}}),yt.element.classList.add("persona-hidden"),Un=g,g.appendChild(c),g.appendChild(yt.element),yt.backdrop&&le.appendChild(yt.backdrop),le.appendChild(g),qo=()=>{var y,P,N,V;if(!Un||!yt)return;if(!(((N=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:N.resizable)===!0)){wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,Ae=(V=O.defaultView)!=null?V:window,ue=ee=>{var at,it;if(!yt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;ee.preventDefault(),Ro();let he=ee.clientX,Ee=yt.element.getBoundingClientRect().width,Oe=(it=(at=o.features)==null?void 0:at.artifacts)==null?void 0:it.layout,tt=Pe=>{let Re=Un.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),L=qe?0:Sm(Un,Ae),Me=qe?0:z.getBoundingClientRect().width||6,We=Ee-(Pe.clientX-he),Ke=Am(We,Re,L,Me,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);yt.element.style.width=`${Ke}px`,yt.element.style.maxWidth="none",jo()},Ye=()=>{O.removeEventListener("pointermove",tt),O.removeEventListener("pointerup",Ye),O.removeEventListener("pointercancel",Ye),no=null;try{z.releasePointerCapture(ee.pointerId)}catch{}};no=Ye,O.addEventListener("pointermove",tt),O.addEventListener("pointerup",Ye),O.addEventListener("pointercancel",Ye);try{z.setPointerCapture(ee.pointerId)}catch{}};z.addEventListener("pointerdown",ue),Wt=z,Un.insertBefore(z,yt.element),wn=()=>{z.removeEventListener("pointerdown",ue)}}if(Wt){let z=Vn.artifacts.length>0&&!xn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re,qe,L;if(!I||!yt||((ue=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||pn(o)&&Mo(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,P=(Ee=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Ee:!0,N=(tt=(Oe=o.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?tt:640;if(P&&y.innerWidth<=N||!Cm(o,I))return;let V=(it=(at=(Ye=o.launcher)==null?void 0:Ye.width)!=null?at:o.launcherWidth)!=null?it:io,z=(L=(qe=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:qe.expandedPanelWidth)!=null?L:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!xn?(le.style.width=z,le.style.maxWidth=z):(le.style.width=V,le.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(le))}else le.appendChild(ce),k()&&$e&&(Be.peekBanner&&$e.appendChild(Be.peekBanner),$e.appendChild(Ve));e.appendChild(ye),$e&&e.appendChild($e);let po=()=>{var Ke,Ce,Lt,st,Xt,cn,Pt,An,dn,Je,lt,Tn,mn,mr,gr,fr,Nr,_r,qt,hr,nr,ht,Pn,Oo,kn,Wn,Ht,Ut;if(k()){le.style.width="100%",le.style.maxWidth="100%";let Dt=(Ce=(Ke=o.launcher)==null?void 0:Ke.composerBar)!=null?Ce:{},jt=ye.dataset.state==="expanded",Bn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(jt&&Bn!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let en=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=ka(o),No=(br,Aa)=>{var Cs;return br==null||br===""?Aa:(Cs=Vr(To,br))!=null?Cs:br},wa="1px solid var(--persona-border)",Ca="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Sa="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=No(en==null?void 0:en.border,wa),ce.style.borderRadius=No(en==null?void 0:en.borderRadius,Sa),ce.style.boxShadow=No(en==null?void 0:en.shadow,Ca),ce.style.overflow="hidden";return}let c=pn(o),g=(Pt=(cn=o.launcher)==null?void 0:cn.sidebarMode)!=null?Pt:!1,h=c||g||((dn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?dn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,P=(Tn=(lt=o.theme)==null?void 0:lt.components)==null?void 0:Tn.panel,N=ka(o),V=(Dt,jt)=>{var Bn;return Dt==null||Dt===""?jt:(Bn=Vr(N,Dt))!=null?Bn:Dt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,O=(gr=(mr=o.launcher)==null?void 0:mr.mobileFullscreen)!=null?gr:!0,Ae=(Nr=(fr=o.launcher)==null?void 0:fr.mobileBreakpoint)!=null?Nr:640,ue=z.innerWidth<=Ae,ee=O&&ue&&I,he=(qt=(_r=o.launcher)==null?void 0:_r.position)!=null?qt:"bottom-left",Ee=he==="bottom-left"||he==="top-left",Oe=(nr=(hr=o.launcher)==null?void 0:hr.zIndex)!=null?nr:hn,tt=g||ee?"none":"1px solid var(--persona-border)",Ye=ee?"none":g?Ee?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ye="none",tt="none");let at=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=V(P==null?void 0:P.border,tt),Pe=V(P==null?void 0:P.shadow,Ye),Re=V(P==null?void 0:P.borderRadius,at),qe=K.scrollTop;e.style.cssText="",ye.style.cssText="",le.style.cssText="",ce.style.cssText="",K.style.cssText="",Ve.style.cssText="";let L=()=>{var jt;if(qe<=0)return;((jt=K.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(K.scrollTop===qe)return;let Bn=K.scrollHeight-K.clientHeight;Bn<=0||(K.scrollTop=Math.min(qe,Bn))})};if(ee){ye.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"),ye.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -37,9 +37,9 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${Be} !important;
40
+ z-index: ${Oe} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
- `,ce.style.cssText=`
42
+ `,le.style.cssText=`
43
43
  position: relative !important;
44
44
  display: flex !important;
45
45
  flex-direction: column !important;
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
52
52
  padding: 0 !important;
53
53
  box-shadow: none !important;
54
54
  border-radius: 0 !important;
55
- `,de.style.cssText=`
55
+ `,ce.style.cssText=`
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
58
  flex: 1 1 0% !important;
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:o}var Za=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
- `,Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",Ne.style.flexShrink="0",w=!0,I();return}let ke=(Pn=(bt=o==null?void 0:o.launcher)==null?void 0:bt.width)!=null?Pn:o==null?void 0:o.launcherWidth,Pe=ke!=null?ke:io;if(!m&&!c)y&&h?(ce.style.width="100%",ce.style.maxWidth="100%"):(ce.style.width=Pe,ce.style.maxWidth=Pe);else if(c)if(Mo(o).reveal==="emerge"){let qt=Mo(o).width;ce.style.width=qt,ce.style.maxWidth=qt}else ce.style.width="100%",ce.style.maxWidth="100%";if(Co(),ce.style.boxShadow=Ie,ce.style.borderRadius=Me,de.style.border=lt,de.style.borderRadius=Me,c&&!ne&&(P==null?void 0:P.border)===void 0&&(de.style.border="none",Mo(o).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.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"),ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.height="100%",ce.style.overflow="hidden",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",Ne.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"),!m&&!y&&!c&&((Oo=xo[he])!=null?Oo:xo["bottom-right"]).split(" ").forEach(qt=>ge.classList.add(qt)),m){let Dt=(Wn=(kn=o.launcher)==null?void 0:kn.sidebarWidth)!=null?Wn:"420px";ge.style.cssText=`
66
+ `,K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",Ve.style.flexShrink="0",x=!0,L();return}let Me=(Pn=(ht=o==null?void 0:o.launcher)==null?void 0:ht.width)!=null?Pn:o==null?void 0:o.launcherWidth,We=Me!=null?Me:io;if(!g&&!c)y&&h?(le.style.width="100%",le.style.maxWidth="100%"):(le.style.width=We,le.style.maxWidth=We);else if(c)if(Mo(o).reveal==="emerge"){let jt=Mo(o).width;le.style.width=jt,le.style.maxWidth=jt}else le.style.width="100%",le.style.maxWidth="100%";if(Co(),le.style.boxShadow=Pe,le.style.borderRadius=Re,ce.style.border=it,ce.style.borderRadius=Re,c&&!ee&&(P==null?void 0:P.border)===void 0&&(ce.style.border="none",Mo(o).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.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%"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",y&&(ye.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",le.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",Ve.style.flexShrink="0"),ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!y&&!c&&((Oo=xo[he])!=null?Oo:xo["bottom-right"]).split(" ").forEach(jt=>ye.classList.add(jt)),g){let Dt=(Wn=(kn=o.launcher)==null?void 0:kn.sidebarWidth)!=null?Wn:"420px";ye.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
@@ -74,9 +74,9 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
74
74
  padding: 0 !important;
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
- z-index: ${Be} !important;
78
- ${Te?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
- `,ce.style.cssText=`
77
+ z-index: ${Oe} !important;
78
+ ${Ee?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
+ `,le.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
82
82
  flex-direction: column !important;
@@ -87,9 +87,9 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
87
87
  min-height: 0 !important;
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
- box-shadow: ${Ie} !important;
91
- border-radius: ${Me} !important;
92
- `,ce.style.setProperty("width","100%","important"),ce.style.setProperty("max-width","100%","important"),de.style.cssText=`
90
+ box-shadow: ${Pe} !important;
91
+ border-radius: ${Re} !important;
92
+ `,le.style.setProperty("width","100%","important"),le.style.setProperty("max-width","100%","important"),ce.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
95
  flex: 1 1 0% !important;
@@ -98,13 +98,13 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${Me} !important;
102
- border: ${lt} !important;
103
- `,Ne.style.cssText=`
101
+ border-radius: ${Re} !important;
102
+ border: ${it} !important;
103
+ `,Ve.style.cssText=`
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 Dt="max-height: -moz-available !important; max-height: stretch !important;",qt=m?"":"padding-top: 1.25em !important;",Bn=m?"":`z-index: ${(Vt=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Vt:bn} !important;`;ge.style.cssText+=Dt+qt+Bn}I()};po(),$r(e,o),Ai(e,o),Ti(e,o);let ft=[];ft.push(()=>{document.removeEventListener("keydown",zo)});let Kt=null,Gt=null;ft.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),_n&&ft.push(()=>{_n==null||_n.disconnect(),_n=null}),ft.push(()=>{Cn==null||Cn(),Cn=null,Ro(),Wt&&(Wt.remove(),Wt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ie&&ft.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),fe==null||fe.destroy(),fe=null,X==null||X.destroy(),X=null,Z=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=nu(()=>{$r(e,o)}))};Ko(),ft.push(()=>{qn&&(qn(),qn=null)});let oo=(_c=o.features)==null?void 0:_c.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=_s(oo.type,oo.plugins);c&&(pl(c,e),ft.push(()=>zu(e)))}let uo=um(Ct),jn=null,T,Kn=!1,mo=Ou(),Po=new Map,So=new Map,ss=0,go=oi(),fo=0,ho=null,Wo=!1,ir=!1,ra=4,as=24,sa=80,Rr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=($c=(Vc=o.voiceRecognition)==null?void 0:Vc.autoResume)!=null?$c:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{g(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Fl(d.voiceState),m=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<ex&&setTimeout(()=>{var _,V;mt.active||(mt.manuallyDeactivated=!1,((V=(_=o.voiceRecognition)==null?void 0:_.provider)==null?void 0:V.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("restore"),T.isVoiceActive()&&R()}):pr("restore"))},1e3)},ia=()=>T?Hm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Pr(c){if(!(i!=null&&i.save))return;let h={messages:c?Hm(c):T?ia():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.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 Bo=null,la=()=>ge.querySelector("#persona-scroll-container")||Y,lr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},ls=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),ir=!1,lr()},Ho=()=>{if(!vn()||le){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==de&&de.appendChild(Et),yt();let c=Fs(Y)>0;Et.style.display=go.isFollowing()||!c?"none":""},cs=()=>{go.pause()&&(ls(),Ho())},Go=()=>{go.resume(),Ho()},Yo=(c=!1)=>{go.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),ir=!0,ho=requestAnimationFrame(()=>{ho=null,ir=!1,go.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,m=500)=>{let h=c.scrollTop,y=Fs(c),P=y-h;if(Math.abs(P)<1){fo=c.scrollTop;return}if(Math.abs(P)>=sa){lr(),Wo=!0,c.scrollTop=y,fo=c.scrollTop,Wo=!1;return}lr();let _=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!go.isFollowing()){lr();return}let Ce=Fs(c);Ce!==y&&(y=Ce,P=y-h);let pe=O-_,ne=Math.min(pe/m,1),he=V(ne),Te=h+P*he;c.scrollTop=Te,fo=c.scrollTop,ne<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,fo=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},da=c=>{let m=new Map;c.forEach(h=>{let y=Rr.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}))}),Rr.clear(),m.forEach((h,y)=>{Rr.set(y,h)})},cr=(c,m,h)=>{var Ye,it,lt,Ie,Me,$e;let y=document.createElement("div"),_=(()=>{var ke;let I=r.find(Pe=>Pe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((ke=o.loadingIndicator)!=null&&ke.render)return o.loadingIndicator.render})(),V=(I,ke)=>ke==null?!1:typeof ke=="string"?(I.textContent=ke,!0):(I.appendChild(ke),!0),z=new Set,O=new Set,Ce=r.some(I=>I.renderAskUserQuestion),pe=[],ne=[],he=o.enableComponentStreaming!==!1;if(m.forEach(I=>{var An,pn,Je,ct,Tn,gn,ur,mr,gr,Nr,_r,zt,fr,tr;z.add(I.id);let ke=Ce&&Ar(I),Pe=!ke&&I.role==="assistant"&&!I.variant&&he&&Rm(I);if(!Pe&&So.has(I.id)){let bt=c.querySelector(`#wrapper-${I.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),So.delete(I.id)}let qe=Ar(I)?`:${(An=I.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(pn=I.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Fu(I,ss)+qe,It=ke||Pe?null:Nu(mo,I.id,xe);if(It){y.appendChild(It.cloneNode(!0)),Ar(I)&&((Je=I.toolCall)!=null&&Je.id)&&((ct=I.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((Tn=I.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(I.toolCall.id),wi(I,o,Le.composerOverlay));return}let st=null,Xt=r.find(bt=>!!(I.variant==="reasoning"&&bt.renderReasoning||I.variant==="tool"&&bt.renderToolCall||I.variant==="approval"&&bt.renderApproval||!I.variant&&bt.renderMessage)),dn=(gn=o.layout)==null?void 0:gn.messages;if(Ar(I)&&((ur=I.agentMetadata)==null?void 0:ur.askUserQuestionAnswered)===!0){Po.delete(I.id);let bt=c.querySelector(`#wrapper-${I.id}`);bt==null||bt.removeAttribute("data-preserve-runtime");return}if(Ar(I)&&((gr=(mr=o.features)==null?void 0:mr.askUserQuestion)==null?void 0:gr.enabled)!==!1){let bt=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(bt&&Rt.current){let Pn=Po.get(I.id),Oo=Pn!==xe,kn=null;if(Oo){let{payload:Vt,complete:Dt}=Xr(I),qt=I.id,Bn=()=>{var Yn;return(Yn=Rt.current)==null?void 0:Yn.getMessages().find(tn=>tn.id===qt)};kn=bt.renderAskUserQuestion({message:I,payload:Vt,complete:Dt,resolve:Yn=>{var To;let tn=Bn();tn&&((To=Rt.current)==null||To.resolveAskUserQuestion(tn,Yn))},dismiss:()=>{var tn,To,No;let Yn=Bn();(tn=Yn==null?void 0:Yn.agentMetadata)!=null&&tn.awaitingLocalTool&&((To=Rt.current)==null||To.markAskUserQuestionResolved(Yn),(No=Rt.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=I.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=I.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(I.toolCall.id),wi(I,o,Le.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${I.id}`,Ht.setAttribute("data-wrapper-id",I.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),pe.push({messageId:I.id,fingerprint:xe,bubble:kn});return}else{((zt=I.agentMetadata)==null?void 0:zt.awaitingLocalTool)===!0&&!((fr=I.agentMetadata)!=null&&fr.askUserQuestionAnswered)&&(O.add(I.toolCall.id),wi(I,o,Le.composerOverlay));return}}else if(Xt)if(I.variant==="reasoning"&&I.reasoning&&Xt.renderReasoning){if(!re)return;st=Xt.renderReasoning({message:I,defaultRenderer:()=>yl(I,o),config:o})}else if(I.variant==="tool"&&I.toolCall&&Xt.renderToolCall){if(!be)return;st=Xt.renderToolCall({message:I,defaultRenderer:()=>vl(I,o),config:o})}else if(I.variant==="approval"&&I.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:I,defaultRenderer:()=>El(I,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:I,defaultRenderer:()=>{let bt=bl(I,h,dn,o.messageActions,j,{loadingIndicatorRenderer:_,widgetConfig:o});return I.role!=="user"&&Rl(bt,I,o,T),bt},config:o}));if(!st&&Pe){let bt=Pm(I);if(bt){let Pn=So.get(I.id),Oo=Pn!==xe,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Lm(bt,{config:o,message:I,transform:h});if(Ht)if(kn){let Vt=document.createElement("div");if(Vt.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(" "),Vt.id=`bubble-${I.id}`,Vt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Vt.appendChild(Dt)}Vt.appendChild(Ht),Wn=Vt}else{let Vt=document.createElement("div");if(Vt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Vt.id=`bubble-${I.id}`,Vt.setAttribute("data-message-id",I.id),Vt.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Vt.appendChild(Dt)}Vt.appendChild(Ht),Wn=Vt}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${I.id}`,Ht.setAttribute("data-wrapper-id",I.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),ne.push({messageId:I.id,fingerprint:xe,bubble:Wn});return}}}if(!st)if(I.variant==="reasoning"&&I.reasoning){if(!re)return;st=yl(I,o)}else if(I.variant==="tool"&&I.toolCall){if(!be)return;st=vl(I,o)}else if(I.variant==="approval"&&I.approval){if(o.approval===!1)return;st=El(I,o)}else{let bt=(tr=o.layout)==null?void 0:tr.messages;bt!=null&&bt.renderUserMessage&&I.role==="user"?st=bt.renderUserMessage({message:I,config:o,streaming:!!I.streaming}):bt!=null&&bt.renderAssistantMessage&&I.role==="assistant"?st=bt.renderAssistantMessage({message:I,config:o,streaming:!!I.streaming}):st=bl(I,h,bt,o.messageActions,j,{loadingIndicatorRenderer:_,widgetConfig:o}),I.role!=="user"&&st&&Rl(st,I,o,T)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${I.id}`,Pt.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Pt.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(st),_u(mo,I.id,xe,Pt),y.appendChild(Pt)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let Pe=ke.getAttribute("data-persona-ask-sheet-for");Pe&&!O.has(Pe)&&Jr(Le.composerOverlay,Pe)}),(it=(Ye=o.features)==null?void 0:Ye.toolCallDisplay)!=null&&it.grouped){let I=[],ke=[];m.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&be){ke.push(Pe);return}ke.length>1&&I.push(ke),ke=[]}),ke.length>1&&I.push(ke),I.forEach((Pe,qe)=>{var pn,Je;let xe=Pe.map(ct=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(xe.length<2)return;let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-tool-group-${qe}-${Pe[0].id}`,It.setAttribute("data-wrapper-id",`tool-group-${qe}-${Pe[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${Pe.length} tools`,Pt=(Je=(pn=o.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Je.call(pn,{messages:Pe,toolCalls:Pe.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:o});V(Xt,Pt)||(Xt.textContent=dn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),It.appendChild(st),xe[0].before(It),xe.forEach((ct,Tn)=>{let gn=document.createElement("div");gn.className="persona-tool-group-item persona-relative",gn.setAttribute("data-persona-tool-group-item","true"),Tn<xe.length-1&&gn.setAttribute("data-persona-tool-group-connector","true"),gn.appendChild(ct),An.appendChild(gn)})})}Vu(mo,z);let Te=m.some(I=>I.role==="assistant"&&I.streaming),Be=m[m.length-1],et=(Be==null?void 0:Be.role)==="assistant"&&!Be.streaming&&Be.variant!=="approval";if(Kn&&m.some(I=>I.role==="user")&&!Te&&!et){let I={config:o,streaming:!0,location:"standalone",defaultRenderer:Ks},ke=r.find(qe=>qe.renderLoadingIndicator),Pe=null;if(ke!=null&&ke.renderLoadingIndicator&&(Pe=ke.renderLoadingIndicator(I)),Pe===null&&((lt=o.loadingIndicator)!=null&&lt.render)&&(Pe=o.loadingIndicator.render(I)),Pe===null&&(Pe=Ks()),Pe){let qe=document.createElement("div"),xe=((Ie=o.loadingIndicator)==null?void 0:Ie.showBubble)!==!1;qe.className=xe?["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(" "),qe.setAttribute("data-typing-indicator","true"),qe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",qe.appendChild(Pe);let It=document.createElement("div");It.className="persona-flex",It.id="wrapper-typing-indicator",It.setAttribute("data-wrapper-id","typing-indicator"),It.appendChild(qe),y.appendChild(It)}}if(!Kn&&m.length>0){let I=m[m.length-1],ke={config:o,lastMessage:I,messageCount:m.length},Pe=r.find(xe=>xe.renderIdleIndicator),qe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(qe=Pe.renderIdleIndicator(ke)),qe===null&&((Me=o.loadingIndicator)!=null&&Me.renderIdle)&&(qe=o.loadingIndicator.renderIdle(ke)),qe){let xe=document.createElement("div"),It=(($e=o.loadingIndicator)==null?void 0:$e.showBubble)!==!1;xe.className=It?["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(" "),xe.setAttribute("data-idle-indicator","true"),xe.appendChild(qe);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(xe),y.appendChild(st)}}if(ti(c,y),pe.length>0)for(let{messageId:I,fingerprint:ke,bubble:Pe}of pe){let qe=c.querySelector(`#wrapper-${I}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",ke),Po.set(I,ke))}if(Po.size>0)for(let I of Po.keys())z.has(I)||Po.delete(I);if(ne.length>0)for(let{messageId:I,fingerprint:ke,bubble:Pe}of ne){let qe=c.querySelector(`#wrapper-${I}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",ke),So.set(I,ke))}if(So.size>0)for(let I of So.keys())z.has(I)||So.delete(I)},Xo=null,pa=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ge)||_e&&P.includes(_e)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ds=()=>{var m;if(!Xo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Xo,!0),Xo=null};ft.push(()=>ds());let Qo=null,ua=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ps=()=>{var m;if(!Qo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Qo,!0),Qo=null};ft.push(()=>ps());let Jo=!1,us=new Set,ma=()=>{var m,h,y,P;let c=(y=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var it,lt,Ie,Me;if(!E())return;let c=Le.peekBanner,m=Le.peekTextNode;if(!c||!m)return;if(k){c.classList.remove("persona-pill-peek--visible");return}let h=(it=T==null?void 0:T.getMessages())!=null?it:[],y;for(let $e=h.length-1;$e>=0;$e--){let I=h[$e];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,V=ma(),z=ai(V),O=z.type!=="none"?_s(z.type,V==null?void 0:V.plugins):null,Ce=((lt=O==null?void 0:O.isAnimating)==null?void 0:lt.call(O,y))===!0,pe=O!==null&&(_||Ce);pe&&O&&!us.has(O.name)&&(pl(O,e),us.add(O.name));let ne=pe&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;he&&he!==ne&&(m.classList.remove(he),delete m.dataset.personaPeekStreamClass),ne&&he!==ne&&(m.classList.add(ne),m.dataset.personaPeekStreamClass=ne),pe?(m.style.setProperty("--persona-stream-step",`${z.speed}ms`),m.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Te=pe?ii(P,z.buffer,O,y,_):P;if(pe&&z.placeholder==="skeleton"&&_&&(!Te||!Te.trim())){let $e=document.createElement("div"),I=$s();I.classList.add("persona-pill-peek__skeleton"),$e.appendChild(I),ti(m,$e)}else{let $e=Math.max(0,Te.length-100),I=Te.length>100?Te.slice(-100):Te,ke=Ls(I);if(!pe||!O){let Pe=Te.length>100?`\u2026${I}`:I;m.textContent!==Pe&&(m.textContent=Pe)}else{let Pe=ke;(O.wrap==="char"||O.wrap==="word")&&(Pe=Vs(ke,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:$e}));let qe=document.createElement("div");if(qe.innerHTML=Pe,O.useCaret&&I.length>0){let xe=li(),It=qe.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=It[It.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(xe,st.nextSibling):qe.appendChild(xe)}ti(m,qe),(Me=O.onAfterRender)==null||Me.call(O,{container:m,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Ye=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Ye)};if(E()){let c=Le.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),ft.push(()=>{c.removeEventListener("pointerdown",y)})}let m=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};ce.addEventListener("pointerenter",m),ce.addEventListener("pointerleave",h),ft.push(()=>{ce.removeEventListener("pointerenter",m),ce.removeEventListener("pointerleave",h)}),_e&&(_e.addEventListener("pointerenter",m),_e.addEventListener("pointerleave",h),ft.push(()=>{_e.removeEventListener("pointerenter",m),_e.removeEventListener("pointerleave",h)}))}let ga=c=>{var he,Te,Be,et,Ye,it,lt,Ie;let m=(Te=(he=o.launcher)==null?void 0:he.composerBar)!=null?Te:{},h=(Be=m.expandedSize)!=null?Be:"anchored",y=(et=m.bottomOffset)!=null?et:"16px",P=m.collapsedMaxWidth,_=(Ye=m.expandedMaxWidth)!=null?Ye:"880px",V=(it=m.expandedTopOffset)!=null?it:"5vh",z=(lt=m.modalMaxWidth)!=null?lt:"880px",O=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",Ce="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",ne=ge.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",_e){let Me=_e.style;Me.bottom=y,Me.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=z,ne.maxWidth=Ce,ne.maxHeight=O,ne.height=O;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${y} + ${pe})`,ne.top=V,ne.width=_,ne.maxWidth=Ce}},Zo=()=>{var O,Ce,pe,ne,he,Te,Be,et;if(!S())return;if(E()){let it=(pe=((Ce=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ce:{}).expandedSize)!=null?pe:"anchored",lt=k?"expanded":"collapsed";ge.dataset.state=lt,ge.dataset.expandedSize=it,_e&&(_e.dataset.state=lt,_e.dataset.expandedSize=it),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ga(k),de.style.display=k?"flex":"none",po(),k?(pa(),ua()):(ds(),ps()),Do();return}let c=un(o),m=(ne=e.ownerDocument.defaultView)!=null?ne:window,h=(Te=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Te:640,y=(et=(Be=o.launcher)==null?void 0:Be.mobileFullscreen)!=null?et:!0,P=m.innerWidth<=h,_=y&&P&&W,V=Mo(o).reveal;k?(ge.style.removeProperty("display"),ge.style.display=c?"flex":"",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!_?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.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"),ce.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"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Ge?Ge.element.style.display=c?"none":"":Qe&&(Qe.style.display=c?"none":""))},Bt=(c,m="user")=>{var _,V;if(!S()||k===c)return;let h=k;k=c,Zo();let y=(()=>{var Be,et,Ye,it,lt,Ie,Me,$e,I,ke;let z=(et=(Be=o.launcher)==null?void 0:Be.sidebarMode)!=null?et:!1,O=(Ye=e.ownerDocument.defaultView)!=null?Ye:window,Ce=(lt=(it=o.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,pe=(Me=(Ie=o.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Me:640,ne=O.innerWidth<=pe,he=un(o)&&Ce&&ne,Te=E()&&((ke=(I=($e=o.launcher)==null?void 0:$e.composerBar)==null?void 0:I.expandedSize)!=null?ke:"fullscreen")==="fullscreen";return z||Ce&&ne&&W||he||Te})();if(k&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=ul(O,(V=(_=o.launcher)==null?void 0:_.zIndex)!=null?V:bn))}Gt||(Gt=ml(e.ownerDocument))}else k||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);k&&(Yt(),Yo(!0));let P={open:k,source:m,timestamp:Date.now()};k&&!h?s.emit("widget:opened",P):!k&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:k,launcherEnabled:W,voiceActive:mt.active,streaming:T.isStreaming()})},Wr=c=>{jt(c?"stop":"send"),K&&(K.disabled=c),uo.buttons.forEach(m=>{m.disabled=c}),Ne.dataset.personaComposerStreaming=c?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Br=()=>{mt.active||Q&&Q.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Br(),200)});let ms=()=>{var h,y,P,_,V,z,O,Ce,pe,ne,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(_=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",Q.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=Y.querySelector("[data-persona-intro-card]");if(c){let Te=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Te?"":"none",Te?(Y.classList.remove("persona-gap-3"),Y.classList.add("persona-gap-6")):(Y.classList.remove("persona-gap-6"),Y.classList.add("persona-gap-3"))}!((pe=(Ce=o.sendButton)==null?void 0:Ce.useIcon)!=null&&pe)&&!(T!=null&&T.isStreaming())&&(Fe.textContent=(he=(ne=o.copy)==null?void 0:ne.sendButtonLabel)!=null?he:"Send"),Q.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Q.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 Ao=null,fa=()=>{Ao==null&&(Ao=setInterval(()=>{let c=Ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let m=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ua(m-y))})},100))};if(T=new Za(o,{onMessagesChanged(c){cr(Ve,c,me),fa(),T&&(c.some(P=>P.role==="user")?uo.render([],T,Q,c):uo.render(o.suggestionChips,T,Q,c,o.suggestionChipsConfig)),Yo(!Kn),da(c);let m=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;m&&m.id!==h&&(mt.lastUserMessageId=m.id,s.emit("user:message",m)),mt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Pr(c),Do()},onStatusChanged(c){var y;let m=(y=o.statusIndicator)!=null?y:{};tt(ln,(P=>{var _,V,z,O;return P==="idle"?(_=m.idleText)!=null?_:hn.idle:P==="connecting"?(V=m.connectingText)!=null?V:hn.connecting:P==="connected"?(z=m.connectedText)!=null?z:hn.connected:P==="error"?(O=m.errorText)!=null?O:hn.error:hn[P]})(c),m,c)},onStreamingChanged(c){Kn=c,Wr(c),T&&cr(Ve,T.getMessages(),me),c||Yo(!0),Do()},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":G(),ee();break;case"speaking":G(),te();break;default:c==="idle"&&T.isBargeInActive()?(G(),R(),K==null||K.setAttribute("aria-label","End voice session")):(mt.active=!1,G(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Pr()}}),Rt.current=T,((zc=(Uc=o.voiceRecognition)==null?void 0:Uc.provider)==null?void 0:zc.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&T.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(X||o.onSSEEvent)&&T.setSSEEventCallback((c,m)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,m),Ae==null||Ae.processEvent(c,m),X==null||X.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=Fl(c.metadata),M.syncFromMetadata()),(m=c.messages)!=null&&m.length&&T.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&T.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var m,h,y;!E()||k||!((y=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},fs=c=>{var P;if(c.preventDefault(),T.isStreaming()){T.cancel(),Ae==null||Ae.reset(),fe==null||fe.update();return}let m=Q.value.trim(),h=(P=Ze==null?void 0:Ze.hasAttachments())!=null?P:!1;if(!m&&!h)return;gs();let y;h&&(y=[],y.push(...Ze.getContentParts()),m&&y.push(il(m))),Q.value="",Q.style.height="auto",dr(),T.sendMessage(m,{contentParts:y}),h&&Ze.clearAttachments()},ha=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Hr={...ni},Dr=!1,dr=()=>{Hr={...ni}},ba=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),ya=c=>{if(!Q)return;Dr=!0,Q.value=c,Q.dispatchEvent(new Event("input",{bubbles:!0})),Dr=!1;let m=Q.value.length;Q.setSelectionRange(m,m)},hs=()=>{Dr||dr()},bs=c=>{if(Q){if(ha()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=Q.selectionStart===0&&Q.selectionEnd===0,h=Du({direction:c.key==="ArrowUp"?"up":"down",history:ba(),currentValue:Q.value,atStart:m,state:Hr});if(Hr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ya(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}dr(),c.preventDefault(),Fe.click()}}},ys=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(de)&&(T.cancel(),Ae==null||Ae.reset(),fe==null||fe.update(),dr(),c.preventDefault(),c.stopImmediatePropagation())},vs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!Ze)return;let m=nx(c.clipboardData);m.length!==0&&(c.preventDefault(),await Ze.handleFiles(m))},Sn=null,Gn=!1,Fo=null,rt=null,xs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,pr=(c="user")=>{var _,V,z,O,Ce,pe,ne;if(Gn||T.isStreaming())return;let m=xs();if(!m)return;Sn=new m;let y=(V=((_=o.voiceRecognition)!=null?_:{}).pauseDuration)!=null?V:2e3;Sn.continuous=!0,Sn.interimResults=!0,Sn.lang="en-US";let P=Q.value;Sn.onresult=he=>{let Te="",Be="";for(let Ye=0;Ye<he.results.length;Ye++){let it=he.results[Ye],lt=it[0].transcript;it.isFinal?Te+=lt+" ":Be=lt}let et=P+Te+Be;Q.value=et,Fo&&clearTimeout(Fo),(Te||Be)&&(Fo=window.setTimeout(()=>{let Ye=Q.value.trim();Ye&&Sn&&Gn&&(bo(),Q.value="",Q.style.height="auto",T.sendMessage(Ye,{viaVoice:!0}))},y))},Sn.onerror=he=>{he.error!=="no-speech"&&bo()},Sn.onend=()=>{if(Gn){let he=Q.value.trim();he&&he!==P.trim()&&(Q.value="",Q.style.height="auto",T.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Sn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),K){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(O=he.iconName)!=null?O:"mic",iconSize:parseFloat((ne=(pe=he.iconSize)!=null?pe:(Ce=o.sendButton)==null?void 0:Ce.size)!=null?ne:"40")||24};let Te=he.recordingBackgroundColor,Be=he.recordingIconColor,et=he.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Be!=null?Be:"var(--persona-voice-recording-indicator, #ffffff)",Be){let Ye=K.querySelector("svg");Ye&&Ye.setAttribute("stroke",Be)}et&&(K.style.borderColor=et),K.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Sn){try{Sn.stop()}catch{}Sn=null}if(mt.active=!1,ro(c),Rn(),K){if(K.classList.remove("persona-voice-recording"),rt){K.style.backgroundColor=rt.backgroundColor,K.style.color=rt.color,K.style.borderColor=rt.borderColor;let m=K.querySelector("svg");m&&m.setAttribute("stroke",rt.color||"currentColor"),rt=null}K.setAttribute("aria-label","Start voice recognition")}}},Fr=(c,m)=>{var it,lt,Ie,Me,$e,I,ke,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(h||y))return null;let _=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let z=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",O=(Ie=m==null?void 0:m.size)!=null?Ie:"40px",Ce=(Me=c==null?void 0:c.iconSize)!=null?Me:O,pe=parseFloat(Ce)||24,ne=($e=c==null?void 0:c.backgroundColor)!=null?$e:m==null?void 0:m.backgroundColor,he=(I=c==null?void 0:c.iconColor)!=null?I:m==null?void 0:m.textColor;V.style.width=Ce,V.style.height=Ce,V.style.minWidth=Ce,V.style.minHeight=Ce,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Be=Se(z,pe,he||"currentColor",1.5);Be?V.appendChild(Be):V.textContent="\u{1F3A4}",ne?V.style.backgroundColor=ne:V.style.backgroundColor="",c!=null&&c.borderWidth&&(V.style.borderWidth=c.borderWidth,V.style.borderStyle="solid"),c!=null&&c.borderColor&&(V.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(V.style.paddingLeft=c.paddingX,V.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(V.style.paddingTop=c.paddingY,V.style.paddingBottom=c.paddingY),_.appendChild(V);let et=(ke=c==null?void 0:c.tooltipText)!=null?ke:"Start voice recognition";if(((Pe=c==null?void 0:c.showTooltip)!=null?Pe:!1)&&et){let qe=b("div","persona-send-button-tooltip");qe.textContent=et,_.appendChild(qe)}return{micButton:V,micButtonWrapper:_}},Ue=()=>{var m,h,y,P,_;if(!K||rt)return;let c=(m=o.voiceRecognition)!=null?m:{};rt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.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}},A=(c,m)=>{var _,V,z,O,Ce;if(!K)return;let h=K.querySelector("svg");h&&h.remove();let y=(Ce=rt==null?void 0:rt.iconSize)!=null?Ce:parseFloat((O=(z=(_=o.voiceRecognition)==null?void 0:_.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?O:"40")||24,P=Se(c,y,m,1.5);P&&K.appendChild(P)},U=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},R=()=>{var P;if(!K)return;Ue();let c=(P=o.voiceRecognition)!=null?P:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(U(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let _=K.querySelector("svg");_&&_.setAttribute("stroke",h)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},ee=()=>{var z,O,Ce,pe,ne,he,Te,Be;if(!K)return;Ue();let c=(z=o.voiceRecognition)!=null?z:{},m=T.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(pe=(Ce=c.processingIconColor)!=null?Ce:rt==null?void 0:rt.color)!=null?pe:"",P=(he=(ne=c.processingBackgroundColor)!=null?ne:rt==null?void 0:rt.backgroundColor)!=null?he:"",_=(Be=(Te=c.processingBorderColor)!=null?Te:rt==null?void 0:rt.borderColor)!=null?Be:"";U(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=P,K.style.borderColor=_;let V=y||"currentColor";K.style.color=V,A(h,V),K.setAttribute("aria-label","Processing voice input"),m==="none"&&(K.style.cursor="default")},te=()=>{var Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me;if(!K)return;Ue();let c=(Ce=o.voiceRecognition)!=null?Ce:{},m=T.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",y=(pe=c.speakingIconName)!=null?pe:h,P=(Be=c.speakingIconColor)!=null?Be:m==="barge-in"?(he=(ne=c.recordingIconColor)!=null?ne:rt==null?void 0:rt.color)!=null?he:"":(Te=rt==null?void 0:rt.color)!=null?Te:"",_=(it=c.speakingBackgroundColor)!=null?it:m==="barge-in"?(et=c.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Ye=rt==null?void 0:rt.backgroundColor)!=null?Ye:"",V=(Me=c.speakingBorderColor)!=null?Me:m==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Ie=rt==null?void 0:rt.borderColor)!=null?Ie:"";U(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=_,K.style.borderColor=V;let z=P||"currentColor";K.style.color=z,A(y,z);let O=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",O),m==="none"&&(K.style.cursor="default"),m==="barge-in"&&K.classList.add("persona-voice-recording")},G=()=>{var c,m,h;K&&(U(),rt&&(K.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",K.style.color=(m=rt.color)!=null?m:"",K.style.borderColor=(h=rt.borderColor)!=null?h:"",A(rt.iconName,rt.color||"currentColor"),rt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},ze=()=>{var c,m;if(((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let h=T.getVoiceStatus(),y=T.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()});return}T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),mt.manuallyDeactivated=!T.isVoiceActive(),Rn(),ro("user"),T.isVoiceActive()?R():G()});return}if(Gn){let h=Q.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(Q.value="",Q.style.height="auto",T.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),pr("user")};Fn=ze,K&&(K.addEventListener("click",ze),ft.push(()=>{var c,m;((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),G()):bo("system"),K&&K.removeEventListener("click",ze)}));let De=s.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!mt.active&&!mt.manuallyDeactivated&&(((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("auto"),T.isVoiceActive()&&R()}):pr("auto"))},600))});ft.push(De);let at=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});ft.push(at);let Ke=()=>{Bt(!k,"user")},Ge=null,Qe=null;if(W&&!E()){let c=r.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ke).element,onToggle:Ke});m&&(Qe=m)}Qe||(Ge=qs(o,Ke))}Ge?e.appendChild(Ge.element):Qe&&e.appendChild(Qe),Zo(),uo.render(o.suggestionChips,T,Q,void 0,o.suggestionChipsConfig),ms(),Wr(T.isStreaming()),Yo(!0),aa(),H&&(!W||E()?setTimeout(()=>Br(),0):k&&setTimeout(()=>Br(),200));let Yt=()=>{var O,Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me,$e,I,ke,Pe,qe,xe,It,st,Xt;if(E()){yt(),Zo();return}let c=un(o),m=(Ce=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ce:!1,h=c||m||((ne=(pe=o.launcher)==null?void 0:pe.fullHeight)!=null?ne:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Be=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?Be:!0,_=(Ye=(et=o.launcher)==null?void 0:et.mobileBreakpoint)!=null?Ye:640,V=y.innerWidth<=_,z=P&&V&&W;try{if(z){po(),$r(e,o);return}if(w&&(w=!1,po(),$r(e,o)),!W&&!c){ce.style.height="",ce.style.width="";return}if(!m&&!c){let dn=(lt=(it=o==null?void 0:o.launcher)==null?void 0:it.width)!=null?lt:o==null?void 0:o.launcherWidth,Pt=dn!=null?dn:io;ce.style.width=Pt,ce.style.maxWidth=Pt}if(Co(),!h){let dn=y.innerHeight,Pt=64,An=(Me=(Ie=o.launcher)==null?void 0:Ie.heightOffset)!=null?Me:0,pn=Math.max(200,dn-Pt),Je=Math.min(640,pn),ct=Math.max(200,Je-An);ce.style.height=`${ct}px`}}finally{if(yt(),Zo(),k&&W){let Pt=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((ke=(I=o.launcher)==null?void 0:I.mobileBreakpoint)!=null?ke:640),An=(qe=(Pe=o.launcher)==null?void 0:Pe.sidebarMode)!=null?qe:!1,pn=(It=(xe=o.launcher)==null?void 0:xe.mobileFullscreen)!=null?It:!0,Je=un(o)&&pn&&Pt,ct=An||pn&&Pt&&W||Je;if(ct&&!Gt){let Tn=e.getRootNode(),gn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");gn&&!Kt&&(Kt=ul(gn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:bn)),Gt=ml(e.ownerDocument)}else ct||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Yt();let Tt=(qc=e.ownerDocument.defaultView)!=null?qc:window;if(Tt.addEventListener("resize",Yt),ft.push(()=>Tt.removeEventListener("resize",Yt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(Ne),ft.push(()=>c.disconnect())}fo=Y.scrollTop;let Lt=Y.scrollHeight,on=()=>{let c=Y.scrollTop,m=Y.scrollHeight,h=m<Lt;Lt=m;let{action:y,nextLastScrollTop:P}=ri({following:go.isFollowing(),currentScrollTop:c,lastScrollTop:fo,nearBottom:Os(Y,as),userScrollThreshold:ra,isAutoScrolling:Wo||ir||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=P,y==="resume"){Go();return}y==="pause"&&cs()};Y.addEventListener("scroll",on,{passive:!0}),ft.push(()=>Y.removeEventListener("scroll",on));let mn=c=>{let m=si({following:go.isFollowing(),deltaY:c.deltaY,nearBottom:Os(Y,as),resumeWhenNearBottom:!0});m==="pause"?cs():m==="resume"&&Go()};Y.addEventListener("wheel",mn,{passive:!0}),ft.push(()=>Y.removeEventListener("wheel",mn)),Et.addEventListener("click",()=>{Y.scrollTop=Y.scrollHeight,fo=Y.scrollTop,Go(),Yo(!0)}),ft.push(()=>Et.remove()),ft.push(()=>{ls()});let cn=()=>{N&&(jn&&(N.removeEventListener("click",jn),jn=null),S()?(N.style.display="",jn=()=>{Bt(!1,"user")},N.addEventListener("click",jn)):N.style.display="none")};cn(),(()=>{let{clearChatButton:c}=Le;c&&c.addEventListener("click",()=>{T.clearMessages(),mo.clear(),Go(),Jr(Le.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)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={},M.syncFromMetadata(),X==null||X.clear(),Ae==null||Ae.reset(),fe==null||fe.update()})})(),Ft&&Ft.addEventListener("submit",fs),Q==null||Q.addEventListener("keydown",bs),Q==null||Q.addEventListener("input",hs),Q==null||Q.addEventListener("paste",vs);let so=(jc=e.ownerDocument)!=null?jc:document;so.addEventListener("keydown",ys,!0);let Jl="persona-attachment-drop-active",ws=0,$i=()=>{ws=0,de.classList.remove(Jl)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&Ze!==null},Zl=c=>{!ki(c.dataTransfer)||!Or()||(ws++,ws===1&&de.classList.add(Jl))},ec=c=>{!ki(c.dataTransfer)||!Or()||(ws--,ws<=0&&$i())},tc=c=>{!ki(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},nc=c=>{var h;if(!ki(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),$i();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&Ze.handleFiles(m)},er=!0;de.addEventListener("dragenter",Zl,er),de.addEventListener("dragleave",ec,er),e.addEventListener("dragover",tc,er),e.addEventListener("drop",nc,er);let va=e.ownerDocument,oc=c=>{Or()&&c.preventDefault()},rc=c=>{Or()&&c.preventDefault()};va.addEventListener("dragover",oc),va.addEventListener("drop",rc),ft.push(()=>{Ft&&Ft.removeEventListener("submit",fs),Q==null||Q.removeEventListener("keydown",bs),Q==null||Q.removeEventListener("input",hs),Q==null||Q.removeEventListener("paste",vs),so.removeEventListener("keydown",ys,!0)}),ft.push(()=>{de.removeEventListener("dragenter",Zl,er),de.removeEventListener("dragleave",ec,er),e.removeEventListener("dragover",tc,er),e.removeEventListener("drop",nc,er),va.removeEventListener("dragover",oc),va.removeEventListener("drop",rc),$i()}),ft.push(()=>{T.cancel()}),Ge?ft.push(()=>{Ge==null||Ge.destroy()}):Qe&&ft.push(()=>{Qe==null||Qe.remove()});let en={update(c){var tn,To,No,xa,wa,Ca,hr,Sa,Cs,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,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;let m=o.toolCall,h=o.messageActions,y=(tn=o.layout)==null?void 0:tn.messages,P=o.colorScheme,_=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,O=(No=o.features)==null?void 0:No.showToolCalls,Ce=(xa=o.features)==null?void 0:xa.toolCallDisplay,pe=(wa=o.features)==null?void 0:wa.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ai(e,o),Ti(e,o),zn(),o.colorScheme!==P&&Ko();let ne=Wl.getForInstance(o.plugins);r.length=0,r.push(...ne),W=(hr=(Ca=o.launcher)==null?void 0:Ca.enabled)!=null?hr:!0,L=(Cs=(Sa=o.launcher)==null?void 0:Sa.autoExpand)!=null?Cs:!1,re=(ed=(Zc=o.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,be=(nd=(td=o.features)==null?void 0:td.showToolCalls)!=null?nd:!0,we=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},Ut(),Ho();let he=ie;if(ie=(ad=(sd=o.features)==null?void 0:sd.showEventStreamToggle)!=null?ad:!1,ie&&!he){if(X||(Z=new Xs(ye),X=new Ys(Ee,Z),Ae=Ae!=null?Ae:new Qs,Z.open().then(()=>X==null?void 0:X.restore()).catch(()=>{}),T.setSSEEventCallback((J,xt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,J,xt),Ae==null||Ae.processEvent(J,xt),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!ut&&Oe){let J=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.classNames,xt="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"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");ut=b("button",xt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ot=Se("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let dt=Le.clearChatButtonWrapper,Mt=Le.closeButtonWrapper,rn=dt||Mt;rn&&rn.parentNode===Oe?Oe.insertBefore(ut,rn):Oe.appendChild(ut),ut.addEventListener("click",()=>{le?On():xn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),X==null||X.clear(),Z==null||Z.destroy(),X=null,Z=null,Ae==null||Ae.reset(),Ae=null);if(((cd=o.launcher)==null?void 0:cd.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((pd=o.launcher)==null?void 0:pd.enabled)!==!1&&!Ge&&!Qe){let J=r.find(xt=>xt.renderLauncher);if(J!=null&&J.renderLauncher){let xt=J.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ke).element,onToggle:Ke});xt&&(Qe=xt,e.appendChild(Qe))}Qe||(Ge=qs(o,Ke),e.appendChild(Ge.element))}Ge&&Ge.update(o),He&&((ud=o.launcher)==null?void 0:ud.title)!==void 0&&(He.textContent=o.launcher.title),Xe&&((md=o.launcher)==null?void 0:md.subtitle)!==void 0&&(Xe.textContent=o.launcher.subtitle);let Te=(gd=o.layout)==null?void 0:gd.header;if((Te==null?void 0:Te.layout)!==v&&Oe){let J=Te?ui(o,Te,{showClose:S(),onClose:()=>Bt(!1,"user")}):Sr({config:o,showClose:S(),onClose:()=>Bt(!1,"user")});Oe.replaceWith(J.header),Oe=J.header,se=J.iconHolder,He=J.headerTitle,Xe=J.headerSubtitle,N=J.closeButton,v=Te==null?void 0:Te.layout}else if(Te&&(se&&(se.style.display=Te.showIcon===!1?"none":""),He&&(He.style.display=Te.showTitle===!1?"none":""),Xe&&(Xe.style.display=Te.showSubtitle===!1?"none":""),N&&(N.style.display=Te.showCloseButton===!1?"none":""),Le.clearChatButtonWrapper)){let J=Te.showClearChat;if(J!==void 0){Le.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:xt}=Le;xt&&!xt.classList.contains("persona-absolute")&&(J?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let et=((fd=o.layout)==null?void 0:fd.showHeader)!==!1;Oe&&(Oe.style.display=et?"":"none");let Ye=((hd=o.layout)==null?void 0:hd.showFooter)!==!1;Ne&&(Ne.style.display=Ye?"":"none"),yt(),Ho(),W!==B?W?Bt(L,"auto"):(k=!0,Zo()):L!==D&&Bt(L,"auto"),D=L,B=W,Yt(),cn();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(m),Me=JSON.stringify(o.messageActions)!==JSON.stringify(h),$e=JSON.stringify((bd=o.layout)==null?void 0:bd.messages)!==JSON.stringify(y),I=((yd=o.loadingIndicator)==null?void 0:yd.render)!==(_==null?void 0:_.render)||((vd=o.loadingIndicator)==null?void 0:vd.renderIdle)!==(_==null?void 0:_.renderIdle)||((xd=o.loadingIndicator)==null?void 0:xd.showBubble)!==(_==null?void 0:_.showBubble),ke=o.iterationDisplay!==V,Pe=((Cd=(wd=o.features)==null?void 0:wd.showReasoning)!=null?Cd:!0)!==(z!=null?z:!0)||((Ad=(Sd=o.features)==null?void 0:Sd.showToolCalls)!=null?Ad:!0)!==(O!=null?O:!0)||JSON.stringify((Td=o.features)==null?void 0:Td.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((kd=o.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(pe);(Ie||Me||$e||I||ke||Pe)&&T&&(ss++,cr(Ve,T.getMessages(),me));let xe=(Ed=o.launcher)!=null?Ed:{},It=(Md=xe.headerIconHidden)!=null?Md:!1,st=(Id=(Ld=o.layout)==null?void 0:Ld.header)==null?void 0:Id.showIcon,Xt=It||st===!1,dn=xe.headerIconName,Pt=(Rd=xe.headerIconSize)!=null?Rd:"48px";if(se){let J=de.querySelector(".persona-border-b-persona-divider"),xt=J==null?void 0:J.querySelector(".persona-flex-col");if(Xt)se.style.display="none",J&&xt&&!J.contains(xt)&&J.insertBefore(xt,J.firstChild);else{if(se.style.display="",se.style.height=Pt,se.style.width=Pt,J&&xt&&(J.contains(se)?se.nextSibling!==xt&&(se.remove(),J.insertBefore(se,xt)):J.insertBefore(se,xt)),dn){let dt=parseFloat(Pt)||24,Mt=Se(dn,dt*.6,"#ffffff",2);Mt?se.replaceChildren(Mt):se.textContent=(Pd=xe.agentIconText)!=null?Pd:"\u{1F4AC}"}else if(xe.iconUrl){let dt=se.querySelector("img");if(dt)dt.src=xe.iconUrl,dt.style.height=Pt,dt.style.width=Pt;else{let Mt=document.createElement("img");Mt.src=xe.iconUrl,Mt.alt="",Mt.className="persona-rounded-xl persona-object-cover",Mt.style.height=Pt,Mt.style.width=Pt,se.replaceChildren(Mt)}}else{let dt=se.querySelector("svg"),Mt=se.querySelector("img");(dt||Mt)&&se.replaceChildren(),se.textContent=(Wd=xe.agentIconText)!=null?Wd:"\u{1F4AC}"}let Ot=se.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Hd=(Bd=o.layout)==null?void 0:Bd.header)==null?void 0:Hd.showTitle,pn=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showSubtitle;if(He&&(He.style.display=An===!1?"none":""),Xe&&(Xe.style.display=pn===!1?"none":""),N){((Nd=(Od=o.layout)==null?void 0:Od.header)==null?void 0:Nd.showCloseButton)===!1?N.style.display="none":N.style.display="";let xt=(_d=xe.closeButtonSize)!=null?_d:"32px",Ot=(Vd=xe.closeButtonPlacement)!=null?Vd:"inline";N.style.height=xt,N.style.width=xt;let{closeButtonWrapper:dt}=Le,Mt=Ot==="top-right",rn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Mt!==rn)if(dt.remove(),Mt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let pt=(Ud=($d=xe.clearChat)==null?void 0:$d.placement)!=null?Ud:"inline",sn=(qd=(zd=xe.clearChat)==null?void 0:zd.enabled)!=null?qd:!0;dt.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=de.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(dt)}if(N.style.color=xe.closeButtonColor||Mn.actionIconColor,xe.closeButtonBackgroundColor?(N.style.backgroundColor=xe.closeButtonBackgroundColor,N.classList.remove("hover:persona-bg-gray-100")):(N.style.backgroundColor="",N.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";N.style.border=`${pt} solid ${sn}`,N.classList.remove("persona-border-none")}else N.style.border="",N.classList.add("persona-border-none");xe.closeButtonBorderRadius?(N.style.borderRadius=xe.closeButtonBorderRadius,N.classList.remove("persona-rounded-full")):(N.style.borderRadius="",N.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(N.style.paddingLeft=xe.closeButtonPaddingX,N.style.paddingRight=xe.closeButtonPaddingX):(N.style.paddingLeft="",N.style.paddingRight=""),xe.closeButtonPaddingY?(N.style.paddingTop=xe.closeButtonPaddingY,N.style.paddingBottom=xe.closeButtonPaddingY):(N.style.paddingTop="",N.style.paddingBottom="");let fn=(jd=xe.closeButtonIconName)!=null?jd:"x",yo=(Kd=xe.closeButtonIconText)!=null?Kd:"\xD7";N.innerHTML="";let En=Se(fn,"28px","currentColor",1);En?N.appendChild(En):N.textContent=yo;let Qt=(Gd=xe.closeButtonTooltipText)!=null?Gd:"Close chat",Xn=(Yd=xe.closeButtonShowTooltip)!=null?Yd:!0;if(N.setAttribute("aria-label",Qt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!N)return;let br=N.ownerDocument,Ss=br.body;if(!Ss)return;pt=Eo(br,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(br,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let yr=N.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(nr),pt.style.left=`${yr.left+yr.width/2}px`,pt.style.top=`${yr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};dt.addEventListener("mouseenter",sn),dt.addEventListener("mouseleave",Hn),N.addEventListener("focus",sn),N.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",sn),dt.removeEventListener("mouseleave",Hn)),N&&(N.removeEventListener("focus",sn),N.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:ct}=Le;if(Je){let J=(Xd=xe.clearChat)!=null?Xd:{},xt=(Qd=J.enabled)!=null?Qd:!0,Ot=(Zd=(Jd=o.layout)==null?void 0:Jd.header)==null?void 0:Zd.showClearChat,dt=Ot!==void 0?Ot:xt,Mt=(ep=J.placement)!=null?ep:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:rn}=Le;!E()&&rn&&!rn.classList.contains("persona-absolute")&&(dt?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let fn=Mt==="top-right",yo=ct.classList.contains("persona-absolute");if(!E()&&fn!==yo&&dt){if(ct.remove(),fn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Qt=de.querySelector(".persona-border-b-persona-divider"),Xn=Le.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(ct,Xn):Qt&&Qt.appendChild(ct)}let En=Le.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(fn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(dt){if(!E()){let pt=(tp=J.size)!=null?tp:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(np=J.iconName)!=null?np:"refresh-cw",fn=(op=J.iconColor)!=null?op:"";Je.style.color=fn||Mn.actionIconColor,Je.innerHTML="";let yo=E()?"14px":"20px",En=Se(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),J.backgroundColor?(Je.style.backgroundColor=J.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let pt=J.borderWidth||"0px",sn=J.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");J.borderRadius?(Je.style.borderRadius=J.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),J.paddingX?(Je.style.paddingLeft=J.paddingX,Je.style.paddingRight=J.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),J.paddingY?(Je.style.paddingTop=J.paddingY,Je.style.paddingBottom=J.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(rp=J.tooltipText)!=null?rp:"Clear chat",Xn=(sp=J.showTooltip)!=null?sp:!0;if(Je.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let br=Je.ownerDocument,Ss=br.body;if(!Ss)return;pt=Eo(br,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(br,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let yr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(nr),pt.style.left=`${yr.left+yr.width/2}px`,pt.style.top=`${yr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hl],gn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick];M=Dl({parsers:Tn,handlers:gn,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Dm(o,M,q),T.updateConfig(o),cr(Ve,T.getMessages(),me),uo.render(o.suggestionChips,T,Q,void 0,o.suggestionChipsConfig),ms(),Wr(T.isStreaming());let ur=((ap=o.voiceRecognition)==null?void 0:ap.enabled)===!0,mr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gr=((lp=(ip=o.voiceRecognition)==null?void 0:ip.provider)==null?void 0:lp.type)==="runtype";if(ur&&(mr||gr))if(!K||!gt){let J=Fr(o.voiceRecognition,o.sendButton);J&&(K=J.micButton,gt=J.micButtonWrapper,Nt.insertBefore(gt,Ln),K.addEventListener("click",ze),K.disabled=T.isStreaming())}else{let J=(cp=o.voiceRecognition)!=null?cp:{},xt=(dp=o.sendButton)!=null?dp:{},Ot=(pp=J.iconName)!=null?pp:"mic",dt=(up=xt.size)!=null?up:"40px",Mt=(mp=J.iconSize)!=null?mp:dt,rn=parseFloat(Mt)||24;K.style.width=Mt,K.style.height=Mt,K.style.minWidth=Mt,K.style.minHeight=Mt;let fn=(fp=(gp=J.iconColor)!=null?gp:xt.textColor)!=null?fp:"currentColor";K.innerHTML="";let yo=Se(Ot,rn,fn,2);yo?K.appendChild(yo):K.textContent="\u{1F3A4}";let En=(hp=J.backgroundColor)!=null?hp:xt.backgroundColor;En?K.style.backgroundColor=En:K.style.backgroundColor="",fn?K.style.color=fn:K.style.color="var(--persona-text, #111827)",J.borderWidth?(K.style.borderWidth=J.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),J.borderColor?K.style.borderColor=J.borderColor:K.style.borderColor="",J.paddingX?(K.style.paddingLeft=J.paddingX,K.style.paddingRight=J.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),J.paddingY?(K.style.paddingTop=J.paddingY,K.style.paddingBottom=J.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Qt=gt==null?void 0:gt.querySelector(".persona-send-button-tooltip"),Xn=(bp=J.tooltipText)!=null?bp:"Start voice recognition";if(((yp=J.showTooltip)!=null?yp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,gt==null||gt.insertBefore(sn,K)}else Qt&&(Qt.style.display="none");gt.style.display="",K.disabled=T.isStreaming()}else K&&gt&&(gt.style.display="none",((xp=(vp=o.voiceRecognition)==null?void 0:vp.provider)==null?void 0:xp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Gn&&bo());if(((wp=o.attachments)==null?void 0:wp.enabled)===!0)if(!$t||!nt){let J=(Cp=o.attachments)!=null?Cp:{},Ot=(Ap=((Sp=o.sendButton)!=null?Sp:{}).size)!=null?Ap:"40px";ve||(ve=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ve.style.display="none",Ft.insertBefore(ve,Q)),ae||(ae=document.createElement("input"),ae.type="file",ae.accept=((Tp=J.allowedTypes)!=null?Tp:_o).join(","),ae.multiple=((kp=J.maxFiles)!=null?kp:4)>1,ae.style.display="none",ae.setAttribute("aria-label","Attach files"),Ft.insertBefore(ae,Q)),$t=b("div","persona-send-button-wrapper"),nt=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),nt.type="button",nt.setAttribute("aria-label",(Ep=J.buttonTooltipText)!=null?Ep:"Attach file");let dt=(Mp=J.buttonIconName)!=null?Mp:"paperclip",Mt=Ot,rn=parseFloat(Mt)||40,fn=Math.round(rn*.6);nt.style.width=Mt,nt.style.height=Mt,nt.style.minWidth=Mt,nt.style.minHeight=Mt,nt.style.fontSize="18px",nt.style.lineHeight="1",nt.style.backgroundColor="transparent",nt.style.color="var(--persona-primary, #111827)",nt.style.border="none",nt.style.borderRadius="6px",nt.style.transition="background-color 0.15s ease",nt.addEventListener("mouseenter",()=>{nt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),nt.addEventListener("mouseleave",()=>{nt.style.backgroundColor="transparent"});let yo=Se(dt,fn,"currentColor",1.5);yo?nt.appendChild(yo):nt.textContent="\u{1F4CE}",nt.addEventListener("click",Xn=>{Xn.preventDefault(),ae==null||ae.click()}),$t.appendChild(nt);let En=(Lp=J.buttonTooltipText)!=null?Lp:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,$t.appendChild(Qt),St.append($t),!Ze&&ae&&ve&&(Ze=Ds.fromConfig(J),Ze.setPreviewsContainer(ve),ae.addEventListener("change",async()=>{Ze&&(ae!=null&&ae.files)&&(await Ze.handleFileSelect(ae.files),ae.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Fm(J.dropOverlay))}else{$t.style.display="";let J=(Ip=o.attachments)!=null?Ip:{};ae&&(ae.accept=((Rp=J.allowedTypes)!=null?Rp:_o).join(","),ae.multiple=((Pp=J.maxFiles)!=null?Pp:4)>1),Ze&&Ze.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else $t&&($t.style.display="none"),Ze&&Ze.clearAttachments(),(Wp=de.querySelector(".persona-attachment-drop-overlay"))==null||Wp.remove();let zt=(Bp=o.sendButton)!=null?Bp:{},fr=(Hp=zt.useIcon)!=null?Hp:!1,tr=(Dp=zt.iconText)!=null?Dp:"\u2191",bt=zt.iconName,Pn=(Fp=zt.tooltipText)!=null?Fp:"Send message",Oo=(Op=zt.showTooltip)!=null?Op:!1,kn=(Np=zt.size)!=null?Np:"40px",Wn=zt.backgroundColor,Ht=zt.textColor;if(fr){if(Fe.style.width=kn,Fe.style.height=kn,Fe.style.minWidth=kn,Fe.style.minHeight=kn,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.innerHTML="",Ht?Fe.style.color=Ht:Fe.style.color="var(--persona-button-primary-fg, #ffffff)",bt){let J=parseFloat(kn)||24,xt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Se(bt,J,xt,2);Ot?Fe.appendChild(Ot):Fe.textContent=tr}else Fe.textContent=tr;Fe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-primary")):(Fe.style.backgroundColor="",Fe.classList.add("persona-bg-persona-primary"))}else Fe.textContent=(Vp=(_p=o.copy)==null?void 0:_p.sendButtonLabel)!=null?Vp:"Send",Fe.style.width="",Fe.style.height="",Fe.style.minWidth="",Fe.style.minHeight="",Fe.style.fontSize="",Fe.style.lineHeight="",Fe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-accent")):Fe.classList.add("persona-bg-persona-accent"),Ht?Fe.style.color=Ht:Fe.classList.add("persona-text-white");zt.borderWidth?(Fe.style.borderWidth=zt.borderWidth,Fe.style.borderStyle="solid"):(Fe.style.borderWidth="",Fe.style.borderStyle=""),zt.borderColor?Fe.style.borderColor=zt.borderColor:Fe.style.borderColor="",zt.paddingX?(Fe.style.paddingLeft=zt.paddingX,Fe.style.paddingRight=zt.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),zt.paddingY?(Fe.style.paddingTop=zt.paddingY,Fe.style.paddingBottom=zt.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Vt=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Vt)Vt.textContent=Pn,Vt.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Pn,Ln==null||Ln.insertBefore(J,Fe)}else Vt&&(Vt.style.display="none");let Dt=(jp=($p=o.layout)==null?void 0:$p.contentMaxWidth)!=null?jp:E()?(qp=(zp=(Up=o.launcher)==null?void 0:Up.composerBar)==null?void 0:zp.contentMaxWidth)!=null?qp:"720px":void 0;Dt?(Ve.style.maxWidth=Dt,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",Ft&&(Ft.style.maxWidth=Dt,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=Dt,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let qt=(Kp=o.statusIndicator)!=null?Kp:{},Bn=(Gp=qt.visible)!=null?Gp:!0;if(ln.style.display=Bn?"":"none",T){let J=T.getStatus();tt(ln,(Ot=>{var dt,Mt,rn,fn;return Ot==="idle"?(dt=qt.idleText)!=null?dt:hn.idle:Ot==="connecting"?(Mt=qt.connectingText)!=null?Mt:hn.connecting:Ot==="connected"?(rn=qt.connectedText)!=null?rn:hn.connected:Ot==="error"?(fn=qt.errorText)!=null?fn:hn.error:hn[Ot]})(J),qt,J)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=qt.align==="left"?"persona-text-left":qt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){S()&&Bt(!0,"api")},close(){S()&&Bt(!1,"api")},toggle(){S()&&Bt(!k,"api")},clearChat(){wn=!1,T.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)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={},M.syncFromMetadata(),X==null||X.clear(),Ae==null||Ae.reset(),fe==null||fe.update()},setMessage(c){return!Q||T.isStreaming()?!1:(!k&&S()&&Bt(!0,"system"),Q.value=c,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let m=(c==null?void 0:c.trim())||Q.value.trim();return m?(!k&&S()&&Bt(!0,"system"),Q.value="",Q.style.height="auto",T.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return T.isStreaming()?!1:((h=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!k&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("user"),T.isVoiceActive()&&R()})),!0):Gn?!0:xs()?(!k&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),pr("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!k&&S()&&Bt(!0,"system");let m=T.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),m},injectUserMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!k&&S()&&Bt(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!k&&S()&&Bt(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!k&&S()&&Bt(!0,"system"),T.injectTestEvent(c)},async connectStream(c,m){return T.connectStream(c,m)},__pushEventStreamEvent(c){X&&(Ae==null||Ae.processEvent(c.type,c.payload),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!X||xn()},hideEventStream(){le&&On()},isEventStreamVisible(){return le},showArtifacts(){co(o)&&(wn=!1,zn(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(wn=!0,zn())},upsertArtifact(c){return co(o)?(wn=!1,T.upsertArtifact(c)):null},selectArtifact(c){co(o)&&T.selectArtifact(c)},clearArtifacts(){co(o)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return W&&!k&&!E()||!Q?!1:(Q.focus(),!0)},async resolveApproval(c,m){let y=T.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"){T.resolveWebMcpApproval(y.id,m);return}return T.resolveApproval(y.approval,m)},getMessages(){return T.getMessages()},getStatus(){return T.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 S()&&k},isVoiceActive(){return mt.active},getState(){return{open:S()&&k,launcherEnabled:W,voiceActive:mt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!k&&S()&&Bt(!0,"system");let m=Ve.querySelector(".persona-feedback-container");m&&m.remove();let h=Wm({onSubmit:async(y,P)=>{var _;T.isClientTokenMode()&&await T.submitCSATFeedback(y,P),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!k&&S()&&Bt(!0,"system");let m=Ve.querySelector(".persona-feedback-container");m&&m.remove();let h=Bm({onSubmit:async(y,P)=>{var _;T.isClientTokenMode()&&await T.submitNPSFeedback(y,P),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return T.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return T.submitNPSFeedback(c,m)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),ft.forEach(c=>c()),ge.remove(),_e==null||_e.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),jn&&N.removeEventListener("click",jn)}};if((((Kc=n==null?void 0:n.debugTools)!=null?Kc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:h=>h?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ft.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=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",m),ft.push(()=>{window.removeEventListener("persona:focusInput",m)}),ie){let z=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.showEventStream()},O=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),ft.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&en.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&en.hideArtifacts()},P=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&en.upsertArtifact(O.artifact)},_=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&en.selectArtifact(O.id)},V=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",_),window.addEventListener("persona:clearArtifacts",V),ft.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",_),window.removeEventListener("persona:clearArtifacts",V)})}let ao=ox(o.persistState);if(ao&&S()){let c=rx(ao.storage),m=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Gc=ao.persist)==null?void 0:Gc.openState)&&c.getItem(m)==="true",_=((Yc=ao.persist)==null?void 0:Yc.voiceState)&&c.getItem(h)==="true",V=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{en.open(),setTimeout(()=>{var z;if(_||V)en.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Qc=ao.persist)!=null&&Qc.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Jc=ao.persist)!=null&&Jc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),ft.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return u&&S()&&setTimeout(()=>{en.open()},0),Do(),en};var sx=(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},Nm=(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"},Vl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},_m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Vl(e)},Ol=e=>{e.style.transition=""},Nl=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=""},_l=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ei=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ax=(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))},ix=(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)},Vm=(e,t,n,o,r,s,a)=>{var x,C,M,W,L,H;let i=Mo(s),d=i.reveal==="push";ax(e,t,n,o,d),ix(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=(W=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?W:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Nl(t),Ol(o),_m(o),_l(n),Ei(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((H=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?H:bn),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"),_m(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Nl(t),Ol(o),_l(n),Ei(r,o);let D=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":B;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=D,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",Ol(o),Vl(o),Ei(r,o);let D=sx(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",w=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}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=`${B+D}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=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}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="",Nl(t),Vl(o),_l(n),Ei(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=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 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||w?"hidden":"visible",o.style.transition=v,D&&(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")}},lx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Nm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Nm(n,o)},destroy(){n.remove()}}},cx=(e,t)=>{var L,H,D,B;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=(H=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||H?(B=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?B:!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(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Vm(a,i,d,l,u,t,p)}),f.observe(a))},C=()=>{Vm(a,i,d,l,u,t,p),x()},M=a.ownerDocument.defaultView,W=()=>{C()};return M==null||M.addEventListener("resize",W),Mo(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,E;t=v,((E=(w=t==null?void 0:t.launcher)==null?void 0:w.enabled)!=null?E:!0)===!1&&(p=!0),C()},destroy(){M==null||M.removeEventListener("resize",W),g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},$m=(e,t)=>un(t)?cx(e,t):lx(e,t);var ts={desktop:{w:1280,h:800},mobile:{w:390,h:844}},$l=.15,Ul=1.5,Mi="persona-preview-shell-theme",Um={load:()=>null,save:()=>{},clear:()=>{}},zm=["How do I get started?","Pricing & plans","Talk to support"];function Li(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qm(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 zl(e){let t=qm(e);return`* { box-sizing: border-box; }
107
+ `}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",jt=g?"":"padding-top: 1.25em !important;",Bn=g?"":`z-index: ${(Ut=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Ut:hn} !important;`;ye.style.cssText+=Dt+jt+Bn}L()};po(),$r(e,o),Ti(e,o),ki(e,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",zo)});let Kt=null,Gt=null;gt.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),_n&&gt.push(()=>{_n==null||_n.disconnect(),_n=null}),gt.push(()=>{wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ie&&gt.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),Se==null||Se.destroy(),Se=null,Y==null||Y.destroy(),Y=null,J=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=nu(()=>{$r(e,o)}))};Ko(),gt.push(()=>{qn&&(qn(),qn=null)});let oo=(_c=o.features)==null?void 0:_c.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=_s(oo.type,oo.plugins);c&&(ul(c,e),gt.push(()=>zu(e)))}let uo=um(Et),jn=null,T,Kn=!1,mo=Ou(),Po=new Map,So=new Map,ss=0,go=ri(),fo=0,ho=null,Wo=!1,lr=!1,ra=4,as=24,sa=80,Pr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=($c=(Vc=o.voiceRecognition)==null?void 0:Vc.autoResume)!=null?$c:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{u(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Ol(d.voiceState),g=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-h<ex&&setTimeout(()=>{var N,V;mt.active||(mt.manuallyDeactivated=!1,((V=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:V.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("restore"),T.isVoiceActive()&&U()}):ur("restore"))},1e3)},ia=()=>T?Hm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Wr(c){if(!(i!=null&&i.save))return;let h={messages:c?Hm(c):T?ia():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.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 Bo=null,la=()=>ye.querySelector("#persona-scroll-container")||K,cr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},ls=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!1,cr()},Ho=()=>{if(!yn()||de){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==ce&&ce.appendChild(Tt),bt();let c=Fs(K)>0;Tt.style.display=go.isFollowing()||!c?"none":""},cs=()=>{go.pause()&&(ls(),Ho())},Go=()=>{go.resume(),Ho()},Yo=(c=!1)=>{go.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!0,ho=requestAnimationFrame(()=>{ho=null,lr=!1,go.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,g=500)=>{let h=c.scrollTop,y=Fs(c),P=y-h;if(Math.abs(P)<1){fo=c.scrollTop;return}if(Math.abs(P)>=sa){cr(),Wo=!0,c.scrollTop=y,fo=c.scrollTop,Wo=!1;return}cr();let N=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!go.isFollowing()){cr();return}let Ae=Fs(c);Ae!==y&&(y=Ae,P=y-h);let ue=O-N,ee=Math.min(ue/g,1),he=V(ee),Ee=h+P*he;c.scrollTop=Ee,fo=c.scrollTop,ee<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,fo=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},da=c=>{let g=new Map;c.forEach(h=>{let y=Pr.get(h.id);g.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}))}),Pr.clear(),g.forEach((h,y)=>{Pr.set(y,h)})},dr=(c,g,h)=>{var Ye,at,it,Pe,Re,qe;let y=document.createElement("div"),N=(()=>{var Me;let L=r.find(We=>We.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((Me=o.loadingIndicator)!=null&&Me.render)return o.loadingIndicator.render})(),V=(L,Me)=>Me==null?!1:typeof Me=="string"?(L.textContent=Me,!0):(L.appendChild(Me),!0),z=new Set,O=new Set,Ae=r.some(L=>L.renderAskUserQuestion),ue=[],ee=[],he=o.enableComponentStreaming!==!1;if(g.forEach(L=>{var An,dn,Je,lt,Tn,mn,mr,gr,fr,Nr,_r,qt,hr,nr;z.add(L.id);let Me=Ae&&Tr(L),We=!Me&&L.role==="assistant"&&!L.variant&&he&&Rm(L);if(!We&&So.has(L.id)){let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),So.delete(L.id)}let Ke=Tr(L)?`:${(An=L.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(dn=L.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ce=Fu(L,ss)+Ke,Lt=Me||We?null:Nu(mo,L.id,Ce);if(Lt){y.appendChild(Lt.cloneNode(!0)),Tr(L)&&((Je=L.toolCall)!=null&&Je.id)&&((lt=L.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((Tn=L.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}let st=null,Xt=r.find(ht=>!!(L.variant==="reasoning"&&ht.renderReasoning||L.variant==="tool"&&ht.renderToolCall||L.variant==="approval"&&ht.renderApproval||!L.variant&&ht.renderMessage)),cn=(mn=o.layout)==null?void 0:mn.messages;if(Tr(L)&&((mr=L.agentMetadata)==null?void 0:mr.askUserQuestionAnswered)===!0){Po.delete(L.id);let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(Tr(L)&&((fr=(gr=o.features)==null?void 0:gr.askUserQuestion)==null?void 0:fr.enabled)!==!1){let ht=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&It.current){let Pn=Po.get(L.id),Oo=Pn!==Ce,kn=null;if(Oo){let{payload:Ut,complete:Dt}=Xr(L),jt=L.id,Bn=()=>{var Yn;return(Yn=It.current)==null?void 0:Yn.getMessages().find(en=>en.id===jt)};kn=ht.renderAskUserQuestion({message:L,payload:Ut,complete:Dt,resolve:Yn=>{var To;let en=Bn();en&&((To=It.current)==null||To.resolveAskUserQuestion(en,Yn))},dismiss:()=>{var en,To,No;let Yn=Bn();(en=Yn==null?void 0:Yn.agentMetadata)!=null&&en.awaitingLocalTool&&((To=It.current)==null||To.markAskUserQuestionResolved(Yn),(No=It.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=L.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=L.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),ue.push({messageId:L.id,fingerprint:Ce,bubble:kn});return}else{((qt=L.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((hr=L.agentMetadata)!=null&&hr.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}}else if(Xt)if(L.variant==="reasoning"&&L.reasoning&&Xt.renderReasoning){if(!se)return;st=Xt.renderReasoning({message:L,defaultRenderer:()=>vl(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&Xt.renderToolCall){if(!ge)return;st=Xt.renderToolCall({message:L,defaultRenderer:()=>xl(L,o),config:o})}else if(L.variant==="approval"&&L.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:L,defaultRenderer:()=>Ml(L,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:L,defaultRenderer:()=>{let ht=yl(L,h,cn,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o});return L.role!=="user"&&Pl(ht,L,o,T),ht},config:o}));if(!st&&We){let ht=Pm(L);if(ht){let Pn=So.get(L.id),Oo=Pn!==Ce,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Lm(ht,{config:o,message:L,transform:h});if(Ht)if(kn){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),Ut.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),ee.push({messageId:L.id,fingerprint:Ce,bubble:Wn});return}}}if(!st)if(L.variant==="reasoning"&&L.reasoning){if(!se)return;st=vl(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!ge)return;st=xl(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;st=Ml(L,o)}else{let ht=(nr=o.layout)==null?void 0:nr.messages;ht!=null&&ht.renderUserMessage&&L.role==="user"?st=ht.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):ht!=null&&ht.renderAssistantMessage&&L.role==="assistant"?st=ht.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):st=yl(L,h,ht,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o}),L.role!=="user"&&st&&Pl(st,L,o,T)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${L.id}`,Pt.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Pt.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(st),_u(mo,L.id,Ce,Pt),y.appendChild(Pt)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Me=>{let We=Me.getAttribute("data-persona-ask-sheet-for");We&&!O.has(We)&&Jr(Be.composerOverlay,We)}),(at=(Ye=o.features)==null?void 0:Ye.toolCallDisplay)!=null&&at.grouped){let L=[],Me=[];g.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&ge){Me.push(We);return}Me.length>1&&L.push(Me),Me=[]}),Me.length>1&&L.push(Me),L.forEach((We,Ke)=>{var dn,Je;let Ce=We.map(lt=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===lt.id)).filter(lt=>!!lt);if(Ce.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Ke}-${We[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Ke}-${We[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${We.length} tools`,Pt=(Je=(dn=o.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Je.call(dn,{messages:We,toolCalls:We.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:o});V(Xt,Pt)||(Xt.textContent=cn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),Lt.appendChild(st),Ce[0].before(Lt),Ce.forEach((lt,Tn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Tn<Ce.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(lt),An.appendChild(mn)})})}Vu(mo,z);let Ee=g.some(L=>L.role==="assistant"&&L.streaming),Oe=g[g.length-1],tt=(Oe==null?void 0:Oe.role)==="assistant"&&!Oe.streaming&&Oe.variant!=="approval";if(Kn&&g.some(L=>L.role==="user")&&!Ee&&!tt){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Ks},Me=r.find(Ke=>Ke.renderLoadingIndicator),We=null;if(Me!=null&&Me.renderLoadingIndicator&&(We=Me.renderLoadingIndicator(L)),We===null&&((it=o.loadingIndicator)!=null&&it.render)&&(We=o.loadingIndicator.render(L)),We===null&&(We=Ks()),We){let Ke=document.createElement("div"),Ce=((Pe=o.loadingIndicator)==null?void 0:Pe.showBubble)!==!1;Ke.className=Ce?["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(" "),Ke.setAttribute("data-typing-indicator","true"),Ke.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ke.appendChild(We);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Ke),y.appendChild(Lt)}}if(!Kn&&g.length>0){let L=g[g.length-1],Me={config:o,lastMessage:L,messageCount:g.length},We=r.find(Ce=>Ce.renderIdleIndicator),Ke=null;if(We!=null&&We.renderIdleIndicator&&(Ke=We.renderIdleIndicator(Me)),Ke===null&&((Re=o.loadingIndicator)!=null&&Re.renderIdle)&&(Ke=o.loadingIndicator.renderIdle(Me)),Ke){let Ce=document.createElement("div"),Lt=((qe=o.loadingIndicator)==null?void 0:qe.showBubble)!==!1;Ce.className=Lt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ce.setAttribute("data-idle-indicator","true"),Ce.appendChild(Ke);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(Ce),y.appendChild(st)}}if(ni(c,y),ue.length>0)for(let{messageId:L,fingerprint:Me,bubble:We}of ue){let Ke=c.querySelector(`#wrapper-${L}`);Ke&&We!==null&&(Ke.replaceChildren(We),Ke.setAttribute("data-bubble-fp",Me),Po.set(L,Me))}if(Po.size>0)for(let L of Po.keys())z.has(L)||Po.delete(L);if(ee.length>0)for(let{messageId:L,fingerprint:Me,bubble:We}of ee){let Ke=c.querySelector(`#wrapper-${L}`);Ke&&We!==null&&(Ke.replaceChildren(We),Ke.setAttribute("data-bubble-fp",Me),So.set(L,Me))}if(So.size>0)for(let L of So.keys())z.has(L)||So.delete(L)},Xo=null,pa=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ye)||$e&&P.includes($e)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ds=()=>{var g;if(!Xo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Xo,!0),Xo=null};gt.push(()=>ds());let Qo=null,ua=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ps=()=>{var g;if(!Qo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Qo,!0),Qo=null};gt.push(()=>ps());let Jo=!1,us=new Set,ma=()=>{var g,h,y,P;let c=(y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var at,it,Pe,Re;if(!k())return;let c=Be.peekBanner,g=Be.peekTextNode;if(!c||!g)return;if(E){c.classList.remove("persona-pill-peek--visible");return}let h=(at=T==null?void 0:T.getMessages())!=null?at:[],y;for(let qe=h.length-1;qe>=0;qe--){let L=h[qe];if(L.role==="assistant"&&L.content){y=L;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,N=!!y.streaming,V=ma(),z=ii(V),O=z.type!=="none"?_s(z.type,V==null?void 0:V.plugins):null,Ae=((it=O==null?void 0:O.isAnimating)==null?void 0:it.call(O,y))===!0,ue=O!==null&&(N||Ae);ue&&O&&!us.has(O.name)&&(ul(O,e),us.add(O.name));let ee=ue&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Pe=g.dataset.personaPeekStreamClass)!=null?Pe:null;he&&he!==ee&&(g.classList.remove(he),delete g.dataset.personaPeekStreamClass),ee&&he!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),ue?(g.style.setProperty("--persona-stream-step",`${z.speed}ms`),g.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ee=ue?li(P,z.buffer,O,y,N):P;if(ue&&z.placeholder==="skeleton"&&N&&(!Ee||!Ee.trim())){let qe=document.createElement("div"),L=$s();L.classList.add("persona-pill-peek__skeleton"),qe.appendChild(L),ni(g,qe)}else{let qe=Math.max(0,Ee.length-100),L=Ee.length>100?Ee.slice(-100):Ee,Me=Ls(L);if(!ue||!O){let We=Ee.length>100?`\u2026${L}`:L;g.textContent!==We&&(g.textContent=We)}else{let We=Me;(O.wrap==="char"||O.wrap==="word")&&(We=Vs(Me,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:qe}));let Ke=document.createElement("div");if(Ke.innerHTML=We,O.useCaret&&L.length>0){let Ce=ci(),Lt=Ke.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=Lt[Lt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(Ce,st.nextSibling):Ke.appendChild(Ce)}ni(g,Ke),(Re=O.onAfterRender)==null||Re.call(O,{container:g,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Ye=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Ye)};if(k()){let c=Be.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};le.addEventListener("pointerenter",g),le.addEventListener("pointerleave",h),gt.push(()=>{le.removeEventListener("pointerenter",g),le.removeEventListener("pointerleave",h)}),$e&&($e.addEventListener("pointerenter",g),$e.addEventListener("pointerleave",h),gt.push(()=>{$e.removeEventListener("pointerenter",g),$e.removeEventListener("pointerleave",h)}))}let ga=c=>{var he,Ee,Oe,tt,Ye,at,it,Pe;let g=(Ee=(he=o.launcher)==null?void 0:he.composerBar)!=null?Ee:{},h=(Oe=g.expandedSize)!=null?Oe:"anchored",y=(tt=g.bottomOffset)!=null?tt:"16px",P=g.collapsedMaxWidth,N=(Ye=g.expandedMaxWidth)!=null?Ye:"880px",V=(at=g.expandedTopOffset)!=null?at:"5vh",z=(it=g.modalMaxWidth)!=null?it:"880px",O=(Pe=g.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ee=ye.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",$e){let Re=$e.style;Re.bottom=y,Re.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=z,ee.maxWidth=Ae,ee.maxHeight=O,ee.height=O;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ue})`,ee.top=V,ee.width=N,ee.maxWidth=Ae}},Zo=()=>{var O,Ae,ue,ee,he,Ee,Oe,tt;if(!S())return;if(k()){let at=(ue=((Ae=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",it=E?"expanded":"collapsed";ye.dataset.state=it,ye.dataset.expandedSize=at,$e&&($e.dataset.state=it,$e.dataset.expandedSize=at),ye.style.removeProperty("display"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ga(E),ce.style.display=E?"flex":"none",po(),E?(pa(),ua()):(ds(),ps()),Do();return}let c=pn(o),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(Ee=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ee:640,y=(tt=(Oe=o.launcher)==null?void 0:Oe.mobileFullscreen)!=null?tt:!0,P=g.innerWidth<=h,N=y&&P&&I,V=Mo(o).reveal;E?(ye.style.removeProperty("display"),ye.style.display=c?"flex":"",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),Ie?Ie.element.style.display="none":Ge&&(Ge.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!N?(ye.style.removeProperty("display"),ye.style.display="flex",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.setProperty("display","none","important"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.display="",ye.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),Ie?Ie.element.style.display=c?"none":"":Ge&&(Ge.style.display=c?"none":""))},Bt=(c,g="user")=>{var N,V;if(!S()||E===c)return;let h=E;E=c,Zo();let y=(()=>{var Oe,tt,Ye,at,it,Pe,Re,qe,L,Me;let z=(tt=(Oe=o.launcher)==null?void 0:Oe.sidebarMode)!=null?tt:!1,O=(Ye=e.ownerDocument.defaultView)!=null?Ye:window,Ae=(it=(at=o.launcher)==null?void 0:at.mobileFullscreen)!=null?it:!0,ue=(Re=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,ee=O.innerWidth<=ue,he=pn(o)&&Ae&&ee,Ee=k()&&((Me=(L=(qe=o.launcher)==null?void 0:qe.composerBar)==null?void 0:L.expandedSize)!=null?Me:"fullscreen")==="fullscreen";return z||Ae&&ee&&I||he||Ee})();if(E&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=ml(O,(V=(N=o.launcher)==null?void 0:N.zIndex)!=null?V:hn))}Gt||(Gt=gl(e.ownerDocument))}else E||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);E&&(Rt(),Yo(!0));let P={open:E,source:g,timestamp:Date.now()};E&&!h?s.emit("widget:opened",P):!E&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:E,launcherEnabled:I,voiceActive:mt.active,streaming:T.isStreaming()})},Br=c=>{Vt(c?"stop":"send"),q&&(q.disabled=c),uo.buttons.forEach(g=>{g.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Hr=()=>{mt.active||pe&&pe.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hr(),200)});let ms=()=>{var h,y,P,N,V,z,O,Ae,ue,ee,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(N=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",pe.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=K.querySelector("[data-persona-intro-card]");if(c){let Ee=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ee?"":"none",Ee?(K.classList.remove("persona-gap-3"),K.classList.add("persona-gap-6")):(K.classList.remove("persona-gap-6"),K.classList.add("persona-gap-3"))}!((ue=(Ae=o.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(T!=null&&T.isStreaming())&&(ae.textContent=(he=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?he:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(g=>({...g,sessionId:c}))}});let Ao=null,fa=()=>{Ao==null&&(Ao=setInterval(()=>{let c=_e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let g=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=za(g-y))})},100))};if(T=new ei(o,{onMessagesChanged(c){dr(_e,c,me),fa(),T&&(c.some(P=>P.role==="user")?uo.render([],T,pe,c):uo.render(o.suggestionChips,T,pe,c,o.suggestionChipsConfig)),Yo(!Kn),da(c);let g=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;g&&g.id!==h&&(mt.lastUserMessageId=g.id,s.emit("user:message",g)),mt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wr(c),Do()},onStatusChanged(c){var y;let g=(y=o.statusIndicator)!=null?y:{};nt(ln,(P=>{var N,V,z,O;return P==="idle"?(N=g.idleText)!=null?N:fn.idle:P==="connecting"?(V=g.connectingText)!=null?V:fn.connecting:P==="connected"?(z=g.connectedText)!=null?z:fn.connected:P==="error"?(O=g.errorText)!=null?O:fn.error:fn[P]})(c),g,c)},onStreamingChanged(c){Kn=c,Br(c),T&&dr(_e,T.getMessages(),me),c||Yo(!0),Do()},onVoiceStatusChanged(c){var g,h;if(((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":G(),W();break;case"speaking":G(),Z();break;default:c==="idle"&&T.isBargeInActive()?(G(),U(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,G(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Wr()}}),It.current=T,((zc=(Uc=o.voiceRecognition)==null?void 0:Uc.provider)==null?void 0:zc.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&T.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Y||o.onSSEEvent)&&T.setSSEEventCallback((c,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,g),xe==null||xe.processEvent(c,g),Y==null||Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,h,y;c&&(c.metadata&&(d=Ol(c.metadata),M.syncFromMetadata()),(g=c.messages)!=null&&g.length&&T.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&T.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var g,h,y;!k()||E||!((y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},fs=c=>{var P;if(c.preventDefault(),T.isStreaming()){T.cancel(),xe==null||xe.reset(),Se==null||Se.update();return}let g=pe.value.trim(),h=(P=et==null?void 0:et.hasAttachments())!=null?P:!1;if(!g&&!h)return;gs();let y;h&&(y=[],y.push(...et.getContentParts()),g&&y.push(ll(g))),pe.value="",pe.style.height="auto",pr(),T.sendMessage(g,{contentParts:y}),h&&et.clearAttachments()},ha=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Dr={...oi},Fr=!1,pr=()=>{Dr={...oi}},ba=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ya=c=>{if(!pe)return;Fr=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Fr=!1;let g=pe.value.length;pe.setSelectionRange(g,g)},hs=()=>{Fr||pr()},bs=c=>{if(pe){if(ha()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=pe.selectionStart===0&&pe.selectionEnd===0,h=Du({direction:c.key==="ArrowUp"?"up":"down",history:ba(),currentValue:pe.value,atStart:g,state:Dr});if(Dr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ya(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}pr(),c.preventDefault(),ae.click()}}},ys=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(ce)&&(T.cancel(),xe==null||xe.reset(),Se==null||Se.update(),pr(),c.preventDefault(),c.stopImmediatePropagation())},vs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let g=nx(c.clipboardData);g.length!==0&&(c.preventDefault(),await et.handleFiles(g))},Cn=null,Gn=!1,Fo=null,rt=null,xs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ur=(c="user")=>{var N,V,z,O,Ae,ue,ee;if(Gn||T.isStreaming())return;let g=xs();if(!g)return;Cn=new g;let y=(V=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?V:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let P=pe.value;Cn.onresult=he=>{let Ee="",Oe="";for(let Ye=0;Ye<he.results.length;Ye++){let at=he.results[Ye],it=at[0].transcript;at.isFinal?Ee+=it+" ":Oe=it}let tt=P+Ee+Oe;pe.value=tt,Fo&&clearTimeout(Fo),(Ee||Oe)&&(Fo=window.setTimeout(()=>{let Ye=pe.value.trim();Ye&&Cn&&Gn&&(bo(),pe.value="",pe.style.height="auto",T.sendMessage(Ye,{viaVoice:!0}))},y))},Cn.onerror=he=>{he.error!=="no-speech"&&bo()},Cn.onend=()=>{if(Gn){let he=pe.value.trim();he&&he!==P.trim()&&(pe.value="",pe.style.height="auto",T.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Cn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),q){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(O=he.iconName)!=null?O:"mic",iconSize:parseFloat((ee=(ue=he.iconSize)!=null?ue:(Ae=o.sendButton)==null?void 0:Ae.size)!=null?ee:"40")||24};let Ee=he.recordingBackgroundColor,Oe=he.recordingIconColor,tt=he.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Ee!=null?Ee:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let Ye=q.querySelector("svg");Ye&&Ye.setAttribute("stroke",Oe)}tt&&(q.style.borderColor=tt),q.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Cn){try{Cn.stop()}catch{}Cn=null}if(mt.active=!1,ro(c),Rn(),q){if(q.classList.remove("persona-voice-recording"),rt){q.style.backgroundColor=rt.backgroundColor,q.style.color=rt.color,q.style.borderColor=rt.borderColor;let g=q.querySelector("svg");g&&g.setAttribute("stroke",rt.color||"currentColor"),rt=null}q.setAttribute("aria-label","Start voice recognition")}}},va=(c,g)=>{var at,it,Pe,Re,qe,L,Me,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(h||y))return null;let N=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let z=(it=c==null?void 0:c.iconName)!=null?it:"mic",O=(Pe=g==null?void 0:g.size)!=null?Pe:"40px",Ae=(Re=c==null?void 0:c.iconSize)!=null?Re:O,ue=parseFloat(Ae)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,he=(L=c==null?void 0:c.iconColor)!=null?L:g==null?void 0:g.textColor;V.style.width=Ae,V.style.height=Ae,V.style.minWidth=Ae,V.style.minHeight=Ae,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Oe=Te(z,ue,he||"currentColor",1.5);Oe?V.appendChild(Oe):V.textContent="\u{1F3A4}",ee?V.style.backgroundColor=ee:V.style.backgroundColor="",c!=null&&c.borderWidth&&(V.style.borderWidth=c.borderWidth,V.style.borderStyle="solid"),c!=null&&c.borderColor&&(V.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(V.style.paddingLeft=c.paddingX,V.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(V.style.paddingTop=c.paddingY,V.style.paddingBottom=c.paddingY),N.appendChild(V);let tt=(Me=c==null?void 0:c.tooltipText)!=null?Me:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&tt){let Ke=b("div","persona-send-button-tooltip");Ke.textContent=tt,N.appendChild(Ke)}return{micButton:V,micButtonWrapper:N}},er=()=>{var g,h,y,P,N;if(!q||rt)return;let c=(g=o.voiceRecognition)!=null?g:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(P=c.iconSize)!=null?P:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},je=(c,g)=>{var N,V,z,O,Ae;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(Ae=rt==null?void 0:rt.iconSize)!=null?Ae:parseFloat((O=(z=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?O:"40")||24,P=Te(c,y,g,1.5);P&&q.appendChild(P)},A=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},U=()=>{var P;if(!q)return;er();let c=(P=o.voiceRecognition)!=null?P:{},g=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=q.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},W=()=>{var z,O,Ae,ue,ee,he,Ee,Oe;if(!q)return;er();let c=(z=o.voiceRecognition)!=null?z:{},g=T.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ue=(Ae=c.processingIconColor)!=null?Ae:rt==null?void 0:rt.color)!=null?ue:"",P=(he=(ee=c.processingBackgroundColor)!=null?ee:rt==null?void 0:rt.backgroundColor)!=null?he:"",N=(Oe=(Ee=c.processingBorderColor)!=null?Ee:rt==null?void 0:rt.borderColor)!=null?Oe:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=P,q.style.borderColor=N;let V=y||"currentColor";q.style.color=V,je(h,V),q.setAttribute("aria-label","Processing voice input"),g==="none"&&(q.style.cursor="default")},Z=()=>{var Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re;if(!q)return;er();let c=(Ae=o.voiceRecognition)!=null?Ae:{},g=T.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,P=(Oe=c.speakingIconColor)!=null?Oe:g==="barge-in"?(he=(ee=c.recordingIconColor)!=null?ee:rt==null?void 0:rt.color)!=null?he:"":(Ee=rt==null?void 0:rt.color)!=null?Ee:"",N=(at=c.speakingBackgroundColor)!=null?at:g==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Ye=rt==null?void 0:rt.backgroundColor)!=null?Ye:"",V=(Re=c.speakingBorderColor)!=null?Re:g==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(Pe=rt==null?void 0:rt.borderColor)!=null?Pe:"";A(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=N,q.style.borderColor=V;let z=P||"currentColor";q.style.color=z,je(y,z);let O=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",O),g==="none"&&(q.style.cursor="default"),g==="barge-in"&&q.classList.add("persona-voice-recording")},G=()=>{var c,g,h;q&&(A(),rt&&(q.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",q.style.color=(g=rt.color)!=null?g:"",q.style.borderColor=(h=rt.borderColor)!=null?h:"",je(rt.iconName,rt.color||"currentColor"),rt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},X=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let h=T.getVoiceStatus(),y=T.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()});return}T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),mt.manuallyDeactivated=!T.isVoiceActive(),Rn(),ro("user"),T.isVoiceActive()?U():G()});return}if(Gn){let h=pe.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(pe.value="",pe.style.height="auto",T.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),ur("user")};Fn=X,q&&(q.addEventListener("click",X),gt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),G()):bo("system"),q&&q.removeEventListener("click",X)}));let Xe=s.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!mt.active&&!mt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("auto"),T.isVoiceActive()&&U()}):ur("auto"))},600))});gt.push(Xe);let Ne=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});gt.push(Ne);let Ze=()=>{Bt(!E,"user")},Ie=null,Ge=null;if(I&&!k()){let c=r.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ze).element,onToggle:Ze});g&&(Ge=g)}Ge||(Ie=qs(o,Ze))}Ie?e.appendChild(Ie.element):Ge&&e.appendChild(Ge),Zo(),uo.render(o.suggestionChips,T,pe,void 0,o.suggestionChipsConfig),ms(),Br(T.isStreaming()),Yo(!0),aa(),H&&(!I||k()?setTimeout(()=>Hr(),0):E&&setTimeout(()=>Hr(),200));let Rt=()=>{var O,Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re,qe,L,Me,We,Ke,Ce,Lt,st,Xt;if(k()){bt(),Zo();return}let c=pn(o),g=(Ae=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ae:!1,h=c||g||((ee=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?ee:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Oe=(Ee=o.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Oe:!0,N=(Ye=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Ye:640,V=y.innerWidth<=N,z=P&&V&&I;try{if(z){po(),$r(e,o);return}if(x&&(x=!1,po(),$r(e,o)),!I&&!c){le.style.height="",le.style.width="";return}if(!g&&!c){let cn=(it=(at=o==null?void 0:o.launcher)==null?void 0:at.width)!=null?it:o==null?void 0:o.launcherWidth,Pt=cn!=null?cn:io;le.style.width=Pt,le.style.maxWidth=Pt}if(Co(),!h){let cn=y.innerHeight,Pt=64,An=(Re=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Re:0,dn=Math.max(200,cn-Pt),Je=Math.min(640,dn),lt=Math.max(200,Je-An);le.style.height=`${lt}px`}}finally{if(bt(),Zo(),E&&I){let Pt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Me=(L=o.launcher)==null?void 0:L.mobileBreakpoint)!=null?Me:640),An=(Ke=(We=o.launcher)==null?void 0:We.sidebarMode)!=null?Ke:!1,dn=(Lt=(Ce=o.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Lt:!0,Je=pn(o)&&dn&&Pt,lt=An||dn&&Pt&&I||Je;if(lt&&!Gt){let Tn=e.getRootNode(),mn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");mn&&!Kt&&(Kt=ml(mn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:hn)),Gt=gl(e.ownerDocument)}else lt||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Rt();let nn=(qc=e.ownerDocument.defaultView)!=null?qc:window;if(nn.addEventListener("resize",Rt),gt.push(()=>nn.removeEventListener("resize",Rt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe(Ve),gt.push(()=>c.disconnect())}fo=K.scrollTop;let Ct=K.scrollHeight,Mt=()=>{let c=K.scrollTop,g=K.scrollHeight,h=g<Ct;Ct=g;let{action:y,nextLastScrollTop:P}=si({following:go.isFollowing(),currentScrollTop:c,lastScrollTop:fo,nearBottom:Os(K,as),userScrollThreshold:ra,isAutoScrolling:Wo||lr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=P,y==="resume"){Go();return}y==="pause"&&cs()};K.addEventListener("scroll",Mt,{passive:!0}),gt.push(()=>K.removeEventListener("scroll",Mt));let on=c=>{let g=ai({following:go.isFollowing(),deltaY:c.deltaY,nearBottom:Os(K,as),resumeWhenNearBottom:!0});g==="pause"?cs():g==="resume"&&Go()};K.addEventListener("wheel",on,{passive:!0}),gt.push(()=>K.removeEventListener("wheel",on)),Tt.addEventListener("click",()=>{K.scrollTop=K.scrollHeight,fo=K.scrollTop,Go(),Yo(!0)}),gt.push(()=>Tt.remove()),gt.push(()=>{ls()});let un=()=>{ze&&(jn&&(ze.removeEventListener("click",jn),jn=null),S()?(ze.style.display="",jn=()=>{Bt(!1,"user")},ze.addEventListener("click",jn)):ze.style.display="none")};un(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{T.clearMessages(),mo.clear(),Go(),Jr(Be.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)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 g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),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={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()})})(),Nt&&Nt.addEventListener("submit",fs),pe==null||pe.addEventListener("keydown",bs),pe==null||pe.addEventListener("input",hs),pe==null||pe.addEventListener("paste",vs);let Yt=(jc=e.ownerDocument)!=null?jc:document;Yt.addEventListener("keydown",ys,!0);let so="persona-attachment-drop-active",ws=0,Ui=()=>{ws=0,ce.classList.remove(so)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},Zl=c=>{!Ei(c.dataTransfer)||!Or()||(ws++,ws===1&&ce.classList.add(so))},ec=c=>{!Ei(c.dataTransfer)||!Or()||(ws--,ws<=0&&Ui())},tc=c=>{!Ei(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},nc=c=>{var h;if(!Ei(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),Ui();let g=Array.from((h=c.dataTransfer.files)!=null?h:[]);g.length!==0&&et.handleFiles(g)},tr=!0;ce.addEventListener("dragenter",Zl,tr),ce.addEventListener("dragleave",ec,tr),e.addEventListener("dragover",tc,tr),e.addEventListener("drop",nc,tr);let xa=e.ownerDocument,oc=c=>{Or()&&c.preventDefault()},rc=c=>{Or()&&c.preventDefault()};xa.addEventListener("dragover",oc),xa.addEventListener("drop",rc),gt.push(()=>{Nt&&Nt.removeEventListener("submit",fs),pe==null||pe.removeEventListener("keydown",bs),pe==null||pe.removeEventListener("input",hs),pe==null||pe.removeEventListener("paste",vs),Yt.removeEventListener("keydown",ys,!0)}),gt.push(()=>{ce.removeEventListener("dragenter",Zl,tr),ce.removeEventListener("dragleave",ec,tr),e.removeEventListener("dragover",tc,tr),e.removeEventListener("drop",nc,tr),xa.removeEventListener("dragover",oc),xa.removeEventListener("drop",rc),Ui()}),gt.push(()=>{T.cancel()}),Ie?gt.push(()=>{Ie==null||Ie.destroy()}):Ge&&gt.push(()=>{Ge==null||Ge.remove()});let Zt={update(c){var en,To,No,wa,Ca,Sa,br,Aa,Cs,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,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;let g=o.toolCall,h=o.messageActions,y=(en=o.layout)==null?void 0:en.messages,P=o.colorScheme,N=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,O=(No=o.features)==null?void 0:No.showToolCalls,Ae=(wa=o.features)==null?void 0:wa.toolCallDisplay,ue=(Ca=o.features)==null?void 0:Ca.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ti(e,o),ki(e,o),zn(),o.colorScheme!==P&&Ko();let ee=Bl.getForInstance(o.plugins);r.length=0,r.push(...ee),I=(br=(Sa=o.launcher)==null?void 0:Sa.enabled)!=null?br:!0,R=(Cs=(Aa=o.launcher)==null?void 0:Aa.autoExpand)!=null?Cs:!1,se=(ed=(Zc=o.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,ge=(nd=(td=o.features)==null?void 0:td.showToolCalls)!=null?nd:!0,be=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},zt(),Ho();let he=ie;if(ie=(ad=(sd=o.features)==null?void 0:sd.showEventStreamToggle)!=null?ad:!1,ie&&!he){if(Y||(J=new Xs(ve),Y=new Ys(Le,J),xe=xe!=null?xe:new Qs,J.open().then(()=>Y==null?void 0:Y.restore()).catch(()=>{}),T.setSSEEventCallback((Q,vt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,Q,vt),xe==null||xe.processEvent(Q,vt),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!ut&&De){let Q=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");ut=b("button",vt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ot=Te("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let ct=Be.clearChatButtonWrapper,kt=Be.closeButtonWrapper,rn=ct||kt;rn&&rn.parentNode===De?De.insertBefore(ut,rn):De.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),Y==null||Y.clear(),J==null||J.destroy(),Y=null,J=null,xe==null||xe.reset(),xe=null);if(((cd=o.launcher)==null?void 0:cd.enabled)===!1&&Ie&&(Ie.destroy(),Ie=null),((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((pd=o.launcher)==null?void 0:pd.enabled)!==!1&&!Ie&&!Ge){let Q=r.find(vt=>vt.renderLauncher);if(Q!=null&&Q.renderLauncher){let vt=Q.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ze).element,onToggle:Ze});vt&&(Ge=vt,e.appendChild(Ge))}Ge||(Ie=qs(o,Ze),e.appendChild(Ie.element))}Ie&&Ie.update(o),ke&&((ud=o.launcher)==null?void 0:ud.title)!==void 0&&(ke.textContent=o.launcher.title),He&&((md=o.launcher)==null?void 0:md.subtitle)!==void 0&&(He.textContent=o.launcher.subtitle);let Ee=(gd=o.layout)==null?void 0:gd.header;if((Ee==null?void 0:Ee.layout)!==v&&De){let Q=Ee?mi(o,Ee,{showClose:S(),onClose:()=>Bt(!1,"user")}):Ar({config:o,showClose:S(),onClose:()=>Bt(!1,"user")});De.replaceWith(Q.header),De=Q.header,_=Q.iconHolder,ke=Q.headerTitle,He=Q.headerSubtitle,ze=Q.closeButton,v=Ee==null?void 0:Ee.layout}else if(Ee&&(_&&(_.style.display=Ee.showIcon===!1?"none":""),ke&&(ke.style.display=Ee.showTitle===!1?"none":""),He&&(He.style.display=Ee.showSubtitle===!1?"none":""),ze&&(ze.style.display=Ee.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let Q=Ee.showClearChat;if(Q!==void 0){Be.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:vt}=Be;vt&&!vt.classList.contains("persona-absolute")&&(Q?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let tt=((fd=o.layout)==null?void 0:fd.showHeader)!==!1;De&&(De.style.display=tt?"":"none");let Ye=((hd=o.layout)==null?void 0:hd.showFooter)!==!1;Ve&&(Ve.style.display=Ye?"":"none"),bt(),Ho(),I!==B?I?Bt(R,"auto"):(E=!0,Zo()):R!==D&&Bt(R,"auto"),D=R,B=I,Rt(),un();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),qe=JSON.stringify((bd=o.layout)==null?void 0:bd.messages)!==JSON.stringify(y),L=((yd=o.loadingIndicator)==null?void 0:yd.render)!==(N==null?void 0:N.render)||((vd=o.loadingIndicator)==null?void 0:vd.renderIdle)!==(N==null?void 0:N.renderIdle)||((xd=o.loadingIndicator)==null?void 0:xd.showBubble)!==(N==null?void 0:N.showBubble),Me=o.iterationDisplay!==V,We=((Cd=(wd=o.features)==null?void 0:wd.showReasoning)!=null?Cd:!0)!==(z!=null?z:!0)||((Ad=(Sd=o.features)==null?void 0:Sd.showToolCalls)!=null?Ad:!0)!==(O!=null?O:!0)||JSON.stringify((Td=o.features)==null?void 0:Td.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((kd=o.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(ue);(Pe||Re||qe||L||Me||We)&&T&&(ss++,dr(_e,T.getMessages(),me));let Ce=(Ed=o.launcher)!=null?Ed:{},Lt=(Md=Ce.headerIconHidden)!=null?Md:!1,st=(Id=(Ld=o.layout)==null?void 0:Ld.header)==null?void 0:Id.showIcon,Xt=Lt||st===!1,cn=Ce.headerIconName,Pt=(Rd=Ce.headerIconSize)!=null?Rd:"48px";if(_){let Q=ce.querySelector(".persona-border-b-persona-divider"),vt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Xt)_.style.display="none",Q&&vt&&!Q.contains(vt)&&Q.insertBefore(vt,Q.firstChild);else{if(_.style.display="",_.style.height=Pt,_.style.width=Pt,Q&&vt&&(Q.contains(_)?_.nextSibling!==vt&&(_.remove(),Q.insertBefore(_,vt)):Q.insertBefore(_,vt)),cn){let ct=parseFloat(Pt)||24,kt=Te(cn,ct*.6,"#ffffff",2);kt?_.replaceChildren(kt):_.textContent=(Pd=Ce.agentIconText)!=null?Pd:"\u{1F4AC}"}else if(Ce.iconUrl){let ct=_.querySelector("img");if(ct)ct.src=Ce.iconUrl,ct.style.height=Pt,ct.style.width=Pt;else{let kt=document.createElement("img");kt.src=Ce.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Pt,kt.style.width=Pt,_.replaceChildren(kt)}}else{let ct=_.querySelector("svg"),kt=_.querySelector("img");(ct||kt)&&_.replaceChildren(),_.textContent=(Wd=Ce.agentIconText)!=null?Wd:"\u{1F4AC}"}let Ot=_.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Hd=(Bd=o.layout)==null?void 0:Bd.header)==null?void 0:Hd.showTitle,dn=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showSubtitle;if(ke&&(ke.style.display=An===!1?"none":""),He&&(He.style.display=dn===!1?"none":""),ze){((Nd=(Od=o.layout)==null?void 0:Od.header)==null?void 0:Nd.showCloseButton)===!1?ze.style.display="none":ze.style.display="";let vt=(_d=Ce.closeButtonSize)!=null?_d:"32px",Ot=(Vd=Ce.closeButtonPlacement)!=null?Vd:"inline";ze.style.height=vt,ze.style.width=vt;let{closeButtonWrapper:ct}=Be,kt=Ot==="top-right",rn=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&kt!==rn)if(ct.remove(),kt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(ct);else{let pt=(Ud=($d=Ce.clearChat)==null?void 0:$d.placement)!=null?Ud:"inline",sn=(qd=(zd=Ce.clearChat)==null?void 0:zd.enabled)!=null?qd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=ce.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ct)}if(ze.style.color=Ce.closeButtonColor||Mn.actionIconColor,Ce.closeButtonBackgroundColor?(ze.style.backgroundColor=Ce.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let pt=Ce.closeButtonBorderWidth||"0px",sn=Ce.closeButtonBorderColor||"transparent";ze.style.border=`${pt} solid ${sn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(ze.style.borderRadius=Ce.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(ze.style.paddingLeft=Ce.closeButtonPaddingX,ze.style.paddingRight=Ce.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Ce.closeButtonPaddingY?(ze.style.paddingTop=Ce.closeButtonPaddingY,ze.style.paddingBottom=Ce.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let gn=(jd=Ce.closeButtonIconName)!=null?jd:"x",yo=(Kd=Ce.closeButtonIconText)!=null?Kd:"\xD7";ze.innerHTML="";let En=Te(gn,"28px","currentColor",1);En?ze.appendChild(En):ze.textContent=yo;let Qt=(Gd=Ce.closeButtonTooltipText)!=null?Gd:"Close chat",Xn=(Yd=Ce.closeButtonShowTooltip)!=null?Yd:!0;if(ze.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!ze)return;let yr=ze.ownerDocument,Ss=yr.body;if(!Ss)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(yr,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let vr=ze.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),ze.addEventListener("focus",sn),ze.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),ze&&(ze.removeEventListener("focus",sn),ze.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:lt}=Be;if(Je){let Q=(Xd=Ce.clearChat)!=null?Xd:{},vt=(Qd=Q.enabled)!=null?Qd:!0,Ot=(Zd=(Jd=o.layout)==null?void 0:Jd.header)==null?void 0:Zd.showClearChat,ct=Ot!==void 0?Ot:vt,kt=(ep=Q.placement)!=null?ep:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:rn}=Be;!k()&&rn&&!rn.classList.contains("persona-absolute")&&(ct?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let gn=kt==="top-right",yo=lt.classList.contains("persona-absolute");if(!k()&&gn!==yo&&ct){if(lt.remove(),gn)lt.className="persona-absolute persona-top-4 persona-z-50",lt.style.right="48px",ce.style.position="relative",ce.appendChild(lt);else{lt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",lt.style.right="";let Qt=ce.querySelector(".persona-border-b-persona-divider"),Xn=Be.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(lt,Xn):Qt&&Qt.appendChild(lt)}let En=Be.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ct){if(!k()){let pt=(tp=Q.size)!=null?tp:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(np=Q.iconName)!=null?np:"refresh-cw",gn=(op=Q.iconColor)!=null?op:"";Je.style.color=gn||Mn.actionIconColor,Je.innerHTML="";let yo=k()?"14px":"20px",En=Te(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),Q.backgroundColor?(Je.style.backgroundColor=Q.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let pt=Q.borderWidth||"0px",sn=Q.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");Q.borderRadius?(Je.style.borderRadius=Q.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),Q.paddingX?(Je.style.paddingLeft=Q.paddingX,Je.style.paddingRight=Q.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),Q.paddingY?(Je.style.paddingTop=Q.paddingY,Je.style.paddingBottom=Q.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(rp=Q.tooltipText)!=null?rp:"Clear chat",Xn=(sp=Q.showTooltip)!=null?sp:!0;if(Je.setAttribute("aria-label",Qt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let yr=Je.ownerDocument,Ss=yr.body;if(!Ss)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(yr,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let vr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),lt._cleanupTooltip=()=>{Hn(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick];M=Fl({parsers:Tn,handlers:mn,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Dm(o,M,j),T.updateConfig(o),dr(_e,T.getMessages(),me),uo.render(o.suggestionChips,T,pe,void 0,o.suggestionChipsConfig),ms(),Br(T.isStreaming());let mr=((ap=o.voiceRecognition)==null?void 0:ap.enabled)===!0,gr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),fr=((lp=(ip=o.voiceRecognition)==null?void 0:ip.provider)==null?void 0:lp.type)==="runtype";if(mr&&(gr||fr))if(!q||!_t){let Q=va(o.voiceRecognition,o.sendButton);Q&&(q=Q.micButton,_t=Q.micButtonWrapper,At.insertBefore(_t,Ln),q.addEventListener("click",X),q.disabled=T.isStreaming())}else{let Q=(cp=o.voiceRecognition)!=null?cp:{},vt=(dp=o.sendButton)!=null?dp:{},Ot=(pp=Q.iconName)!=null?pp:"mic",ct=(up=vt.size)!=null?up:"40px",kt=(mp=Q.iconSize)!=null?mp:ct,rn=parseFloat(kt)||24;q.style.width=kt,q.style.height=kt,q.style.minWidth=kt,q.style.minHeight=kt;let gn=(fp=(gp=Q.iconColor)!=null?gp:vt.textColor)!=null?fp:"currentColor";q.innerHTML="";let yo=Te(Ot,rn,gn,2);yo?q.appendChild(yo):q.textContent="\u{1F3A4}";let En=(hp=Q.backgroundColor)!=null?hp:vt.backgroundColor;En?q.style.backgroundColor=En:q.style.backgroundColor="",gn?q.style.color=gn:q.style.color="var(--persona-text, #111827)",Q.borderWidth?(q.style.borderWidth=Q.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),Q.borderColor?q.style.borderColor=Q.borderColor:q.style.borderColor="",Q.paddingX?(q.style.paddingLeft=Q.paddingX,q.style.paddingRight=Q.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),Q.paddingY?(q.style.paddingTop=Q.paddingY,q.style.paddingBottom=Q.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Qt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Xn=(bp=Q.tooltipText)!=null?bp:"Start voice recognition";if(((yp=Q.showTooltip)!=null?yp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,_t==null||_t.insertBefore(sn,q)}else Qt&&(Qt.style.display="none");_t.style.display="",q.disabled=T.isStreaming()}else q&&_t&&(_t.style.display="none",((xp=(vp=o.voiceRecognition)==null?void 0:vp.provider)==null?void 0:xp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Gn&&bo());if(((wp=o.attachments)==null?void 0:wp.enabled)===!0)if(!Ft||!Qe){let Q=(Cp=o.attachments)!=null?Cp:{},Ot=(Ap=((Sp=o.sendButton)!=null?Sp:{}).size)!=null?Ap:"40px";fe||(fe=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fe.style.display="none",Nt.insertBefore(fe,pe)),oe||(oe=document.createElement("input"),oe.type="file",oe.accept=((Tp=Q.allowedTypes)!=null?Tp:_o).join(","),oe.multiple=((kp=Q.maxFiles)!=null?kp:4)>1,oe.style.display="none",oe.setAttribute("aria-label","Attach files"),Nt.insertBefore(oe,pe)),Ft=b("div","persona-send-button-wrapper"),Qe=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Qe.type="button",Qe.setAttribute("aria-label",(Ep=Q.buttonTooltipText)!=null?Ep:"Attach file");let ct=(Mp=Q.buttonIconName)!=null?Mp:"paperclip",kt=Ot,rn=parseFloat(kt)||40,gn=Math.round(rn*.6);Qe.style.width=kt,Qe.style.height=kt,Qe.style.minWidth=kt,Qe.style.minHeight=kt,Qe.style.fontSize="18px",Qe.style.lineHeight="1",Qe.style.backgroundColor="transparent",Qe.style.color="var(--persona-primary, #111827)",Qe.style.border="none",Qe.style.borderRadius="6px",Qe.style.transition="background-color 0.15s ease",Qe.addEventListener("mouseenter",()=>{Qe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Qe.addEventListener("mouseleave",()=>{Qe.style.backgroundColor="transparent"});let yo=Te(ct,gn,"currentColor",1.5);yo?Qe.appendChild(yo):Qe.textContent="\u{1F4CE}",Qe.addEventListener("click",Xn=>{Xn.preventDefault(),oe==null||oe.click()}),Ft.appendChild(Qe);let En=(Lp=Q.buttonTooltipText)!=null?Lp:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,Ft.appendChild(Qt),ot.append(Ft),!et&&oe&&fe&&(et=Ds.fromConfig(Q),et.setPreviewsContainer(fe),oe.addEventListener("change",async()=>{et&&(oe!=null&&oe.files)&&(await et.handleFileSelect(oe.files),oe.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Fm(Q.dropOverlay))}else{Ft.style.display="";let Q=(Ip=o.attachments)!=null?Ip:{};oe&&(oe.accept=((Rp=Q.allowedTypes)!=null?Rp:_o).join(","),oe.multiple=((Pp=Q.maxFiles)!=null?Pp:4)>1),et&&et.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ft&&(Ft.style.display="none"),et&&et.clearAttachments(),(Wp=ce.querySelector(".persona-attachment-drop-overlay"))==null||Wp.remove();let qt=(Bp=o.sendButton)!=null?Bp:{},hr=(Hp=qt.useIcon)!=null?Hp:!1,nr=(Dp=qt.iconText)!=null?Dp:"\u2191",ht=qt.iconName,Pn=(Fp=qt.tooltipText)!=null?Fp:"Send message",Oo=(Op=qt.showTooltip)!=null?Op:!1,kn=(Np=qt.size)!=null?Np:"40px",Wn=qt.backgroundColor,Ht=qt.textColor;if(hr){if(ae.style.width=kn,ae.style.height=kn,ae.style.minWidth=kn,ae.style.minHeight=kn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Ht?ae.style.color=Ht:ae.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let Q=parseFloat(kn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Te(ht,Q,vt,2);Ot?ae.appendChild(Ot):ae.textContent=nr}else ae.textContent=nr;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=(Vp=(_p=o.copy)==null?void 0:_p.sendButtonLabel)!=null?Vp:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Ht?ae.style.color=Ht:ae.classList.add("persona-text-white");qt.borderWidth?(ae.style.borderWidth=qt.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),qt.borderColor?ae.style.borderColor=qt.borderColor:ae.style.borderColor="",qt.paddingX?(ae.style.paddingLeft=qt.paddingX,ae.style.paddingRight=qt.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),qt.paddingY?(ae.style.paddingTop=qt.paddingY,ae.style.paddingBottom=qt.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Ut=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Ut)Ut.textContent=Pn,Ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Pn,Ln==null||Ln.insertBefore(Q,ae)}else Ut&&(Ut.style.display="none");let Dt=(jp=($p=o.layout)==null?void 0:$p.contentMaxWidth)!=null?jp:k()?(qp=(zp=(Up=o.launcher)==null?void 0:Up.composerBar)==null?void 0:zp.contentMaxWidth)!=null?qp:"720px":void 0;Dt?(_e.style.maxWidth=Dt,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Et&&(Et.style.maxWidth=Dt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight="",_e.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let jt=(Kp=o.statusIndicator)!=null?Kp:{},Bn=(Gp=jt.visible)!=null?Gp:!0;if(ln.style.display=Bn?"":"none",T){let Q=T.getStatus();nt(ln,(Ot=>{var ct,kt,rn,gn;return Ot==="idle"?(ct=jt.idleText)!=null?ct:fn.idle:Ot==="connecting"?(kt=jt.connectingText)!=null?kt:fn.connecting:Ot==="connected"?(rn=jt.connectedText)!=null?rn:fn.connected:Ot==="error"?(gn=jt.errorText)!=null?gn:fn.error:fn[Ot]})(Q),jt,Q)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){S()&&Bt(!0,"api")},close(){S()&&Bt(!1,"api")},toggle(){S()&&Bt(!E,"api")},clearChat(){xn=!1,T.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()},setMessage(c){return!pe||T.isStreaming()?!1:(!E&&S()&&Bt(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let g=(c==null?void 0:c.trim())||pe.value.trim();return g?(!E&&S()&&Bt(!0,"system"),pe.value="",pe.style.height="auto",T.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return T.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!E&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("user"),T.isVoiceActive()&&U()})),!0):Gn?!0:xs()?(!E&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),ur("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!E&&S()&&Bt(!0,"system");let g=T.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),g},injectUserMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!E&&S()&&Bt(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!E&&S()&&Bt(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!E&&S()&&Bt(!0,"system"),T.injectTestEvent(c)},async connectStream(c,g){return T.connectStream(c,g)},__pushEventStreamEvent(c){Y&&(xe==null||xe.processEvent(c.type,c.payload),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!Y||vn()},hideEventStream(){de&&On()},isEventStreamVisible(){return de},showArtifacts(){co(o)&&(xn=!1,zn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(xn=!0,zn())},upsertArtifact(c){return co(o)?(xn=!1,T.upsertArtifact(c)):null},selectArtifact(c){co(o)&&T.selectArtifact(c)},clearArtifacts(){co(o)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!E&&!k()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,g){let y=T.getMessages().find(P=>{var N;return P.variant==="approval"&&((N=P.approval)==null?void 0:N.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){T.resolveWebMcpApproval(y.id,g);return}return T.resolveApproval(y.approval,g)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return S()&&E},isVoiceActive(){return mt.active},getState(){return{open:S()&&E,launcherEnabled:I,voiceActive:mt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!E&&S()&&Bt(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Wm({onSubmit:async(y,P)=>{var N;T.isClientTokenMode()&&await T.submitCSATFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!E&&S()&&Bt(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Bm({onSubmit:async(y,P)=>{var N;T.isClientTokenMode()&&await T.submitNPSFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return T.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return T.submitNPSFeedback(c,g)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),gt.forEach(c=>c()),ye.remove(),$e==null||$e.remove(),Ie==null||Ie.destroy(),Ge==null||Ge.remove(),jn&&ze.removeEventListener("click",jn)}};if((((Kc=n==null?void 0:n.debugTools)!=null?Kc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:h=>h?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,gt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",g),gt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ie){let z=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.showEventStream()},O=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),gt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.hideArtifacts()},P=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&Zt.upsertArtifact(O.artifact)},N=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&Zt.selectArtifact(O.id)},V=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",V),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",V)})}let ao=ox(o.persistState);if(ao&&S()){let c=rx(ao.storage),g=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Gc=ao.persist)==null?void 0:Gc.openState)&&c.getItem(g)==="true",N=((Yc=ao.persist)==null?void 0:Yc.voiceState)&&c.getItem(h)==="true",V=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var z;if(N||V)Zt.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Qc=ao.persist)!=null&&Qc.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Jc=ao.persist)!=null&&Jc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(g),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),gt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return p&&S()&&setTimeout(()=>{Zt.open()},0),Do(),Zt};var sx=(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},Nm=(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"},$l=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},_m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",$l(e)},Nl=e=>{e.style.transition=""},_l=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=""},Vl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ax=(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))},ix=(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)},Vm=(e,t,n,o,r,s,a)=>{var w,C,M,I,R,H;let i=Mo(s),d=i.reveal==="push";ax(e,t,n,o,d),ix(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,p=(C=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?C:!0,m=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,f=l!=null?l.innerWidth<=m:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),_l(t),Nl(o),_m(o),Vl(n),Mi(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((H=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?H:hn),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"),_m(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",_l(t),Nl(o),Vl(n),Mi(r,o);let D=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":B;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=D,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",Nl(o),$l(o),Mi(r,o);let D=sx(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}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=`${B+D}px`,t.style.transition=v,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}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="",_l(t),$l(o),Vl(n),Mi(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||x?"hidden":"visible",o.style.transition=v,D&&(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")}},lx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Nm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Nm(n,o)},destroy(){n.remove()}}},cx=(e,t)=>{var R,H,D,B;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"),p=n.createElement("div"),m=(H=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||H?(B=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?B:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),o.insertBefore(a,e),d.appendChild(e);let f=null,u=()=>{f==null||f.disconnect(),f=null},w=()=>{u(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Vm(a,i,d,l,p,t,m)}),f.observe(a))},C=()=>{Vm(a,i,d,l,p,t,m),w()},M=a.ownerDocument.defaultView,I=()=>{C()};return M==null||M.addEventListener("resize",I),Mo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),C(),{mode:"docked",host:p,shell:a,syncWidgetState(v){let x=v.launcherEnabled?v.open:!0;m!==x&&(m=x,C())},updateConfig(v){var x,k;t=v,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(m=!0),C()},destroy(){M==null||M.removeEventListener("resize",I),u(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},$m=(e,t)=>pn(t)?cx(e,t):lx(e,t);var ts={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ul=.15,zl=1.5,Li="persona-preview-shell-theme",Um={load:()=>null,save:()=>{},clear:()=>{}},zm=["How do I get started?","Pricing & plans","Talk to support"];function Ii(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qm(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 ql(e){let t=qm(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}; }
@@ -128,7 +128,7 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
128
128
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
129
129
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
130
130
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
131
- .preview-workspace-card.short { height: 96px; }`}function ql(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Mi);o||(o=n.createElement("style"),o.id=Mi,n.head.appendChild(o)),o.textContent=zl(t)}var jm=`
131
+ .preview-workspace-card.short { height: 96px; }`}function jl(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Li);o||(o=n.createElement("style"),o.id=Li,n.head.appendChild(o)),o.textContent=ql(t)}var jm=`
132
132
  <div class="preview-iframe-mock" aria-hidden="true">
133
133
  <div class="preview-iframe-chrome">
134
134
  <span class="preview-iframe-dot"></span>
@@ -160,7 +160,7 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
160
160
  <div class="preview-workspace-card short"></div>
161
161
  <div class="preview-workspace-card short"></div>
162
162
  </div>
163
- </div>`;function jl(e,t,n,o){let r=`
163
+ </div>`;function Kl(e,t,n,o){let r=`
164
164
  ${jm}
165
165
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
166
166
  <div class="preview-workspace-shell">
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
181
181
  <head>
182
182
  <meta charset="UTF-8">
183
183
  <meta name="viewport" content="width=device-width, initial-scale=1">
184
- <link rel="stylesheet" href="${Li(o)}">
185
- <style id="${Mi}">${zl(t)}</style>
184
+ <link rel="stylesheet" href="${Ii(o)}">
185
+ <style id="${Li}">${ql(t)}</style>
186
186
  </head>
187
187
  <body>
188
188
  ${n?s:r}
189
189
  </body>
190
- </html>`}var dx={"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 px(e){return dx[e]}function Kl(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 dx={"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 px(e){return dx[e]}function Gl(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 ux(e,t){return[...e,Kl(t,e.length)]}function Gm(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function mx(e,t,n){var d,l;let o=Kl(e,t);if(!Gm(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 gx=()=>[{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()}],fx=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 Ym(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"&&fx(t)?[...gx(),...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 Gl(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:zm:e.suggestionChips,initialMessages:Ym(t,e,n),storageAdapter:Um};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Mr(e,t){var s,a,i,d;let n=e.theme?nn(e.theme,{validate:!1}):nn(),o=(s=e.scene)!=null?s:"conversation",r={...kt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return Gl(r,o,(d=e.appendedMessages)!=null?d:[])}function hx(e,t,n){var a,i,d;let o=e.theme?nn(e.theme,{validate:!1}):nn(),r=(a=e.scene)!=null?a:"conversation",s={...kt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return Gl(s,r,t)}function Xm(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:Mr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Mr(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:Mr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Mr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Mr(e,n),shellMode:n}]}function bx(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function u(){var L;return(L=n.device)!=null?L:"desktop"}function p(){var L;return(L=n.zoom)!=null?L:i}function f(){var k,F;let L=getComputedStyle(e),H=parseFloat(L.paddingLeft)+parseFloat(L.paddingRight),D=parseFloat(L.paddingTop)+parseFloat(L.paddingBottom),B=40,v=((k=n.compareMode)!=null?k:"off")!=="off",w=(e.clientWidth-H-B)/(v?2:1),E=e.clientHeight-D-B;if(w<=0||E<=0)return 1;let S=(F=ts[u()])!=null?F:ts.desktop;return Math.min(w/S.w,E/S.h,1)}function g(){var D,B,v;i=f();let L=Math.max($l,Math.min(Ul,p()));d=L;let H=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let w of H){let E=(D=w.dataset.device)!=null?D:"desktop",S=(B=ts[E])!=null?B:ts.desktop;w.style.width=`${S.w*L}px`,w.style.height=`${S.h*L}px`,E==="mobile"&&(w.style.borderRadius=`${32*L}px`);let k=w.querySelector("iframe");k&&(k.style.width=`${S.w}px`,k.style.height=`${S.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${L})`)}(v=n.onScaleChange)==null||v.call(n,L)}function x(){var L;(L=n.onBeforeDestroy)==null||L.call(n);for(let H of o)H.destroy();for(let H of r)H();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var be,ie,we,We;if(a)return;x();let L=++l,H=Xm(n),D=u(),B=((be=n.compareMode)!=null?be:"off")!=="off",v=((ie=n.scene)!=null?ie:"conversation")==="minimized",w=(we=n.widgetCssPath)!=null?we:"/widget-dist/widget.css",E=(We=n.buildSrcdoc)!=null?We:jl,S=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=ye=>`<div class="${S}" data-mount-id="${ye.mountId}" data-device="${D}" data-shell-mode="${ye.shellMode}">
194
- ${B?`<div class="preview-frame-meta"><span class="preview-frame-label">${Li(ye.label)}</span></div>`:""}
195
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ye.mountId}"></iframe>
196
- </div>`,F=B?`<div class="preview-compare-grid">${H.map(ye=>`<div class="preview-compare-cell">${k(ye)}</div>`).join("")}</div>`:`<div class="preview-single">${k(H[0])}</div>`;n.morphContainer?n.morphContainer(e,F):e.innerHTML=F,g();let $=C(),q=0,me=$.length,re=()=>{var Z,Ee,X,Ae,fe;if(a||L!==l)return;for(let le of $){let ue=le.dataset.mountId;if(!ue||!le.contentDocument)continue;let je=H.find(ge=>ge.mountId===ue);if(!je)continue;let j=()=>{},oe=un(je.config),Re=oe?(()=>{var Y;let ge=(Y=le.contentDocument)==null?void 0:Y.getElementById(`preview-content-${ue}`);if(!ge)return null;let ce=$m(ge,je.config),_e=le.contentDocument.createElement("div");_e.id=ue,_e.style.height="100%",_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1",_e.style.minHeight="0",ce.host.appendChild(_e);let Le=()=>ce.syncWidgetState(tt.getState()),de=j;return j=()=>{ce.destroy(),de()},_e.__syncDock=Le,_e.__hostLayout=ce,_e})():le.contentDocument.getElementById(ue);if(!Re)continue;let tt=Om(Re,je.config);if(o.push(tt),oe&&Re.__syncDock){let ge=Re.__syncDock,ce=tt.on("widget:opened",ge),_e=tt.on("widget:closed",ge),Le=j;j=()=>{ce(),_e(),Le()},ge()}r.push(j),v&&tt.close()}if(((Z=n.scene)!=null?Z:"conversation")==="artifact"||(Ae=(X=(Ee=n.config)==null?void 0:Ee.features)==null?void 0:X.artifacts)!=null&&Ae.enabled)for(let le of o)le.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
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 ux(e,t){return[...e,Gl(t,e.length)]}function Gm(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function mx(e,t,n){var d,l;let o=Gl(e,t);if(!Gm(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 p=r;p<a.length;p+=r)i.push({message:{...o,content:a.slice(0,p),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var gx=()=>[{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()}],fx=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 Ym(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"&&fx(t)?[...gx(),...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 Yl(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:zm:e.suggestionChips,initialMessages:Ym(t,e,n),storageAdapter:Um};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Lr(e,t){var s,a,i,d;let n=e.theme?tn(e.theme,{validate:!1}):tn(),o=(s=e.scene)!=null?s:"conversation",r={...St,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return Yl(r,o,(d=e.appendedMessages)!=null?d:[])}function hx(e,t,n){var a,i,d;let o=e.theme?tn(e.theme,{validate:!1}):tn(),r=(a=e.scene)!=null?a:"conversation",s={...St,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return Yl(s,r,t)}function Xm(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:Lr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Lr(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:Lr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Lr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Lr(e,n),shellMode:n}]}function bx(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function p(){var R;return(R=n.device)!=null?R:"desktop"}function m(){var R;return(R=n.zoom)!=null?R:i}function f(){var E,F;let R=getComputedStyle(e),H=parseFloat(R.paddingLeft)+parseFloat(R.paddingRight),D=parseFloat(R.paddingTop)+parseFloat(R.paddingBottom),B=40,v=((E=n.compareMode)!=null?E:"off")!=="off",x=(e.clientWidth-H-B)/(v?2:1),k=e.clientHeight-D-B;if(x<=0||k<=0)return 1;let S=(F=ts[p()])!=null?F:ts.desktop;return Math.min(x/S.w,k/S.h,1)}function u(){var D,B,v;i=f();let R=Math.max(Ul,Math.min(zl,m()));d=R;let H=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of H){let k=(D=x.dataset.device)!=null?D:"desktop",S=(B=ts[k])!=null?B:ts.desktop;x.style.width=`${S.w*R}px`,x.style.height=`${S.h*R}px`,k==="mobile"&&(x.style.borderRadius=`${32*R}px`);let E=x.querySelector("iframe");E&&(E.style.width=`${S.w}px`,E.style.height=`${S.h}px`,E.style.transformOrigin="top left",E.style.transition="none",E.style.transform=`scale(${R})`)}(v=n.onScaleChange)==null||v.call(n,R)}function w(){var R;(R=n.onBeforeDestroy)==null||R.call(n);for(let H of o)H.destroy();for(let H of r)H();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var ge,ie,be,Fe;if(a)return;w();let R=++l,H=Xm(n),D=p(),B=((ge=n.compareMode)!=null?ge:"off")!=="off",v=((ie=n.scene)!=null?ie:"conversation")==="minimized",x=(be=n.widgetCssPath)!=null?be:"/widget-dist/widget.css",k=(Fe=n.buildSrcdoc)!=null?Fe:Kl,S=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",E=ve=>`<div class="${S}" data-mount-id="${ve.mountId}" data-device="${D}" data-shell-mode="${ve.shellMode}">
194
+ ${B?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ii(ve.label)}</span></div>`:""}
195
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ve.mountId}"></iframe>
196
+ </div>`,F=B?`<div class="preview-compare-grid">${H.map(ve=>`<div class="preview-compare-cell">${E(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${E(H[0])}</div>`;n.morphContainer?n.morphContainer(e,F):e.innerHTML=F,u();let $=C(),j=0,me=$.length,se=()=>{var J,Le,Y,xe,Se;if(a||R!==l)return;for(let de of $){let we=de.dataset.mountId;if(!we||!de.contentDocument)continue;let Ue=H.find(ye=>ye.mountId===we);if(!Ue)continue;let te=()=>{},ne=pn(Ue.config),re=ne?(()=>{var K;let ye=(K=de.contentDocument)==null?void 0:K.getElementById(`preview-content-${we}`);if(!ye)return null;let le=$m(ye,Ue.config),$e=de.contentDocument.createElement("div");$e.id=we,$e.style.height="100%",$e.style.display="flex",$e.style.flexDirection="column",$e.style.flex="1",$e.style.minHeight="0",le.host.appendChild($e);let Be=()=>le.syncWidgetState(nt.getState()),ce=te;return te=()=>{le.destroy(),ce()},$e.__syncDock=Be,$e.__hostLayout=le,$e})():de.contentDocument.getElementById(we);if(!re)continue;let nt=Om(re,Ue.config);if(o.push(nt),ne&&re.__syncDock){let ye=re.__syncDock,le=nt.on("widget:opened",ye),$e=nt.on("widget:closed",ye),Be=te;te=()=>{le(),$e(),Be()},ye()}r.push(te),v&&nt.close()}if(((J=n.scene)!=null?J:"conversation")==="artifact"||(xe=(Y=(Le=n.config)==null?void 0:Le.features)==null?void 0:Y.artifacts)!=null&&xe.enabled)for(let de of o)de.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`});(fe=n.onAfterMount)==null||fe.call(n,{iframes:$,controllers:[...o]})};for(let ye of $){let Z=ye.dataset.mountId;if(!Z)continue;let Ee=H.find(X=>X.mountId===Z);Ee&&(ye.addEventListener("load",()=>{q++,q>=me&&re()},{once:!0}),ye.srcdoc=E(Z,Ee.shellMode,un(Ee.config),w))}me===0&&re()}function W(){var D;if(a)return;let L=Xm(n);if(o.length!==L.length){M();return}if(L.some(B=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!v||v.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,v)=>{var w;B.update(L[v].config),((w=n.scene)!=null?w:"conversation")==="minimized"&&B.close()});for(let B of L){let v=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);v&&ql(v,B.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:C(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||g()}),s.observe(e)),M(),{update(L){if(a)return;let H=L.device!==void 0&&L.device!==n.device||L.scene!==void 0&&L.scene!==n.scene||L.compareMode!==void 0&&L.compareMode!==n.compareMode||L.widgetCssPath!==void 0&&L.widgetCssPath!==n.widgetCssPath;n={...n,...L},H?M():W()},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(L){a||(n={...n,zoom:L},g())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Ri={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"},yx=/^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 vx(e){return yx.test(e)}function ns(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=Ri[t];if(n)return n;let o=ks(t);if(Gi(o)||o==="transparent"||vx(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(Ri).slice(0,6).join(", ")}).`)}var Pi=Ea.map(e=>e==="gray"?"neutral":e),xx={...Object.fromEntries(Pi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Wi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=xx[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 Bi(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 Hi(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 wx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Di(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=wx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Fi(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=ji(t);return Ki(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Oi(e){for(let t of zr){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 Qm=Oi("typo-font-family"),Zs=Oi("typo-font-size"),ea=Oi("typo-font-weight"),Ii=Oi("typo-line-height"),Jm={...Qm,monospace:Qm.mono},Zm={...Zs,small:Zs.sm,md:Zs.base,medium:Zs.base,large:Zs.lg},eg={...ea,400:ea.normal,500:ea.medium,600:ea.semibold,700:ea.bold},tg={...Ii,"1.25":Ii.tight,"1.5":Ii.normal,"1.625":Ii.relaxed};function ng(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 og="theme.palette.radius.";function Cx(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of zr)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(og)&&typeof i=="string"&&(s[a.slice(og.length)]=i);e[r[1]]=s}return e}var na=Cx(),rg=["sm","md","lg","xl","full"];function _i(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?_i(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?_i(e,r,n,o+1):null}function Ni(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 os(e){return e.replace(/^role-/,"")}function Sx(e){for(let[t,n]of Object.entries(na))if(rg.every(o=>e[o]===n[o]))return t;return"custom"}function Lr(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 xr)n[os(s.roleId)]=Ji(a=>e.get(`theme.${a}`),s);return{brand:{primary:Yl(e.get("theme.palette.colors.primary.500")),secondary:Yl(e.get("theme.palette.colors.secondary.500")),accent:Yl(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:Ni(e,"theme.semantic.typography.fontFamily"),fontSize:Ni(e,"theme.semantic.typography.fontSize"),fontWeight:Ni(e,"theme.semantic.typography.fontWeight"),lineHeight:Ni(e,"theme.semantic.typography.lineHeight")},roundness:{style:Sx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Yl(e){return typeof e=="string"&&e!==""?e:null}var ta=[{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 sg(e){let t=new Set(e.targets.map(n=>n.path));return ta.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Ax={AA:4.5,AAA:7};function Tx(e){return Math.round(e*100)/100}function kx(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=Ur.indexOf(a[2]),l=null,u=1/0;return Ur.forEach((p,f)=>{let g=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof g!="string"||!(g.startsWith("#")||g.startsWith("rgb")))&&ka(g,n)>=o){let x=d>=0?Math.abs(f-d):f;x<u&&(u=x,l=`palette.colors.${i}.${p}`)}}),l}function oa(e,t="AA",n="both",o){let r=Ax[t],s=n==="both"?["light","dark"]:[n],a=o?ta.filter(d=>o.includes(d.key)):ta,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let p=_i(e,u.fg,l),f=_i(e,u.bg,l);if(!p||!f)continue;let g=Tx(ka(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 M=kx(e,u.fg,f,r,l);M&&(C.suggestion=M)}i.push(C)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function rs(e,t,n="light",o="AA"){return t.length===0?[]:oa(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 an={};for(let e of xr){let t=os(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Ex(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=xr.map(r=>os(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function ag(){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 el)t(n.sections);for(let n of Oa)t(n.sections);return e}var Mx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Lx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Xl=["bottom-right","bottom-left","top-right","top-left"],Ql=["bubble","flat","minimal"],Ix={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function ig(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,w,E=n)=>{let S={};return(E==="light"||E==="both")&&(S[`theme.${v}`]=w),(E==="dark"||E==="both")&&(S[`darkTheme.${v}`]=w),S},a=v=>{if(n==="both")return v;let w={};for(let[E,S]of Object.entries(v))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(w[E]=S);return w},i=()=>n==="dark"?"dark":"light",d=(v,w=[])=>Vo({ok:!0,summary:Lr(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),E={summary:Lr(e),availableRoles:xr.map(S=>({role:os(S.roleId),helper:S.helper})),availableFamilies:Pi,presets:Ms.map(S=>{var k;return{id:S.id,name:S.name,description:S.description,tags:(k=S.tags)!=null?k:[]}}),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=ag()),E.fieldIndex=Array.from(o.values()).map(S=>{var k;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(k=S.options)==null?void 0:k.map(F=>F.value)}})),Vo(E)}},{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),E=["primary","secondary","accent"],S={},k={};for(let $ of E){if(w[$]===void 0)continue;let q=ns(w[$]);k[$]=q;let me=Xi(q);for(let re of Ur){let be=me[re];be!==void 0&&Object.assign(S,s(`palette.colors.${$}.${re}`,be))}}if(Object.keys(k).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let F=rs(e,["primary-button","user-message"],i());return d(k,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:Pi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let w=r(v),E=Ex(w.role),S=Wi(w.family,!0),k=Bi(w.intensity),F=a(Fa(S,k,E)),$=Object.keys(F).length;e.setBatch(F);let q=rs(e,sg(E),i());return d({role:os(E.roleId),family:S,intensity:k,tokensWritten:$},q)}},{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),E={},S={},k=(F,$)=>{var me;if(w[F]===void 0)return;let q=ng(w[F],$,F);S[F]=(me=q.split(".").pop())!=null?me:q,Object.assign(E,s(`semantic.typography.${F}`,q))};if(k("fontFamily",Jm),k("fontSize",Zm),k("fontWeight",eg),k("lineHeight",tg),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),d(S)}},{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),E={},S={};if(w.style!==void 0){let k=Di(w.style);S.style=k;for(let[F,$]of Object.entries(na[k]))Object.assign(E,s(`palette.radius.${F}`,$))}if(w.radius!==void 0){let k=r(w.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(k[$]===void 0)continue;let q=Fi(k[$]);F[$]=q,Object.assign(E,s(`palette.radius.${$}`,q))}S.radius=F}if(Object.keys(E).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(E),d(S)}},{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),E={};if(w.scheme!==void 0){let S=Hi(w.scheme);e.set("colorScheme",S),E.scheme=S}if(w.editTarget!==void 0){let S=String(w.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${w.editTarget}". Valid: light, dark, both.`);n=S,E.editTarget=S}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Lr(e),warnings:[],applied:E,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),E=tl(String(w!=null?w:""));if(!E){let $=Ms.map(q=>q.id).join(", ");throw new Error(`Unknown preset "${w}". Valid presets: ${$}.`)}let S=nn(E.theme,{validate:!1}),k={...e.getConfig()};E.darkTheme&&(k.darkTheme=nn(E.darkTheme,{validate:!1})),E.toolCall&&(k.toolCall=E.toolCall),e.setFullConfig(k,S);let F=rs(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.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:Xl},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:Ql}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,q,me;let w=r(v),E={},S={};if(w.launcherPosition!==void 0){let re=String(w.launcherPosition);if(!Xl.includes(re))throw new Error(`Unknown launcherPosition "${re}". Valid: ${Xl.join(", ")}.`);E["launcher.position"]=re,S.launcherPosition=re}let k=r(w.features);for(let[re,be]of Object.entries(Mx))k[re]!==void 0&&(E[be]=!!k[re],($=S.features)!=null||(S.features={}),S.features[re]=!!k[re]);let F=r(w.layout);for(let[re,be]of Object.entries(Lx))if(F[re]!==void 0)if(re==="messageStyle"){let ie=String(F[re]);if(!Ql.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Ql.join(", ")}.`);E[be]=ie,(q=S.layout)!=null||(S.layout={}),S.layout[re]=ie}else E[be]=!!F[re],(me=S.layout)!=null||(S.layout={}),S.layout[re]=!!F[re];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),d(S)}},{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),E={},S={};for(let[k,F]of Object.entries(Ix))w[k]!==void 0&&(E[F]=String(w[k]),S[k]=String(w[k]));if(w.suggestions!==void 0){if(!Array.isArray(w.suggestions))throw new Error("`suggestions` must be an array of strings.");let k=w.suggestions.filter(F=>typeof F=="string");E.suggestionChips=k,S.suggestions=k}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(S)}},{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: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=ag());let E={},S=[];for(let $ of w){let q=r($),me=String((F=q.field)!=null?F:"");try{let re=o.get(me),be=re?re.path:me;if(!re&&!/^(theme|darkTheme)\.|\./.test(be))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Rx(re,q.value);if(re&&be.startsWith("theme.")){let we=s(be.slice(6),ie);Object.assign(E,we),S.push({field:me,resolvedPath:Object.keys(we),ok:!0})}else E[be]=ie,S.push({field:me,resolvedPath:be,ok:!0})}catch(re){S.push({field:me,ok:!1,error:re.message})}}let k=S.filter($=>$.ok);return Object.keys(E).length>0&&e.setBatch(E),Vo({ok:k.length>0,summary:Lr(e),warnings:[],applied:{updates:S}})}},{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),E=w.level==="AAA"?"AAA":"AA",S=w.variant==="light"||w.variant==="dark"?w.variant:"both",k=oa(e,E,S);return Vo({level:k.level,passing:k.checks.length-k.failures.length,total:k.checks.length,checks:k.checks,failures:k.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 Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${w}". Valid: undo, redo, reset, export.`)}}}]}function Rx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ns(t)):ns(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}}export{bu as ADVANCED_TOKENS_SECTION,xr as ALL_ROLES,el as ALL_TABS,mu as BRAND_PALETTE_SECTION,vu as BUILT_IN_PRESETS,Og as COLORS_SECTIONS,Qi as COLOR_FAMILIES,du as COMPONENTS_SECTIONS,cu as COMPONENT_COLOR_SECTIONS,lu as COMPONENT_SHAPE_SECTIONS,pu as CONFIGURE_SECTIONS,Oa as CONFIGURE_SUB_GROUPS,ta as CONTRAST_PAIRS,Ri as CSS_NAMED_COLORS,ts as DEVICE_DIMENSIONS,zm as HOME_SUGGESTION_CHIPS,fu as INTERFACE_ROLES_SECTION,jm as MOCK_BROWSER_CONTENT,Km as MOCK_WORKSPACE_CONTENT,Dg as PALETTE_SECTION,Um as PREVIEW_STORAGE_ADAPTER,na as RADIUS_PRESETS,Ra as ROLE_ASSISTANT_MESSAGES,Da as ROLE_BORDERS,Ea as ROLE_FAMILIES,Sg as ROLE_FAMILY_LABELS,La as ROLE_HEADER,Ba as ROLE_INPUT,ko as ROLE_INTENSITIES,Ha as ROLE_LINKS_FOCUS,Pa as ROLE_PRIMARY_ACTIONS,Wa as ROLE_SCROLL_TO_BOTTOM,Ma as ROLE_SURFACES,Ia as ROLE_USER_MESSAGES,Fg as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Mi as SHELL_STYLE_ID,hu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,wf as STYLE_SECTIONS_V2,Ms as THEME_EDITOR_PRESETS,uu as THEME_SECTION,qi as ThemeEditorState,Ul as ZOOM_MAX,$l as ZOOM_MIN,ux as appendPreviewTranscriptEntry,Gl as applySceneConfig,ql as applyShellTheme,Mr as buildPreviewConfig,hx as buildPreviewConfigWithMessages,zl as buildShellCss,jl as buildSrcdoc,Lr as buildSummary,mx as buildTranscriptStreamFrames,ns as coerceColor,Wi as coerceFamily,Bi as coerceIntensity,Fi as coerceRadius,Di as coerceRoundnessStyle,Hi as coerceScheme,xg as convertFromPx,vg as convertToPx,Ym as createPreviewMessages,Kl as createPreviewTranscriptEntry,ig as createThemeEditorTools,bx as createThemePreview,Ji as detectRoleAssignment,Li as escapeHtml,Sf as findSection,Ki as formatCssValue,Xi as generateColorScale,px as getPreviewTranscriptPresetLabel,qm as getShellPalette,tl as getThemeEditorPreset,ou as hexToHsl,ru as hslToHex,Gi as isValidHex,ks as normalizeColorValue,wg as paletteColorPath,ji as parseCssValue,Gm as presetStreamsText,rs as quickContrastWarnings,Fa as resolveRoleAssignment,su as resolveThemeColorPath,Yi as rgbToHex,oa as runContrastChecks,Af as scopeSection,Cg as tokenRefDisplayName,Vo as toolResult,ka as wcagContrastRatio};
204
+ - Resizable panes`});(Se=n.onAfterMount)==null||Se.call(n,{iframes:$,controllers:[...o]})};for(let ve of $){let J=ve.dataset.mountId;if(!J)continue;let Le=H.find(Y=>Y.mountId===J);Le&&(ve.addEventListener("load",()=>{j++,j>=me&&se()},{once:!0}),ve.srcdoc=k(J,Le.shellMode,pn(Le.config),x))}me===0&&se()}function I(){var D;if(a)return;let R=Xm(n);if(o.length!==R.length){M();return}if(R.some(B=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!v||v.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,v)=>{var x;B.update(R[v].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&B.close()});for(let B of R){let v=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);v&&jl(v,B.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:C(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(e)),M(),{update(R){if(a)return;let H=R.device!==void 0&&R.device!==n.device||R.scene!==void 0&&R.scene!==n.scene||R.compareMode!==void 0&&R.compareMode!==n.compareMode||R.widgetCssPath!==void 0&&R.widgetCssPath!==n.widgetCssPath;n={...n,...R},H?M():I()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},u())},getIframes(){return C()},getScale(){return d},setZoom(R){a||(n={...n,zoom:R},u())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Pi={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"},yx=/^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 vx(e){return yx.test(e)}function ns(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=Pi[t];if(n)return n;let o=ks(t);if(Yi(o)||o==="transparent"||vx(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(Pi).slice(0,6).join(", ")}).`)}var Wi=Ma.map(e=>e==="gray"?"neutral":e),xx={...Object.fromEntries(Wi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Bi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=xx[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 Hi(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 Di(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 wx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Fi(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=wx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Oi(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=Ki(t);return Gi(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Ni(e){for(let t of zr){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 Qm=Ni("typo-font-family"),Zs=Ni("typo-font-size"),ea=Ni("typo-font-weight"),Ri=Ni("typo-line-height"),Jm={...Qm,monospace:Qm.mono},Zm={...Zs,small:Zs.sm,md:Zs.base,medium:Zs.base,large:Zs.lg},eg={...ea,400:ea.normal,500:ea.medium,600:ea.semibold,700:ea.bold},tg={...Ri,"1.25":Ri.tight,"1.5":Ri.normal,"1.625":Ri.relaxed};function ng(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 og="theme.palette.radius.";function Cx(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of zr)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(og)&&typeof i=="string"&&(s[a.slice(og.length)]=i);e[r[1]]=s}return e}var na=Cx(),rg=["sm","md","lg","xl","full"];function Vi(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Vi(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Vi(e,r,n,o+1):null}function _i(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 os(e){return e.replace(/^role-/,"")}function Sx(e){for(let[t,n]of Object.entries(na))if(rg.every(o=>e[o]===n[o]))return t;return"custom"}function Ir(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 wr)n[os(s.roleId)]=Zi(a=>e.get(`theme.${a}`),s);return{brand:{primary:Xl(e.get("theme.palette.colors.primary.500")),secondary:Xl(e.get("theme.palette.colors.secondary.500")),accent:Xl(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:_i(e,"theme.semantic.typography.fontFamily"),fontSize:_i(e,"theme.semantic.typography.fontSize"),fontWeight:_i(e,"theme.semantic.typography.fontWeight"),lineHeight:_i(e,"theme.semantic.typography.lineHeight")},roundness:{style:Sx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Xl(e){return typeof e=="string"&&e!==""?e:null}var ta=[{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 sg(e){let t=new Set(e.targets.map(n=>n.path));return ta.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Ax={AA:4.5,AAA:7};function Tx(e){return Math.round(e*100)/100}function kx(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=Ur.indexOf(a[2]),l=null,p=1/0;return Ur.forEach((m,f)=>{let u=e.get(`${r}.palette.colors.${i}.${m}`);if(!(typeof u!="string"||!(u.startsWith("#")||u.startsWith("rgb")))&&Ea(u,n)>=o){let w=d>=0?Math.abs(f-d):f;w<p&&(p=w,l=`palette.colors.${i}.${m}`)}}),l}function oa(e,t="AA",n="both",o){let r=Ax[t],s=n==="both"?["light","dark"]:[n],a=o?ta.filter(d=>o.includes(d.key)):ta,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let p of a){let m=Vi(e,p.fg,l),f=Vi(e,p.bg,l);if(!m||!f)continue;let u=Tx(Ea(m,f)),w=u>=r,C={pair:p.key,label:p.label,variant:d,fg:m,bg:f,ratio:u,threshold:r,passes:w};if(!w){let M=kx(e,p.fg,f,r,l);M&&(C.suggestion=M)}i.push(C)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function rs(e,t,n="light",o="AA"){return t.length===0?[]:oa(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 an={};for(let e of wr){let t=os(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Ex(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=wr.map(r=>os(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function ag(){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 tl)t(n.sections);for(let n of Na)t(n.sections);return e}var Mx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Lx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Ql=["bottom-right","bottom-left","top-right","top-left"],Jl=["bubble","flat","minimal"],Ix={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function ig(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,x,k=n)=>{let S={};return(k==="light"||k==="both")&&(S[`theme.${v}`]=x),(k==="dark"||k==="both")&&(S[`darkTheme.${v}`]=x),S},a=v=>{if(n==="both")return v;let x={};for(let[k,S]of Object.entries(v))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=S);return x},i=()=>n==="dark"?"dark":"light",d=(v,x=[])=>Vo({ok:!0,summary:Ir(e),warnings:x,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:x}=r(v),k={summary:Ir(e),availableRoles:wr.map(S=>({role:os(S.roleId),helper:S.helper})),availableFamilies:Wi,presets:Ms.map(S=>{var E;return{id:S.id,name:S.name,description:S.description,tags:(E=S.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 x==="full"&&(o!=null||(o=ag()),k.fieldIndex=Array.from(o.values()).map(S=>{var E;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(E=S.options)==null?void 0:E.map(F=>F.value)}})),Vo(k)}},{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 x=r(v),k=["primary","secondary","accent"],S={},E={};for(let $ of k){if(x[$]===void 0)continue;let j=ns(x[$]);E[$]=j;let me=Qi(j);for(let se of Ur){let ge=me[se];ge!==void 0&&Object.assign(S,s(`palette.colors.${$}.${se}`,ge))}}if(Object.keys(E).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let F=rs(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:Wi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let x=r(v),k=Ex(x.role),S=Bi(x.family,!0),E=Hi(x.intensity),F=a(Oa(S,E,k)),$=Object.keys(F).length;e.setBatch(F);let j=rs(e,sg(k),i());return d({role:os(k.roleId),family:S,intensity:E,tokensWritten:$},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 x=r(v),k={},S={},E=(F,$)=>{var me;if(x[F]===void 0)return;let j=ng(x[F],$,F);S[F]=(me=j.split(".").pop())!=null?me:j,Object.assign(k,s(`semantic.typography.${F}`,j))};if(E("fontFamily",Jm),E("fontSize",Zm),E("fontWeight",eg),E("lineHeight",tg),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(S)}},{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 x=r(v),k={},S={};if(x.style!==void 0){let E=Fi(x.style);S.style=E;for(let[F,$]of Object.entries(na[E]))Object.assign(k,s(`palette.radius.${F}`,$))}if(x.radius!==void 0){let E=r(x.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(E[$]===void 0)continue;let j=Oi(E[$]);F[$]=j,Object.assign(k,s(`palette.radius.${$}`,j))}S.radius=F}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(S)}},{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 x=r(v),k={};if(x.scheme!==void 0){let S=Di(x.scheme);e.set("colorScheme",S),k.scheme=S}if(x.editTarget!==void 0){let S=String(x.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=S,k.editTarget=S}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Ir(e),warnings:[],applied:k,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:x}=r(v),k=nl(String(x!=null?x:""));if(!k){let $=Ms.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${$}.`)}let S=tn(k.theme,{validate:!1}),E={...e.getConfig()};k.darkTheme&&(E.darkTheme=tn(k.darkTheme,{validate:!1})),k.toolCall&&(E.toolCall=k.toolCall),e.setFullConfig(E,S);let F=rs(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.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:Ql},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:Jl}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,j,me;let x=r(v),k={},S={};if(x.launcherPosition!==void 0){let se=String(x.launcherPosition);if(!Ql.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Ql.join(", ")}.`);k["launcher.position"]=se,S.launcherPosition=se}let E=r(x.features);for(let[se,ge]of Object.entries(Mx))E[se]!==void 0&&(k[ge]=!!E[se],($=S.features)!=null||(S.features={}),S.features[se]=!!E[se]);let F=r(x.layout);for(let[se,ge]of Object.entries(Lx))if(F[se]!==void 0)if(se==="messageStyle"){let ie=String(F[se]);if(!Jl.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Jl.join(", ")}.`);k[ge]=ie,(j=S.layout)!=null||(S.layout={}),S.layout[se]=ie}else k[ge]=!!F[se],(me=S.layout)!=null||(S.layout={}),S.layout[se]=!!F[se];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(S)}},{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 x=r(v),k={},S={};for(let[E,F]of Object.entries(Ix))x[E]!==void 0&&(k[F]=String(x[E]),S[E]=String(x[E]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let E=x.suggestions.filter(F=>typeof F=="string");k.suggestionChips=E,S.suggestions=E}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(S)}},{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:x}=r(v);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=ag());let k={},S=[];for(let $ of x){let j=r($),me=String((F=j.field)!=null?F:"");try{let se=o.get(me),ge=se?se.path:me;if(!se&&!/^(theme|darkTheme)\.|\./.test(ge))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Rx(se,j.value);if(se&&ge.startsWith("theme.")){let be=s(ge.slice(6),ie);Object.assign(k,be),S.push({field:me,resolvedPath:Object.keys(be),ok:!0})}else k[ge]=ie,S.push({field:me,resolvedPath:ge,ok:!0})}catch(se){S.push({field:me,ok:!1,error:se.message})}}let E=S.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),Vo({ok:E.length>0,summary:Ir(e),warnings:[],applied:{updates:S}})}},{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 x=r(v),k=x.level==="AAA"?"AAA":"AA",S=x.variant==="light"||x.variant==="dark"?x.variant:"both",E=oa(e,k,S);return Vo({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:x}=r(v);switch(x){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 Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Rx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ns(t)):ns(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}}export{bu as ADVANCED_TOKENS_SECTION,wr as ALL_ROLES,tl as ALL_TABS,mu as BRAND_PALETTE_SECTION,vu as BUILT_IN_PRESETS,Og as COLORS_SECTIONS,Ji as COLOR_FAMILIES,du as COMPONENTS_SECTIONS,cu as COMPONENT_COLOR_SECTIONS,lu as COMPONENT_SHAPE_SECTIONS,pu as CONFIGURE_SECTIONS,Na as CONFIGURE_SUB_GROUPS,ta as CONTRAST_PAIRS,Pi as CSS_NAMED_COLORS,ts as DEVICE_DIMENSIONS,zm as HOME_SUGGESTION_CHIPS,fu as INTERFACE_ROLES_SECTION,jm as MOCK_BROWSER_CONTENT,Km as MOCK_WORKSPACE_CONTENT,Dg as PALETTE_SECTION,Um as PREVIEW_STORAGE_ADAPTER,na as RADIUS_PRESETS,Pa as ROLE_ASSISTANT_MESSAGES,Fa as ROLE_BORDERS,Ma as ROLE_FAMILIES,Sg as ROLE_FAMILY_LABELS,Ia as ROLE_HEADER,Ha as ROLE_INPUT,ko as ROLE_INTENSITIES,Da as ROLE_LINKS_FOCUS,Wa as ROLE_PRIMARY_ACTIONS,Ba as ROLE_SCROLL_TO_BOTTOM,La as ROLE_SURFACES,Ra as ROLE_USER_MESSAGES,Fg as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Li as SHELL_STYLE_ID,hu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,wf as STYLE_SECTIONS_V2,Ms as THEME_EDITOR_PRESETS,uu as THEME_SECTION,ji as ThemeEditorState,zl as ZOOM_MAX,Ul as ZOOM_MIN,ux as appendPreviewTranscriptEntry,Yl as applySceneConfig,jl as applyShellTheme,Lr as buildPreviewConfig,hx as buildPreviewConfigWithMessages,ql as buildShellCss,Kl as buildSrcdoc,Ir as buildSummary,mx as buildTranscriptStreamFrames,ns as coerceColor,Bi as coerceFamily,Hi as coerceIntensity,Oi as coerceRadius,Fi as coerceRoundnessStyle,Di as coerceScheme,xg as convertFromPx,vg as convertToPx,Ym as createPreviewMessages,Gl as createPreviewTranscriptEntry,ig as createThemeEditorTools,bx as createThemePreview,Zi as detectRoleAssignment,Ii as escapeHtml,Sf as findSection,Gi as formatCssValue,Qi as generateColorScale,px as getPreviewTranscriptPresetLabel,qm as getShellPalette,nl as getThemeEditorPreset,ou as hexToHsl,ru as hslToHex,Yi as isValidHex,ks as normalizeColorValue,wg as paletteColorPath,Ki as parseCssValue,Gm as presetStreamsText,rs as quickContrastWarnings,Oa as resolveRoleAssignment,su as resolveThemeColorPath,Xi as rgbToHex,oa as runContrastChecks,Af as scopeSection,Cg as tokenRefDisplayName,Vo as toolResult,Ea as wcagContrastRatio};