@runtypelabs/persona 3.29.1 → 3.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -0
- package/dist/codegen.cjs +6 -6
- package/dist/codegen.js +4 -4
- package/dist/index.cjs +47 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +112 -7
- package/dist/index.d.ts +112 -7
- package/dist/index.global.js +59 -59
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +47 -47
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/plugin-kit.cjs +1 -0
- package/dist/plugin-kit.d.cts +98 -0
- package/dist/plugin-kit.d.ts +98 -0
- package/dist/plugin-kit.js +1 -0
- package/dist/smart-dom-reader.d.cts +107 -4
- package/dist/smart-dom-reader.d.ts +107 -4
- package/dist/theme-editor.cjs +38 -38
- package/dist/theme-editor.d.cts +111 -6
- package/dist/theme-editor.d.ts +111 -6
- package/dist/theme-editor.js +38 -38
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +2 -0
- package/dist/theme-reference.d.ts +2 -0
- package/dist/theme-reference.js +1 -1
- package/package.json +8 -2
- package/src/components/approval-bubble.test.ts +268 -0
- package/src/components/approval-bubble.ts +170 -20
- package/src/components/launcher.ts +6 -3
- package/src/components/tool-bubble.test.ts +39 -0
- package/src/components/tool-bubble.ts +4 -0
- package/src/index-core.ts +1 -0
- package/src/plugin-kit.test.ts +230 -0
- package/src/plugin-kit.ts +294 -0
- package/src/plugins/types.ts +49 -2
- package/src/session.test.ts +99 -0
- package/src/session.ts +14 -3
- package/src/theme-editor/preview-utils.test.ts +10 -0
- package/src/theme-editor/preview-utils.ts +29 -1
- package/src/theme-editor/sections.test.ts +17 -0
- package/src/theme-editor/sections.ts +31 -0
- package/src/theme-reference.ts +1 -1
- package/src/types/theme.ts +2 -0
- package/src/types.ts +59 -2
- package/src/ui.approval-plugin.test.ts +204 -0
- package/src/ui.ts +149 -16
- package/src/utils/theme.test.ts +6 -2
- package/src/utils/theme.ts +0 -8
- package/src/utils/tokens.ts +6 -1
- package/src/webmcp-bridge.test.ts +66 -0
- package/src/webmcp-bridge.ts +49 -0
package/dist/theme-editor.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var Xp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ks(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];Xp(s)&&Xp(r)?n[o]=ks(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Ea="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 Qp(e,t){if(!(!e&&!t))return e?t?ks(e,t):e:t}function Jp(e){var t,n,o,r,s,a,i,d,l,m,u,g,p,w,S,M,I,L,H,D,W;return e?{...St,...e,theme:Qp(St.theme,e.theme),darkTheme:Qp(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,Oe,ve,Q,Le,Y,xe,Se;let v=(be=St.features)==null?void 0:be.artifacts,x=(Oe=e.features)==null?void 0:Oe.artifacts,k=(ve=St.features)==null?void 0:ve.scrollToBottom,C=(Q=e.features)==null?void 0:Q.scrollToBottom,T=(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&&C===void 0?void 0:{...k,...C},fe=T===void 0&&F===void 0?void 0:{...T,...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}:{},...fe!==void 0?{streamAnimation:fe}:{},...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:{...(u=(m=St.layout)==null?void 0:m.messages)==null?void 0:u.avatar,...(p=(g=e.layout)==null?void 0:g.messages)==null?void 0:p.avatar},timestamp:{...(S=(w=St.layout)==null?void 0:w.messages)==null?void 0:S.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(L=St.layout)==null?void 0:L.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...St.markdown,...e.markdown,options:{...(D=St.markdown)==null?void 0:D.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...St.messageActions,...e.messageActions}}:St}var pf={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"}},uf={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"}},mf={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:Ea,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 Zp(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 ff(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 eu(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]=eu(s,r):n[o]=r}return n}function gf(e,t){return t?eu(e,t):e}function tn(e,t={}){var r,s,a,i,d,l,m,u,g,p,w,S,M;let n={palette:pf,semantic:uf,components:mf},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,...(m=e==null?void 0:e.semantic)==null?void 0:m.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(w=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(S=e==null?void 0:e.semantic)==null?void 0:S.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:gf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=ff(o);if(!I.valid)throw new Error(`Theme validation failed: ${I.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let I of t.plugins)o=I.transform(o);return o}function tu(e){var S,M,I,L,H,D,W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve,Q,Le,Y,xe,Se,de,we,ze,te,ne,re,nt,ye,le,Ue,He,ce,G,Ve,Et,pe,ae,Ln,Nt,ln,Dn,Jn,qe,_,ke,De,Fe,$e,dt,ot,At,Vt,q,_t,Qe,Ft,oe,ge,xt,$t,Jt,yn,Tt,wt,gt,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,ft,Kt,Gt,qn,Ko,oo,uo,jn;let t=Zp(e),n={};for(let[E,Kn]of Object.entries(t)){let mo=E.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(S=n["--persona-semantic-colors-primary"])!=null?S: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"]=(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"]=(W=n["--persona-semantic-colors-text"])!=null?W: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"]=(C=n["--persona-semantic-colors-divider"])!=null?C:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(T=n["--persona-components-voice-recording-indicator"])!=null?T: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"]=(fe=n["--persona-components-approval-requested-text"])!=null?fe: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"]=(Oe=n["--persona-components-attachment-image-background"])!=null?Oe: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"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q: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"]=(ze=n["--persona-palette-radius-xl"])!=null?ze:"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"]=(Ue=n["--persona-components-button-primary-background"])!=null?Ue:n["--persona-primary"],n["--persona-button-primary-fg"]=(He=n["--persona-components-button-primary-foreground"])!=null?He:n["--persona-text-inverse"],n["--persona-button-radius"]=(G=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?G:"9999px",n["--persona-panel-radius"]=(Et=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve: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"]=(_=(qe=n["--persona-components-message-assistant-borderRadius"])!=null?qe: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"]=(De=n["--persona-components-header-border"])!=null?De:n["--persona-divider"],n["--persona-header-icon-bg"]=(Fe=n["--persona-components-header-iconBackground"])!=null?Fe:n["--persona-primary"],n["--persona-header-icon-fg"]=($e=n["--persona-components-header-iconForeground"])!=null?$e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(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"]=(ge=(oe=r==null?void 0:r.shadow)!=null?oe:n["--persona-components-introCard-shadow"])!=null?ge:"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"]=(gt=n["--persona-components-message-assistant-text"])!=null?gt: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"]=(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 m=e.components,u=m==null?void 0:m.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=m==null?void 0:m.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let p=m==null?void 0:m.toggleGroup;p&&(p.gap&&(n["--persona-toggle-group-gap"]=p.gap),p.borderRadius&&(n["--persona-toggle-group-radius"]=p.borderRadius));let w=m==null?void 0:m.artifact;if(w!=null&&w.toolbar){let E=w.toolbar;E.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=E.iconHoverColor),E.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=E.iconHoverBackground),E.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=E.iconPadding),E.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=E.iconBorderRadius),E.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=E.iconBorder),E.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=E.toggleGroupGap),E.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=E.toggleBorderRadius),E.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=E.copyBackground),E.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=E.copyBorder),E.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=E.copyColor),E.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=E.copyBorderRadius),E.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=E.copyPadding),E.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=E.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:E.copyMenuBackground),E.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=E.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:E.copyMenuBorder),E.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=E.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:E.copyMenuShadow),E.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=E.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:E.copyMenuBorderRadius),E.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=E.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:E.copyMenuItemHoverBackground),E.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=E.iconBackground),E.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=E.toolbarBorder)}if(w!=null&&w.tab){let E=w.tab;E.background&&(n["--persona-artifact-tab-bg"]=E.background),E.activeBackground&&(n["--persona-artifact-tab-active-bg"]=E.activeBackground),E.activeBorder&&(n["--persona-artifact-tab-active-border"]=E.activeBorder),E.borderRadius&&(n["--persona-artifact-tab-radius"]=E.borderRadius),E.textColor&&(n["--persona-artifact-tab-color"]=E.textColor),E.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=E.hoverBackground),E.listBackground&&(n["--persona-artifact-tab-list-bg"]=E.listBackground),E.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=E.listBorderColor),E.listPadding&&(n["--persona-artifact-tab-list-padding"]=E.listPadding)}if(w!=null&&w.pane){let E=w.pane;if(E.toolbarBackground){let Kn=(jn=Vr(e,E.toolbarBackground))!=null?jn:E.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var hf={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"}}},nu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ji=()=>{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"},bf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ji()},yf=e=>bf(e),vf=e=>tn(e),xf=e=>{var n;let t=tn(void 0,{validate:!1});return tn({...e,palette:{...t.palette,colors:{...hf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ma=e=>{let t=yf(e),n=nu(e==null?void 0:e.theme),o=nu(e==null?void 0:e.darkTheme);return t==="dark"?xf(ks(n!=null?n:{},o!=null?o:{})):vf(n)},wf=e=>tu(e),$r=(e,t)=>{var s;let n=Ma(t),o=wf(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)},ou=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ji())});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(ji());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 Ki(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 Gi=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.")?Ki(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Ki((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):Ki(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 Yi(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 Xi(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Cf(e,t){return t==="rem"?e*16:e}function Sf(e,t){return t==="rem"?e/16:e}function Es(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 Qi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Ji(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("%"),m=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(m)?Math.max(0,Math.min(255,Math.round(l?m/100*255:m))):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 La(e,t){let n=s=>{var l;let a=Es(s),i=a.startsWith("rgb")?(l=Ji(a))!=null?l:"#000000":a,d=[1,3,5].map(m=>{let u=parseInt(i.slice(m,m+2),16)/255;return u<=.03928?u/12.92:Math.pow((u+.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 ru(e){var g;let t=Es(e),n=t.startsWith("rgb")?(g=Ji(t))!=null?g:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,m=d>.5?l/(2-a-i):l/(a+i),u;switch(a){case o:u=((r-s)/l+(r<s?6:0))/6;break;case r:u=((s-o)/l+2)/6;break;default:u=((o-r)/l+4)/6;break}return{h:u*360,s:m,l:d}}function su(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 m=u=>{let g=Math.round((u+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${m(i)}${m(d)}${m(l)}`}function Zi(e){let{h:t,s:n,l:o}=ru(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]=su(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],el=["primary","secondary","accent","gray","success","warning","error","info"];function Af(e,t){return`palette.colors.${e}.${t}`}function au(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.")?au(e,`theme.${o}`,n+1):"#cbd5e1"}function Tf(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"}],Ia=["primary","secondary","accent","gray"],kf={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ra={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"}]},Pa={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"}]},Wa={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"}]},Ba={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"}]},Ha={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"}]},Da={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"}]},Fa={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"}]},Oa={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"}]},Na={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},wr=[Ra,Pa,Wa,Ba,Ha,Da,Fa,Oa,Na];function _a(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ef(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 Ef(e,t,n,o){let r=t==="solid";if(o==="role-header")return Mf(e,r,n);if(o==="role-input")return Lf(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 Mf(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 Lf(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 If=/^palette\.colors\.(\w+)\.(\d+)$/;function tl(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(If);if(!r)return null;let s=r[1],a=Ia.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=_a(a,l,t);if(t.targets.every(g=>{var w;return String((w=e(g.path))!=null?w:"")===m[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var Rf={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"}]}]},Pf={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"}]},Wf={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"}}]},Bf={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)"}]}]},Hf={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"}]}]},Df={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"}}]},Ff={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)"}]},Of={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=[Pf,Wf,Hf,Bf,Rf,Df,Ff,Of];function iu(){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:el.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 lu={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"}}]},Nf=iu(),_f=lu,Vf=[iu(),lu],$f={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:Ea},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Uf={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},zf={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"}]}]},qf={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"}]}]},jf={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"}]}]},Kf={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"}}]},Gf={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Yf={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Xf={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"}}]},Qf={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"}]},cu=[$f,Uf,zf,qf,jf],du=[Kf,Gf,Yf,Xf,Qf],pu=[...cu,...du],nl=1024*1024,Jf=["What can you help me with?","Tell me about your features","How does this work?"],Ms={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 Zf(e){return Number(e)*nl}function eg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/nl)):String(t):"10"}function tg(e){var t;return(t=Ms[String(e)])!=null?t:Ms.images}function ng(e){let t=Array.isArray(e)?e:Ms.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Ms)){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 og={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"}]},rg={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:Jf}]},sg={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:""}]},ag={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}]},ig={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},lg={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},cg={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"}]},dg={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},pg={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},ug={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"}]},mg={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"}]},fg={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"}]},gg={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:""}]},hg={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)}]},bg={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*nl,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:eg,parseValue:Zf},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Ms.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:ng,parseValue:tg}]},yg={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"}]}]},vg={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}]},xg={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"}]}]},wg={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}]},Cg={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}]},Va=[{label:"Content",sections:[og,rg]},{label:"Layout",sections:[sg,ag,ig,lg]},{label:"Widget",sections:[cg,dg,pg,ug,mg,fg]},{label:"Features",sections:[gg,hg,bg,yg,vg]},{label:"Developer",collapsedByDefault:!0,sections:[xg,wg,Cg]}],uu=Va.flatMap(e=>e.sections),mu={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"}]}]},fu={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"}]},hu={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:Ra},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Pa},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Wa},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ba},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Ha},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Da},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Fa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Oa},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Na}]},bu={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"}}]},yu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Sg=[mu,fu,gu,hu,bu,yu],ol=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:pu},{id:"configure",label:"Configure",sections:uu}];function vu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Ag(e,t,n){return{...e,id:`${n}-${e.id}`,path:vu(e.path,t)}}function Tg(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function kg(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=>Ag(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])=>[vu(d,t),l]))}))}}var xu=[{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"]}],Ls=[...xu];function rl(e){return Ls.find(t=>t.id===e)}import{Marked as Eg}from"marked";var Mg=e=>{if(e)return e},sl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Eg({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=Mg(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},$a=e=>e?sl({markedOptions:e.options,renderer:e.renderer}):sl(),ew=sl();var Is=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");import Lg from"dompurify";var Ig={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"]},Rg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pg=()=>{let e=Lg(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:")&&!Rg.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Ig)},Ua=e=>e===!1?null:typeof e=="function"?e:Pg();var al="webmcp:",za={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Cu(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}:${Wg(t.join(""))}`}function wu(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 Wg(e){let t=wu(e,0).toString(36),n=wu(e,2654435761).toString(36);return`${t}.${n}`}var qa=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 za.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=Dg(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 p=typeof document!="undefined"&&!!document.modelContext;return vo(p?"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=Bg(t),a;try{a=await r.getTools()}catch(p){let w=p instanceof Error?p.message:String(p);return vo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(p=>p.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,m=!1,u=setTimeout(()=>{m=!0,l.abort()},this.timeoutMs),g=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",g,{once:!0}));try{let p=await r.executeTool(i,_g(n),{signal:l.signal});return Fg(p)}catch(p){if(m)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let w=p instanceof Error?p.message:String(p);return vo(w)}finally{clearTimeout(u),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){za.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,za.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:Og;try{return await n(t)}catch(r){return za.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=>Hg(t,o))}},Bg=e=>e.startsWith(al)?e.slice(al.length):e,qr=e=>e.startsWith(al),Hg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Dg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Fg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Vg(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Og=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ng(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
1
|
+
var nu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ps(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];nu(s)&&nu(r)?n[o]=Ps(s,r):n[o]=r}return n}var go="min(440px, calc(100vw - 24px))",La="440px",It={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:go,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 ou(e,t){if(!(!e&&!t))return e?t?Ps(e,t):e:t}function ru(e){var t,n,o,r,s,a,i,d,l,m,p,f,u,C,v,E,L,I,P,H,W;return e?{...It,...e,theme:ou(It.theme,e.theme),darkTheme:ou(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(t=It.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=It.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Fe,xe,j,de,K,ye,le;let x=(be=It.features)==null?void 0:be.artifacts,w=(Fe=e.features)==null?void 0:Fe.artifacts,k=(xe=It.features)==null?void 0:xe.scrollToBottom,S=(j=e.features)==null?void 0:j.scrollToBottom,A=(de=It.features)==null?void 0:de.streamAnimation,N=(K=e.features)==null?void 0:K.streamAnimation,$=(ye=It.features)==null?void 0:ye.askUserQuestion,G=(le=e.features)==null?void 0:le.askUserQuestion,fe=x===void 0&&w===void 0?void 0:{...x,...w,layout:{...x==null?void 0:x.layout,...w==null?void 0:w.layout}},ge=k===void 0&&S===void 0?void 0:{...k,...S},se=A===void 0&&N===void 0?void 0:{...A,...N},ke=$===void 0&&G===void 0?void 0:{...$,...G,styles:{...$==null?void 0:$.styles,...G==null?void 0:G.styles}};return{...It.features,...e.features,...ge!==void 0?{scrollToBottom:ge}:{},...fe!==void 0?{artifacts:fe}:{},...se!==void 0?{streamAnimation:se}:{},...ke!==void 0?{askUserQuestion:ke}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(a=It.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=It.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(m=It.layout)==null?void 0:m.messages)==null?void 0:p.avatar,...(u=(f=e.layout)==null?void 0:f.messages)==null?void 0:u.avatar},timestamp:{...(v=(C=It.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(L=(E=e.layout)==null?void 0:E.messages)==null?void 0:L.timestamp}},slots:{...(I=It.layout)==null?void 0:I.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...It.markdown,...e.markdown,options:{...(H=It.markdown)==null?void 0:H.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var Sg={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"}},Ag={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"}},Tg={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:go,maxWidth:La,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function jr(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."))?jr(e,o):o}function su(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=jr(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 kg(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 au(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]=au(s,r):n[o]=r}return n}function Eg(e,t){return t?au(e,t):e}function sn(e,t={}){var r,s,a,i,d,l,m,p,f,u,C,v,E;let n={palette:Sg,semantic:Ag,components:Tg},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,...(m=e==null?void 0:e.semantic)==null?void 0:m.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,...(C=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:C.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Eg(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let L=kg(o);if(!L.valid)throw new Error(`Theme validation failed: ${L.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let L of t.plugins)o=L.transform(o);return o}function iu(e){var v,E,L,I,P,H,W,x,w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe,j,de,K,ye,le,te,Ce,Ue,ee,oe,ae,rt,Ae,pe,$e,We,ue,X,Ne,Bt,he,ce,Rn,$t,mn,Dn,eo,ze,_,Me,Be,He,_e,ut,st,Rt,qt,q,Ut,Je,_t,re,we,Tt,jt,en,Sn,Pt,Et,xt,Ct,Kt,nt,Fn,to,An,On,ht,Eo,Nn,dr,Pn,Hr,qo,Bo,St,_n,Vn,Tn,Mt,no,oo,$n,jo,Ho,Ko,Un,Dt,kn,ro,Go,Do,Yo,Mo,zn,bo,yt,Yt,Xt,qn,Xo,so,yo,jn,V,ao;let t=su(e),n={};for(let[ve,Kn]of Object.entries(t)){let io=ve.replace(/\./g,"-");n[`--persona-${io}`]=Kn.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(L=n["--persona-semantic-colors-accent"])!=null?L:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(H=n["--persona-semantic-colors-container"])!=null?H:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(x=n["--persona-semantic-colors-text-muted"])!=null?x: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"]=(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"]=(A=n["--persona-components-voice-recording-indicator"])!=null?A:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(N=n["--persona-components-voice-recording-background"])!=null?N: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"]=(G=n["--persona-components-voice-speaking-icon"])!=null?G:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(fe=n["--persona-components-approval-requested-background"])!=null?fe:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ge=n["--persona-components-approval-requested-border"])!=null?ge:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(se=n["--persona-components-approval-requested-text"])!=null?se:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ke=n["--persona-components-approval-requested-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(be=n["--persona-components-approval-approve-background"])!=null?be:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Fe=n["--persona-components-approval-deny-background"])!=null?Fe:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(xe=n["--persona-components-attachment-image-background"])!=null?xe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(j=n["--persona-components-attachment-image-border"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(de=n["--persona-semantic-typography-fontFamily"])!=null?de:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(K=n["--persona-semantic-typography-fontSize"])!=null?K:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(le=n["--persona-semantic-typography-lineHeight"])!=null?le:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(te=n["--persona-palette-radius-sm"])!=null?te:"0.125rem",n["--persona-radius-md"]=(Ce=n["--persona-palette-radius-md"])!=null?Ce:"0.375rem",n["--persona-radius-lg"]=(Ue=n["--persona-palette-radius-lg"])!=null?Ue:"0.5rem",n["--persona-radius-xl"]=(ee=n["--persona-palette-radius-xl"])!=null?ee:"0.75rem",n["--persona-radius-full"]=(oe=n["--persona-palette-radius-full"])!=null?oe:"9999px",n["--persona-launcher-radius"]=(rt=(ae=n["--persona-components-launcher-borderRadius"])!=null?ae:n["--persona-palette-radius-full"])!=null?rt:"9999px",n["--persona-launcher-bg"]=(Ae=n["--persona-components-launcher-background"])!=null?Ae:n["--persona-primary"],n["--persona-launcher-fg"]=(pe=n["--persona-components-launcher-foreground"])!=null?pe:n["--persona-text-inverse"],n["--persona-launcher-border"]=($e=n["--persona-components-launcher-border"])!=null?$e:n["--persona-border"],n["--persona-button-primary-bg"]=(We=n["--persona-components-button-primary-background"])!=null?We:n["--persona-primary"],n["--persona-button-primary-fg"]=(ue=n["--persona-components-button-primary-foreground"])!=null?ue:n["--persona-text-inverse"],n["--persona-button-radius"]=(Ne=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?Ne:"9999px",n["--persona-panel-radius"]=(he=(Bt=n["--persona-components-panel-borderRadius"])!=null?Bt:n["--persona-radius-xl"])!=null?he:"0.75rem",n["--persona-panel-border"]=(ce=n["--persona-components-panel-border"])!=null?ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=($t=(Rn=n["--persona-components-panel-shadow"])!=null?Rn:n["--persona-palette-shadows-xl"])!=null?$t:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(mn=n["--persona-components-launcher-shadow"])!=null?mn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(eo=(Dn=n["--persona-components-input-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?eo:"0.5rem",n["--persona-message-user-radius"]=(_=(ze=n["--persona-components-message-user-borderRadius"])!=null?ze:n["--persona-radius-lg"])!=null?_:"0.5rem",n["--persona-message-assistant-radius"]=(Be=(Me=n["--persona-components-message-assistant-borderRadius"])!=null?Me:n["--persona-radius-lg"])!=null?Be:"0.5rem",n["--persona-header-bg"]=(He=n["--persona-components-header-background"])!=null?He:n["--persona-surface"],n["--persona-header-border"]=(_e=n["--persona-components-header-border"])!=null?_e:n["--persona-divider"],n["--persona-header-icon-bg"]=(ut=n["--persona-components-header-iconBackground"])!=null?ut:n["--persona-primary"],n["--persona-header-icon-fg"]=(st=n["--persona-components-header-iconForeground"])!=null?st:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Rt=n["--persona-components-header-titleForeground"])!=null?Rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(qt=n["--persona-components-header-subtitleForeground"])!=null?qt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(q=n["--persona-components-header-actionIconForeground"])!=null?q:n["--persona-muted"];let o=(Ut=e.components)==null?void 0:Ut.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(Je=e.components)==null?void 0:Je.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(re=n["--persona-components-introCard-borderRadius"])!=null?re:"1rem",n["--persona-intro-card-padding"]=(we=n["--persona-components-introCard-padding"])!=null?we:"1.5rem",n["--persona-intro-card-shadow"]=(jt=(Tt=r==null?void 0:r.shadow)!=null?Tt:n["--persona-components-introCard-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(en=n["--persona-components-input-background"])!=null?en:n["--persona-surface"],n["--persona-input-placeholder"]=(Sn=n["--persona-components-input-placeholder"])!=null?Sn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Pt=n["--persona-components-message-user-background"])!=null?Pt:n["--persona-accent"],n["--persona-message-user-text"]=(Et=n["--persona-components-message-user-text"])!=null?Et:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(xt=n["--persona-components-message-user-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Ct=n["--persona-components-message-assistant-background"])!=null?Ct:n["--persona-surface"],n["--persona-message-assistant-text"]=(Kt=n["--persona-components-message-assistant-text"])!=null?Kt:n["--persona-text"],n["--persona-message-assistant-border"]=(nt=n["--persona-components-message-assistant-border"])!=null?nt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Fn=n["--persona-components-message-assistant-shadow"])!=null?Fn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(An=(to=n["--persona-components-scrollToBottom-background"])!=null?to:n["--persona-button-primary-bg"])!=null?An:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(ht=(On=n["--persona-components-scrollToBottom-foreground"])!=null?On:n["--persona-button-primary-fg"])!=null?ht:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Eo=n["--persona-components-scrollToBottom-border"])!=null?Eo:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Nn=n["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",n["--persona-scroll-to-bottom-radius"]=(Hr=(Pn=(dr=n["--persona-components-scrollToBottom-borderRadius"])!=null?dr:n["--persona-button-radius"])!=null?Pn:n["--persona-radius-full"])!=null?Hr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Bo=(qo=n["--persona-components-scrollToBottom-shadow"])!=null?qo:n["--persona-palette-shadows-sm"])!=null?Bo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(St=n["--persona-components-scrollToBottom-padding"])!=null?St:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(_n=n["--persona-components-scrollToBottom-gap"])!=null?_n:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Tn=(Vn=n["--persona-components-scrollToBottom-fontSize"])!=null?Vn:n["--persona-palette-typography-fontSize-sm"])!=null?Tn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Mt=n["--persona-components-scrollToBottom-iconSize"])!=null?Mt:"14px",n["--persona-tool-bubble-shadow"]=(no=n["--persona-components-toolBubble-shadow"])!=null?no:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(oo=n["--persona-components-reasoningBubble-shadow"])!=null?oo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=($n=n["--persona-components-composer-shadow"])!=null?$n:"none",n["--persona-md-inline-code-bg"]=(jo=n["--persona-components-markdown-inlineCode-background"])!=null?jo:n["--persona-container"],n["--persona-md-inline-code-color"]=(Ho=n["--persona-components-markdown-inlineCode-foreground"])!=null?Ho:n["--persona-text"],n["--persona-md-link-color"]=(Un=(Ko=n["--persona-components-markdown-link-foreground"])!=null?Ko:n["--persona-accent"])!=null?Un:"#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"]=(Dt=n["--persona-components-markdown-codeBlock-background"])!=null?Dt:n["--persona-container"],n["--persona-md-code-block-border-color"]=(kn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?kn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ro=n["--persona-components-markdown-codeBlock-textColor"])!=null?ro:"inherit",n["--persona-md-table-header-bg"]=(Go=n["--persona-components-markdown-table-headerBackground"])!=null?Go:n["--persona-container"],n["--persona-md-table-border-color"]=(Do=n["--persona-components-markdown-table-borderColor"])!=null?Do:n["--persona-border"],n["--persona-md-hr-color"]=(Yo=n["--persona-components-markdown-hr-color"])!=null?Yo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Mo=n["--persona-components-markdown-blockquote-borderColor"])!=null?Mo:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(zn=n["--persona-components-markdown-blockquote-background"])!=null?zn:"transparent",n["--persona-md-blockquote-text-color"]=(bo=n["--persona-components-markdown-blockquote-textColor"])!=null?bo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(yt=n["--persona-components-collapsibleWidget-container"])!=null?yt:n["--persona-surface"],n["--cw-surface"]=(Yt=n["--persona-components-collapsibleWidget-surface"])!=null?Yt:n["--persona-surface"],n["--cw-border"]=(Xt=n["--persona-components-collapsibleWidget-border"])!=null?Xt:n["--persona-border"],n["--persona-message-border"]=(qn=n["--persona-components-message-border"])!=null?qn:n["--persona-border"];let m=e.components,p=m==null?void 0:m.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=m==null?void 0:m.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=m==null?void 0:m.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let C=m==null?void 0:m.artifact;if(C!=null&&C.toolbar){let ve=C.toolbar;ve.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ve.iconHoverColor),ve.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ve.iconHoverBackground),ve.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ve.iconPadding),ve.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ve.iconBorderRadius),ve.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ve.iconBorder),ve.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ve.toggleGroupGap),ve.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ve.toggleBorderRadius),ve.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ve.copyBackground),ve.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ve.copyBorder),ve.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ve.copyColor),ve.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ve.copyBorderRadius),ve.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ve.copyPadding),ve.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ve.copyMenuBackground,n["--persona-dropdown-bg"]=(Xo=n["--persona-dropdown-bg"])!=null?Xo:ve.copyMenuBackground),ve.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ve.copyMenuBorder,n["--persona-dropdown-border"]=(so=n["--persona-dropdown-border"])!=null?so:ve.copyMenuBorder),ve.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ve.copyMenuShadow,n["--persona-dropdown-shadow"]=(yo=n["--persona-dropdown-shadow"])!=null?yo:ve.copyMenuShadow),ve.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ve.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(jn=n["--persona-dropdown-radius"])!=null?jn:ve.copyMenuBorderRadius),ve.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ve.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(V=n["--persona-dropdown-item-hover-bg"])!=null?V:ve.copyMenuItemHoverBackground),ve.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ve.iconBackground),ve.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ve.toolbarBorder)}if(C!=null&&C.tab){let ve=C.tab;ve.background&&(n["--persona-artifact-tab-bg"]=ve.background),ve.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ve.activeBackground),ve.activeBorder&&(n["--persona-artifact-tab-active-border"]=ve.activeBorder),ve.borderRadius&&(n["--persona-artifact-tab-radius"]=ve.borderRadius),ve.textColor&&(n["--persona-artifact-tab-color"]=ve.textColor),ve.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ve.hoverBackground),ve.listBackground&&(n["--persona-artifact-tab-list-bg"]=ve.listBackground),ve.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ve.listBorderColor),ve.listPadding&&(n["--persona-artifact-tab-list-padding"]=ve.listPadding)}if(C!=null&&C.pane){let ve=C.pane;if(ve.toolbarBackground){let Kn=(ao=jr(e,ve.toolbarBackground))!=null?ao:ve.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"}}},lu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Xi=()=>{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"},Lg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Xi()},Ig=e=>Lg(e),Rg=e=>sn(e),Pg=e=>{var n;let t=sn(void 0,{validate:!1});return sn({...e,palette:{...t.palette,colors:{...Mg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ia=e=>{let t=Ig(e),n=lu(e==null?void 0:e.theme),o=lu(e==null?void 0:e.darkTheme);return t==="dark"?Pg(Ps(n!=null?n:{},o!=null?o:{})):Rg(n)},Wg=e=>iu(e),Kr=(e,t)=>{let n=Ia(t),o=Wg(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},cu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Xi())});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(Xi());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 Sr(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]:Sr((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?{...It,...n}:n!=null?n:It,this.theme=sn(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=Sr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:sn();this.config={...this.config,darkTheme:Sr(s,r,n)}}else this.config=Sr(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=Sr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:sn();this.config={...this.config,darkTheme:Sr(l,d,i)},o=!0}else this.config=Sr(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=sn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=sn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...It},this.theme=sn(),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=sn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Zi(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 el(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Bg(e,t){return t==="rem"?e*16:e}function Hg(e,t){return t==="rem"?e/16:e}function Ws(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 tl(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function nl(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("%"),m=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(m)?Math.max(0,Math.min(255,Math.round(l?m/100*255:m))):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 Ra(e,t){let n=s=>{var l;let a=Ws(s),i=a.startsWith("rgb")?(l=nl(a))!=null?l:"#000000":a,d=[1,3,5].map(m=>{let p=parseInt(i.slice(m,m+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 du(e){var f;let t=Ws(e),n=t.startsWith("rgb")?(f=nl(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,m=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:m,l:d}}function pu(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 m=p=>{let f=Math.round((p+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${m(i)}${m(d)}${m(l)}`}function ol(e){let{h:t,s:n,l:o}=du(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]=pu(t,l,d)}return a}var Gr=["50","100","200","300","400","500","600","700","800","900","950"],rl=["primary","secondary","accent","gray","success","warning","error","info"];function Dg(e,t){return`palette.colors.${e}.${t}`}function uu(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.")?uu(e,`theme.${o}`,n+1):"#cbd5e1"}function Fg(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 Ro=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Pa=["primary","secondary","accent","gray"],Og={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Wa={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:Ro,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Ba={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:Ro,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"}]},Ha={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:Ro,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Da={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:Ro,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Fa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:Ro,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"}]},Oa={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:Ro,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Na={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:Ro,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"}]},_a={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:Ro,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"}]},Va={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:Ro,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},Ar=[Wa,Ba,Ha,Da,Fa,Oa,Na,_a,Va];function $a(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ng(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 Ng(e,t,n,o){let r=t==="solid";if(o==="role-header")return _g(e,r,n);if(o==="role-input")return Vg(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 _g(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 Vg(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 $g=/^palette\.colors\.(\w+)\.(\d+)$/;function sl(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($g);if(!r)return null;let s=r[1],a=Pa.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=$a(a,l,t);if(t.targets.every(f=>{var C;return String((C=e(f.path))!=null?C:"")===m[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var Ug={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"}]}]},zg={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"}]},qg={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"}}]},jg={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)"}]}]},Kg={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"}]}]},Gg={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"}}]},Yg={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)"}]},Xg={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"}]}]},Xr=[zg,qg,Kg,jg,Ug,Gg,Yg,Xg];function gu(){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:rl.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 fu={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"}}]},Qg=gu(),Jg=fu,Zg=[gu(),fu],ef={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:go},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:La},{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"}]}]},tf={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"}]}]},nf={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"}]}]},of={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"}]}]},rf={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"}]}]},sf={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"}}]},af={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"}}]},lf={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"}}]},cf={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"}}]},df={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"}]},Yr=[{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"}],al="0 5px 15px rgba(15, 23, 42, 0.08)",mu=[{value:al,label:"Default"},...Yr],pf={id:"comp-shadows",title:"Component Shadows",description:"Box-shadow for chat bubbles and surfaces.",collapsed:!0,fields:[{id:"shadow-msg-user",label:"User Message",type:"select",path:"theme.components.message.user.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:al,options:mu},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:al,options:mu},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:Yr}]},hu=[ef,tf,nf,of,rf,pf],bu=[sf,af,lf,cf,df],yu=[...hu,...bu],il=1024*1024,uf=["What can you help me with?","Tell me about your features","How does this work?"],Bs={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 mf(e){return Number(e)*il}function gf(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/il)):String(t):"10"}function ff(e){var t;return(t=Bs[String(e)])!=null?t:Bs.images}function hf(e){let t=Array.isArray(e)?e:Bs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Bs)){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 bf={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"}]},yf={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:uf}]},vf={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:""}]},xf={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}]},wf={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"}]}]},Cf={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"}]}]},Sf={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:go},{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"}]},Af={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:""}]},Tf={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"}]},kf={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"}]},Ef={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"}]},Mf={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"}]},Lf={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:""}]},If={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)}]},Rf={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*il,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:gf,parseValue:mf},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Bs.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:hf,parseValue:ff}]},Pf={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"}]}]},Wf={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}]},Bf={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"}]}]},Hf={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}]},Df={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}]},Ua=[{label:"Content",sections:[bf,yf]},{label:"Layout",sections:[vf,xf,wf,Cf]},{label:"Widget",sections:[Sf,Af,Tf,kf,Ef,Mf]},{label:"Features",sections:[Lf,If,Rf,Pf,Wf]},{label:"Developer",collapsedByDefault:!0,sections:[Bf,Hf,Df]}],vu=Ua.flatMap(e=>e.sections),xu={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"}]}]},wu={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"}]},Cu={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"}]},Su={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:Wa},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Ba},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ha},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Da},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Fa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Oa},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Na},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:_a},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Va}]},Au={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"}}]},Tu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Ff=[xu,wu,Cu,Su,Au,Tu],ll=[{id:"style",label:"Style",sections:Xr},{id:"design-system",label:"Design System",sections:yu},{id:"configure",label:"Configure",sections:vu}];function ku(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Of(e,t,n){return{...e,id:`${n}-${e.id}`,path:ku(e.path,t)}}function Nf(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function _f(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=>Of(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])=>[ku(d,t),l]))}))}}var Eu=[{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"]}],Hs=[...Eu];function cl(e){return Hs.find(t=>t.id===e)}import{Marked as Vf}from"marked";var $f=e=>{if(e)return e},dl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Vf({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=$f(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},za=e=>e?dl({markedOptions:e.options,renderer:e.renderer}):dl(),gw=dl();var Ds=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");import Uf from"dompurify";var zf={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"]},qf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,jf=()=>{let e=Uf(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:")&&!qf.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,zf)},qa=e=>e===!1?null:typeof e=="function"?e:jf();var Tr="webmcp:",pl=new Map,Mu=e=>{var t;pl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&pl.set(n.name,o)}},ul=e=>pl.get(Ru(e)),ja={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Iu(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}:${Kf(t.join(""))}`}function Lu(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 Kf(e){let t=Lu(e,0).toString(36),n=Lu(e,2654435761).toString(36);return`${t}.${n}`}var Ka=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 ja.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}Mu(n);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=Yf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return To("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return To(C?"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=Ru(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return To(`Failed to read WebMCP registry: ${v}`)}Mu(a);let i=a.find(C=>C.name===s);if(!i)return To(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return To(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return To("Aborted by cancel()");let d=ul(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return To("User declined the tool call.");if(o!=null&&o.aborted)return To("Aborted by cancel()");let m=new AbortController,p=!1,f=setTimeout(()=>{p=!0,m.abort()},this.timeoutMs),u=()=>m.abort();o&&(o.aborted?m.abort():o.addEventListener("abort",u,{once:!0}));try{let C=await r.executeTool(i,Zf(n),{signal:m.signal});return Xf(C)}catch(C){if(p)return To(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return To("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return To(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",u)}}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){ja.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,ja.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:Qf;try{return await n(t)}catch(r){return ja.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=>Gf(t,o))}},Ru=e=>e.startsWith(Tr)?e.slice(Tr.length):e,Qr=e=>e.startsWith(Tr),Gf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Yf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Xf=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:eh(t)}]}},To=e=>({isError:!0,content:[{type:"text",text:e}]}),Qf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Jf(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
4
|
${t}`:"")+(e.description?`
|
|
5
5
|
|
|
6
|
-
${e.description}`:"");return window.confirm(n)},
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
6
|
+
${e.description}`:"");return window.confirm(n)},Jf=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)}},Zf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},eh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as th,STR as nh,OBJ as oh}from"partial-json";var Pu=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Jr=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)}},rh=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`},Wu=e=>e.status==="complete"?rh(e):e.status==="pending"?"Waiting":"",sh=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 Bu=e=>e.status==="complete"?sh(e):"Using tool...",Ga=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Os=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 Ga(t)},Ya=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 Ga(t)},ml=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Os(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Xa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Fs(o,n.slice(s,a.index),[]),a[1]!==void 0?Fs(o,a[1],["bold"]):a[2]!==void 0?Fs(o,a[2],["italic"]):a[3]!==void 0&&Fs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Fs(o,n.slice(s),[]),o},Fs=(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})},ah=()=>{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()=>{}}},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},ku=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Eu=()=>{var t;let e=Kg();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)}},Mu=()=>{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=$g(n,Ug|zg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Su(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Su(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Lu=()=>{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 Ya=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 Gg="https://api.runtype.com/v1/dispatch",Xa="https://api.runtype.com";function Yg(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 ll=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 Xg(e){switch(e){case"json":return Mu;case"regex-json":return Eu;case"xml":return Lu;default:return ku}}var Iu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Qg(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=Iu(n);if(!Iu(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 Ws=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:Gg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Xg(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 qa(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$/,""))||Xa}/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$/,""))||Xa}/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),m=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(ll).map(D=>{var W,v,x;return{id:D.id,role:D.role,content:(x=(v=(W=D.contentParts)!=null?W:D.llmContent)!=null?v:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,p=!!(g&&g.length>0),w=p?Cu(g):void 0,S=this.clientToolsFingerprintSessionId===d.sessionId,M=p&&S&&this.lastSentClientToolsFingerprint===w,I=!1,L=null,H;for(let D=0;;D++){let v={...u,...p&&(I||!M)&&g?{clientTools:g}:{},...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&&p){let x=await H.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}L=x!=null?x:{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 W=new Error(D.error||"Failed to send message");throw n({type:"error",error:W}),W}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$/,""))||Xa}/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,m;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Xa}/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:(m=o==null?void 0:o.streamResponse)!=null?m:!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(ll).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(ll).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=m=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return o.current=u,r(u),u},l=m=>o.current?o.current:d(m);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 m=l(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,r(m)}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,qe;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,De=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,Fe=_.tools?_.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:De,tools:Fe}},u=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,De=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||De||!!_.stopReason},g=_=>{u(_)&&n({type:"message",message:m(_)})},p=null,w=null,S={current:null},M={current:null},I=!1,L=new Map,H=new Map,D=new Map,W=new Map,v={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(_,ke,De="")=>`${_}::${ke}::${De}`,C=(_,ke)=>`${_}::${ke}::`,T=(_,ke,De,Fe)=>{let $e=k(_,ke,De),dt=D.get($e);if(dt)return dt;let ot=De?`-${De}`:"",At={id:`nested-${_}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Fe,parentToolId:_,parentStepId:ke}};return D.set($e,At),g(At),At},F=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var ke,De,Fe,$e,dt;return F((dt=($e=(Fe=(De=(ke=_.stepId)!=null?ke:_.step_id)!=null?De:_.step)!=null?Fe:_.parentId)!=null?$e:_.flowStepId)!=null?dt:_.flow_step_id)},j=_=>{var ke,De,Fe,$e,dt,ot,At;return F((At=(ot=(dt=($e=(Fe=(De=(ke=_.callId)!=null?ke:_.call_id)!=null?De:_.requestId)!=null?Fe:_.request_id)!=null?$e:_.toolCallId)!=null?dt:_.tool_call_id)!=null?ot:_.stepId)!=null?At:_.step_id)},me=o,se=!1,fe=()=>{if(p)return p;let _;return!se&&me?(_=me,se=!0):me&&M.current?_=`${me}_${M.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,p={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(p),p},ie=(_,ke)=>{v.lastId=ke,_&&v.byStep.set(_,ke)},be=(_,ke)=>{var dt;let De=(dt=_.reasoningId)!=null?dt:_.id,Fe=$(_);if(De){let ot=String(De);return ie(Fe,ot),ot}if(Fe){let ot=v.byStep.get(Fe);if(ot)return v.lastId=ot,ot}if(v.lastId&&!ke)return v.lastId;if(!ke)return null;let $e=`reason-${l()}`;return ie(Fe,$e),$e},Oe=_=>{let ke=L.get(_);if(ke)return ke;let De={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return L.set(_,De),g(De),De},ve=(_,ke)=>{x.lastId=ke,_&&x.byCall.set(_,ke)},Q=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 De=(dt=_.toolId)!=null?dt:_.id,Fe=j(_);if(De){let ot=String(De);return ve(Fe,ot),ot}if(Fe){let ot=x.byCall.get(Fe);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ke)return x.lastId;if(!ke)return null;let $e=`tool-${l()}`;return ve(Fe,$e),$e},we=_=>{let ke=H.get(_);if(ke)return ke;let De={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return H.set(_,De),g(De),De},ze=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let De=Date.parse(_);if(!Number.isNaN(De))return De}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,Ue=(_,ke,De)=>{var At;let Fe=nt.get(_);Fe||(Fe=[],nt.set(_,Fe));let $e=0,dt=Fe.length;for(;$e<dt;){let Vt=$e+dt>>>1;Fe[Vt].seq<ke?$e=Vt+1:dt=Vt}((At=Fe[$e])==null?void 0:At.seq)===ke?Fe[$e]={seq:ke,text:De}:Fe.splice($e,0,{seq:ke,text:De});let ot="";for(let Vt=0;Vt<Fe.length;Vt++)ot+=Fe[Vt].text;return ot},He=(_,ke)=>{let De=te(ke),Fe=re.get(_.id),$e=Qg(Fe,De);_.rawContent=$e;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,g(_)};if(!dt){ot(De),At();return}let Vt=Cr($e);if(Vt!==null&&Vt.trim()!==""){ot(Vt),At();return}let q=Qe=>{var ge;let Ft=typeof Qe=="string"?Qe:(ge=Qe==null?void 0:Qe.text)!=null?ge:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let oe=dt.getExtractedText();return oe!==null&&oe.trim()!==""?oe:De},_t;try{_t=dt.processChunk($e)}catch{ot(De),At();return}if(_t instanceof Promise){_t.then(Qe=>{ot(q(Qe)),At()}).catch(()=>{ot(De),At()});return}ot(q(_t)),At()},ce=[],G=!1,Ve,Et=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,Ve()}))},pe=new Ya((_,ke)=>{ce.push({payloadType:_,payload:ke}),Et()}),ae=null,Ln=new Map,Nt=(ln=this.config.iterationDisplay)!=null?ln:"separate";for(Ve=()=>{var _,ke,De,Fe,$e,dt,ot,At,Vt,q,_t,Qe,Ft,oe,ge,xt,$t,Jt,yn,Tt,wt,gt,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,ft,Kt,Gt,qn,Ko,oo,uo,jn,E,Kn,mo,Po,So,as,fo,go,ho,Wo,lr,aa,is,ia,Pr,mt,ls,ro,Rn,la,ca,Wr,Bo,da,cr,cs,Ho,ds,Go,Yo,pa,ua,zi,dr,Xo,ma,ps,Qo,fa,us,Jo,ms,ga,Do,ha,Zo,Bt,Br,Hr,fs,Ao,ba,gs,hs,ya,Dr,Fr,pr,va,xa,bs,ys,vs,xs,Cn,Gn,Fo,rt,ws,ur,bo,wa;for(let er=0;er<ce.length;er++){let Ke=ce[er].payloadType,A=ce[er].payload;if(Ke==="reason_start"){let U=(_=be(A,!0))!=null?_:`reason-${l()}`,B=Oe(U);B.reasoning=(ke=B.reasoning)!=null?ke:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Fe=B.reasoning.startedAt)!=null?Fe:ze((De=A.startedAt)!=null?De:A.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",g(B)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let U=(dt=($e=be(A,!1))!=null?$e:be(A,!0))!=null?dt:`reason-${l()}`,B=Oe(U);B.reasoning=(ot=B.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Vt=B.reasoning.startedAt)!=null?Vt:ze((At=A.startedAt)!=null?At:A.timestamp);let J=(Qe=(_t=(q=A.reasoningText)!=null?q:A.text)!=null?_t:A.delta)!=null?Qe:"";if(J&&A.hidden!==!0){let ee=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ee!==void 0){let K=Ue(U,ee,String(J));B.reasoning.chunks=[K]}else B.reasoning.chunks.push(String(J))}if(B.reasoning.status=A.done?"complete":"streaming",A.done){B.reasoning.completedAt=ze((Ft=A.completedAt)!=null?Ft:A.timestamp);let ee=(oe=B.reasoning.startedAt)!=null?oe:Date.now();B.reasoning.durationMs=Math.max(0,((ge=B.reasoning.completedAt)!=null?ge:Date.now())-ee)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(Ke==="reason_complete"){let U=($t=(xt=be(A,!1))!=null?xt:be(A,!0))!=null?$t:`reason-${l()}`,B=L.get(U);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=ze((Jt=A.completedAt)!=null?Jt:A.timestamp);let ee=(yn=B.reasoning.startedAt)!=null?yn:Date.now();B.reasoning.durationMs=Math.max(0,((Tt=B.reasoning.completedAt)!=null?Tt:Date.now())-ee),B.streaming=!1,g(B)}let J=$(A);J&&v.byStep.delete(J)}else if(Ke==="tool_start"){let U=(wt=de(A,!0))!=null?wt:`tool-${l()}`,B=(gt=A.toolName)!=null?gt:A.name;if(Se(B)){Q.add(U);continue}let J=we(U),ee=(bt=J.toolCall)!=null?bt:{id:U,status:"pending"};ee.name=B!=null?B:ee.name,ee.status="running",A.args!==void 0?ee.args=A.args:A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=(et=ee.startedAt)!=null?et:ze((zt=A.startedAt)!=null?zt:A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,J.toolCall=ee,J.streaming=!0;let K=A.agentContext;(K||A.executionId)&&(J.agentMetadata={executionId:(Fn=K==null?void 0:K.executionId)!=null?Fn:A.executionId,iteration:(Zn=K==null?void 0:K.iteration)!=null?Zn:A.iteration}),g(J)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let U=(On=(vn=de(A,!1))!=null?vn:de(A,!0))!=null?On:`tool-${l()}`;if(Q.has(U))continue;let B=we(U),J=(ut=B.toolCall)!=null?ut:{id:U,status:"running"};J.startedAt=(Nn=J.startedAt)!=null?Nn:ze((wo=A.startedAt)!=null?wo:A.timestamp);let ee=(Rr=(In=(ir=A.text)!=null?ir:A.delta)!=null?In:A.message)!=null?Rr:"";ee&&(J.chunks=($o=J.chunks)!=null?$o:[],J.chunks.push(String(ee))),J.status="running",B.toolCall=J,B.streaming=!0;let K=A.agentContext;(K||A.executionId)&&(B.agentMetadata=(_n=B.agentMetadata)!=null?_n:{executionId:(Lo=K==null?void 0:K.executionId)!=null?Lo:A.executionId,iteration:(yt=K==null?void 0:K.iteration)!=null?yt:A.iteration}),g(B)}else if(Ke==="tool_complete"){let U=(xn=(Vn=de(A,!1))!=null?Vn:de(A,!0))!=null?xn:`tool-${l()}`;if(Q.has(U)){Q.delete(U);continue}let B=we(U),J=(It=B.toolCall)!=null?It:{id:U,status:"running"};J.status="complete",A.result!==void 0&&(J.result=A.result),typeof A.duration=="number"&&(J.duration=A.duration),J.completedAt=ze((eo=A.completedAt)!=null?eo:A.timestamp);let ee=(to=A.duration)!=null?to:A.executionTime;if(typeof ee=="number")J.durationMs=ee;else{let _e=($n=J.startedAt)!=null?$n:Date.now();J.durationMs=Math.max(0,((Uo=J.completedAt)!=null?Uo:Date.now())-_e)}B.toolCall=J,B.streaming=!1;let K=A.agentContext;(K||A.executionId)&&(B.agentMetadata=(Un=B.agentMetadata)!=null?Un:{executionId:(Io=K==null?void 0:K.executionId)!=null?Io:A.executionId,iteration:(zo=K==null?void 0:K.iteration)!=null?zo:A.iteration}),g(B);let We=j(A);We&&x.byCall.delete(We)}else if(Ke==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,B=(Wt=U!=null?U:A.toolId)!=null?Wt:`local-${l()}`,J=we(B),ee=A.toolName,K=qr(ee),We=(wn=J.toolCall)!=null?wn:{id:B,status:"pending"};We.name=ee,We.args=A.parameters,We.status=K?"running":"complete",We.chunks=(no=We.chunks)!=null?no:[],We.startedAt=(Ro=We.startedAt)!=null?Ro:ze((qo=A.startedAt)!=null?qo:A.timestamp),K?(We.completedAt=void 0,We.duration=void 0,We.durationMs=void 0):We.completedAt=(jo=We.completedAt)!=null?jo:We.startedAt,J.toolCall=We,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(zn=A.executionId)!=null?zn:(Co=J.agentMetadata)==null?void 0:Co.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(J)}else if(Ke==="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 B=p;B&&(B.streaming=!1,g(B),le=B,p=null,I=!0)}U!==void 0&&(M.current=U)}else if(Ke==="text_end"){if((ft=A.toolContext)!=null&&ft.toolId)continue;let U=p;U&&(U.streaming=!1,g(U),le=U,p=null,I=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let U=A.stepType,B=A.executionType;if(U==="tool"||B==="context")continue;let J=A.toolContext;if(J!=null&&J.toolId){let _e=String((Gt=(Kt=A.id)!=null?Kt:J.stepId)!=null?Gt:`step-${l()}`),Ze=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ie=`${J.toolId}::${_e}`,Ye=W.get(Ie);if(Ze!==""&&Ye!==void 0&&Ye!==""&&Ye!==Ze){let Ct=D.get(k(J.toolId,_e,Ye));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,g(Ct))}Ze!==""&&W.set(Ie,Ze);let Rt=T(J.toolId,_e,Ze,J.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,g(Rt)),A.isComplete&&(Rt.streaming=!1,g(Rt));continue}let ee=A.partId;if(ee!==void 0&&M.current!==null&&ee!==M.current){let _e=p;_e&&(_e.streaming=!1,g(_e),le=_e,p=null,I=!0)}ee!==void 0&&(M.current=ee);let K=ee!==void 0&&(jn=ye.get(ee))!=null?jn:fe();ee!==void 0&&(K.partId||(K.partId=ee),ye.set(ee,K));let We=(Po=(mo=(Kn=(E=A.text)!=null?E:A.delta)!=null?Kn:A.content)!=null?mo:A.chunk)!=null?Po:"";if(We){let _e=typeof A.seq=="number"?A.seq:void 0,Ze=ee!=null?ee:K.id,Ie=_e!==void 0?Ue(Ze,_e,String(We)):((So=re.get(K.id))!=null?So:"")+We;K.rawContent=Ie,ne.has(K.id)||ne.set(K.id,this.createStreamParser());let Ye=ne.get(K.id),Rt=Ie.trim().startsWith("{")||Ie.trim().startsWith("[");if(Rt&&re.set(K.id,Ie),Ye.__isPlainTextParser===!0){K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K);continue}let Ct=Ye.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()!=="")K.content=on,g(K);else if(!Rt&&!Ie.trim().startsWith("<")){let Sn=p,Yt=Sn&&Sn.id===K.id?Sn:K;Yt.id===K.id&&(Yt.content=_e!==void 0?Ie:Yt.content+We,re.delete(Yt.id),ne.delete(Yt.id),Yt.rawContent=void 0,g(Yt))}}).catch(()=>{K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K)});else{let Mt=typeof Ct=="string"?Ct:(as=Ct==null?void 0:Ct.text)!=null?as:null;Mt!==null&&Mt.trim()!==""?(K.content=Mt,g(K)):!Rt&&!Ie.trim().startsWith("<")&&(K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K))}}if(A.isComplete){let _e=(go=(fo=A.result)==null?void 0:fo.response)!=null?go:K.content;if(_e){let Ze=re.get(K.id),Ie=Ze!=null?Ze:te(_e);K.rawContent=Ie;let Ye=ne.get(K.id),Rt=null,nn=!1;if(Ye&&(Rt=Ye.getExtractedText(),Rt===null&&(Rt=Cr(Ie)),Rt===null)){let Ct=Ye.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=p;Sn&&Sn.id===K.id&&(Sn.content=on,Sn.streaming=!1,ne.delete(Sn.id),re.delete(Sn.id),g(Sn))}})):Rt=typeof Ct=="string"?Ct:(ho=Ct==null?void 0:Ct.text)!=null?ho:null}if(!nn){Rt!==null&&Rt.trim()!==""?K.content=Rt:re.has(K.id)||(K.content=te(_e));let Ct=ne.get(K.id);if(Ct){let Mt=(Wo=Ct.close)==null?void 0:Wo.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),ne.delete(K.id)}re.delete(K.id),K.streaming=!1,g(K)}}}}else if(Ke==="step_complete"){let U=A.stepType,B=A.executionType;if(U==="tool"||B==="context")continue;let J=A.toolContext;if(J!=null&&J.toolId){let _e=String((aa=(lr=A.id)!=null?lr:J.stepId)!=null?aa:"");if(_e){let Ze=C(J.toolId,_e);for(let[Ie,Ye]of D)Ie.startsWith(Ze)&&Ye.streaming!==!1&&(Ye.streaming=!1,g(Ye));W.delete(`${J.toolId}::${_e}`)}continue}let ee=A.stopReason;if(I){if(p!==null){let Ie=p;ee&&(Ie.stopReason=ee),ne.delete(Ie.id),re.delete(Ie.id),Ie.streaming!==!1&&(Ie.streaming=!1,g(Ie))}let _e=(is=A.result)==null?void 0:is.response,Ze=le;Ze&&(ee&&(Ze.stopReason=ee),_e!=null?He(Ze,_e):(ne.delete(Ze.id),re.delete(Ze.id))),le=null;continue}let K=(ia=A.result)==null?void 0:ia.response,We=fe();if(ee&&(We.stopReason=ee),K!=null){let _e=ne.get(We.id),Ze=!1,Ie=!1;if(_e){let Ye=_e.getExtractedText(),Rt=re.get(We.id),nn=Rt!=null?Rt:te(K);if(We.rawContent=nn,Ye!==null&&Ye.trim()!=="")We.content=Ye,Ze=!0;else{let Ct=Cr(nn);if(Ct!==null)We.content=Ct,Ze=!0;else{let Mt=_e.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=p;Yt&&Yt.id===We.id&&(Yt.content=un,Yt.streaming=!1,ne.delete(Yt.id),re.delete(Yt.id),g(Yt))}else{let Yt=_e.getExtractedText(),so=p;so&&so.id===We.id&&(Yt!==null&&Yt.trim()!==""?so.content=Yt:re.has(so.id)||(so.content=te(K)),so.streaming=!1,ne.delete(so.id),re.delete(so.id),g(so))}});else{let on=typeof Mt=="string"?Mt:(Pr=Mt==null?void 0:Mt.text)!=null?Pr:null;if(on!==null&&on.trim()!=="")We.content=on,Ze=!0;else{let un=_e.getExtractedText();un!==null&&un.trim()!==""&&(We.content=un,Ze=!0)}}}}}if(!Ie){if(!We.rawContent){let Ye=re.get(We.id);We.rawContent=Ye!=null?Ye:te(K)}if(!Ze&&!re.has(We.id)&&(We.content=te(K)),_e){let Ye=(mt=_e.close)==null?void 0:mt.call(_e);Ye instanceof Promise&&Ye.catch(()=>{})}ne.delete(We.id),re.delete(We.id),We.streaming=!1,g(We)}}else ne.delete(We.id),re.delete(We.id),We.streaming=!1,g(We)}else if(Ke==="flow_complete"){let U=(ls=A.result)==null?void 0:ls.response;if(I){if(p!==null){let B=p;ne.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}}else if(U!=null){let B=fe(),J=re.get(B.id),ee=J!=null?J:te(U);B.rawContent=ee;let K=te(U),We=ne.get(B.id);if(We){let Ie=Cr(ee);if(Ie!==null)K=Ie;else{let Ye=We.processChunk(ee);Ye instanceof Promise&&Ye.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(B.content=Ct,B.streaming=!1,g(B))});let Rt=We.getExtractedText();Rt!==null&&(K=Rt)}}ne.delete(B.id),re.delete(B.id);let _e=K!==B.content,Ze=B.streaming!==!1;_e&&(B.content=K),B.streaming=!1,(_e||Ze)&&g(B)}else if(p!==null){let B=p;ne.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")ae={executionId:A.executionId,agentId:(ro=A.agentId)!=null?ro:"virtual",agentName:(Rn=A.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(la=A.maxTurns)!=null?la:1,startedAt:ze(A.startedAt)};else if(Ke==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Nt==="separate"&&A.iteration>1){let U=p;U&&(U.streaming=!1,g(U),Ln.set(A.iteration-1,U),p=null)}}else if(Ke==="agent_turn_start")w=null;else if(Ke==="agent_turn_delta"){if(A.contentType==="text"){let U=fe();U.content+=(ca=A.delta)!=null?ca:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},w=U,g(U)}else if(A.contentType==="thinking"){let U=(Wr=A.turnId)!=null?Wr:`agent-think-${A.iteration}`,B=Oe(U);B.reasoning=(Bo=B.reasoning)!=null?Bo:{id:U,status:"streaming",chunks:[]},B.reasoning.chunks.push((da=A.delta)!=null?da:""),B.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(B)}else if(A.contentType==="tool_input"){let U=(cr=A.toolCallId)!=null?cr:x.lastId;if(U){let B=H.get(U);B!=null&&B.toolCall&&(B.toolCall.chunks=(cs=B.toolCall.chunks)!=null?cs:[],B.toolCall.chunks.push((Ho=A.delta)!=null?Ho:""),g(B))}}}else if(Ke==="agent_turn_complete"){let U=A.turnId;if(U){let ee=L.get(U);if(ee!=null&&ee.reasoning){ee.reasoning.status="complete",ee.reasoning.completedAt=ze(A.completedAt);let K=(ds=ee.reasoning.startedAt)!=null?ds:Date.now();ee.reasoning.durationMs=Math.max(0,((Go=ee.reasoning.completedAt)!=null?Go:Date.now())-K),ee.streaming=!1,g(ee)}}let B=A.stopReason,J=p!=null?p:w;if(B&&J!==null){let ee=A.turnId;(!ee||((Yo=J.agentMetadata)==null?void 0:Yo.turnId)===ee)&&(J.stopReason=B,g(J))}}else if(Ke==="agent_tool_start"){p&&(p.streaming=!1,g(p),p=null);let U=(pa=A.toolCallId)!=null?pa:`agent-tool-${l()}`;ve(j(A),U);let B=we(U),J=(ua=B.toolCall)!=null?ua:{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};J.name=(dr=(zi=A.toolName)!=null?zi:A.name)!=null?dr:J.name,J.status="running",A.parameters!==void 0&&(J.args=A.parameters),J.startedAt=ze((Xo=A.startedAt)!=null?Xo:A.timestamp),B.toolCall=J,B.streaming=!0,B.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(B)}else if(Ke==="agent_tool_delta"){let U=(ma=A.toolCallId)!=null?ma:x.lastId;if(U){let B=(ps=H.get(U))!=null?ps:we(U);B.toolCall&&(B.toolCall.chunks=(Qo=B.toolCall.chunks)!=null?Qo:[],B.toolCall.chunks.push((fa=A.delta)!=null?fa:""),B.toolCall.status="running",B.streaming=!0,g(B))}}else if(Ke==="agent_tool_complete"){let U=(us=A.toolCallId)!=null?us:x.lastId;if(U){let B=(Jo=H.get(U))!=null?Jo:we(U);if(B.toolCall){B.toolCall.status="complete",A.result!==void 0&&(B.toolCall.result=A.result),typeof A.executionTime=="number"&&(B.toolCall.durationMs=A.executionTime),B.toolCall.completedAt=ze((ms=A.completedAt)!=null?ms:A.timestamp),B.streaming=!1,g(B);let J=j(A);J&&x.byCall.delete(J)}}}else if(Ke==="agent_media"){let U=Array.isArray(A.media)?A.media:[],B=[];for(let J of U){if(!J||typeof J!="object")continue;let ee=J,K=typeof ee.type=="string"?ee.type:void 0,We=typeof ee.mediaType=="string"?ee.mediaType.toLowerCase():"",_e=null,Ze="";if(K==="media"){let Ie=typeof ee.data=="string"?ee.data:void 0;if(!Ie)continue;Ze=We.length>0?We:"application/octet-stream",_e=`data:${Ze};base64,${Ie}`}else if(K==="image-url"){let Ie=typeof ee.url=="string"?ee.url:void 0;if(!Ie)continue;Ze=We,_e=Ie}else if(K==="file-url"){let Ie=typeof ee.url=="string"?ee.url:void 0;if(!Ie)continue;Ze=We,_e=Ie}else continue;if(_e)if(K==="image-url"||Ze.startsWith("image/"))B.push({type:"image",image:_e,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))B.push({type:"audio",audio:_e,mimeType:Ze});else if(Ze.startsWith("video/"))B.push({type:"video",video:_e,mimeType:Ze});else{let Ie=Ze||"application/octet-stream";B.push({type:"file",data:_e,mimeType:Ie,filename:Yg(Ie)})}}if(B.length>0){let J=l(),ee=A.toolCallId,We={id:`agent-media-${typeof ee=="string"&&ee.length>0?`${ee}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(We);let _e=p;_e&&(_e.streaming=!1,g(_e)),p=null,S.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,B={id:U,role:"assistant",content:(ga=A.reflection)!=null?ga:"",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}};g(B)}else if(Ke==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=ze(A.completedAt),ae.stopReason=A.stopReason);let U=p;U&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let U=typeof A.error=="string"?A.error:(Zo=(ha=A.error)==null?void 0:ha.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(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let U=(Bt=A.approvalId)!=null?Bt:`approval-${l()}`,B={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:(fs=(Hr=A.executionId)!=null?Hr:ae==null?void 0:ae.executionId)!=null?fs:"",toolName:(Ao=A.toolName)!=null?Ao:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(ba=A.toolName)!=null?ba:"tool"}`,parameters:A.parameters}};g(B)}else if(Ke==="step_await"&&A.awaitReason==="approval_required"){let U=(hs=A.approvalId)!=null?hs:`approval-${l()}`,B={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ya=ae==null?void 0:ae.agentId)!=null?ya:"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:(xa=A.description)!=null?xa:`Execute ${(va=A.toolName)!=null?va:"tool"}`,parameters:A.parameters}};g(B)}else if(Ke==="agent_approval_complete"){let U=A.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(bs=A.decision)!=null?bs:"approved",agentId:(ys=ae==null?void 0:ae.agentId)!=null?ys:"virtual",executionId:(xs=(vs=A.executionId)!=null?vs:ae==null?void 0:ae.executionId)!=null?xs:"",toolName:(Cn=A.toolName)!=null?Cn:"",description:(Gn=A.description)!=null?Gn:"",resolvedAt:Date.now()}};g(J)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let U=A.artifactType,B=String(A.id),J=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:B,artifactType:U,title:J,component:typeof A.component=="string"?A.component:void 0}),xe.set(B,{markdown:"",title:J}),!Y.has(B)){Y.add(B);let ee={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:J,artifactType:U,status:"streaming"}})};Le.set(B,ee),g(ee)}}else if(Ke==="artifact_delta"){let U=String(A.id),B=typeof A.delta=="string"?A.delta:String((Fo=A.delta)!=null?Fo:"");n({type:"artifact_delta",id:U,artDelta:B});let J=xe.get(U);J&&(J.markdown+=B)}else if(Ke==="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(Ke==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let B=Le.get(U);if(B){B.streaming=!1;try{let J=JSON.parse((rt=B.rawContent)!=null?rt:"{}");if(J.props){J.props.status="complete";let ee=xe.get(U);ee!=null&&ee.markdown&&(J.props.markdown=ee.markdown)}B.rawContent=JSON.stringify(J)}catch{}xe.delete(U),g(B),Le.delete(U)}}}else if(Ke==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let B=String((ws=U.id)!=null?ws:`msg-${l()}`),J=U.role,K={id:B,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(g(K),K.rawContent)try{let We=JSON.parse(K.rawContent),_e=(ur=We==null?void 0:We.props)==null?void 0:ur.artifactId;typeof _e=="string"&&Y.add(_e)}catch{}p=null,S.current=null,ne.delete(B),re.delete(B)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(Ke==="dispatch_error"){let B=(bo=A.message)!=null?bo:A.error;B!=null&&B!==""&&(U=new Error(String(B)))}else if(Ke==="step_error"||Ke==="flow_error"){let B=A.error;typeof B=="string"&&B!==""?U=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(U=new Error(String((wa=B.message)!=null?wa:B)))}else Ke==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let B=p;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:_,value:ke}=await r.read();if(_)break;a+=s.decode(ke,{stream:!0});let De=a.split(`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},kr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Hu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Du=()=>{var t;let e=ah();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)}},Fu=()=>{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=th(n,nh|oh);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Pu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Pu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Ou=()=>{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 Qa=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 ih="https://api.runtype.com/v1/dispatch",Ja="https://api.runtype.com";function lh(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 gl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ch(e){switch(e){case"json":return Fu;case"regex-json":return Du;case"xml":return Ou;default:return Hu}}var Nu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dh(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=Nu(n);if(!Nu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=kr(e);return kr(t)!==null&&a===null?t:e}var Ns=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:ih,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:ch(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 Ka(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$/,""))||Ja}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let 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$/,""))||Ja}/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 H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),m=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(gl).map(H=>{var W,x,w;return{id:H.id,role:H.role,content:(w=(x=(W=H.contentParts)!=null?W:H.llmContent)!=null?x:H.rawContent)!=null?w:H.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,u=!!(f&&f.length>0),C=u?Iu(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=u&&v&&this.lastSentClientToolsFingerprint===C,L=!1,I=null,P;for(let H=0;;H++){let x={...p,...u&&(L||!E)&&f?{clientTools:f}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",x),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),signal:o.signal}),P.status===409&&H===0&&u){let w=await P.json().catch(()=>null);if((w==null?void 0:w.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=w!=null?w:{error:"Chat request failed"}}break}if(!P.ok){let H=I!=null?I:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:x}),x}if(P.status===429){let x=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let W=new Error(H.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!P.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=C!=null?C:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.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$/,""))||Ja}/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,m;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ja}/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:(m=o==null?void 0:o.streamResponse)!=null?m:!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(gl).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),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(gl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},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=m=>{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(),...m!==void 0&&{partId:m}};return o.current=p,r(p),p},l=m=>o.current?o.current:d(m);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 m=l(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,r(m)}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 mn,Dn,eo,ze;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=_=>{let Me=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,Be=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,He=_.tools?_.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{..._,reasoning:Me,toolCall:Be,tools:He}},p=_=>{if(_.role!=="assistant"||_.variant)return!0;let Me=Array.isArray(_.contentParts)&&_.contentParts.length>0,Be=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||Me||Be||!!_.stopReason},f=_=>{p(_)&&n({type:"message",message:m(_)})},u=null,C=null,v={current:null},E={current:null},L=!1,I=new Map,P=new Map,H=new Map,W=new Map,x={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},k=(_,Me,Be="")=>`${_}::${Me}::${Be}`,S=(_,Me)=>`${_}::${Me}::`,A=(_,Me,Be,He)=>{let _e=k(_,Me,Be),ut=H.get(_e);if(ut)return ut;let st=Be?`-${Be}`:"",Rt={id:`nested-${_}-${Me}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:He,parentToolId:_,parentStepId:Me}};return H.set(_e,Rt),f(Rt),Rt},N=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var Me,Be,He,_e,ut;return N((ut=(_e=(He=(Be=(Me=_.stepId)!=null?Me:_.step_id)!=null?Be:_.step)!=null?He:_.parentId)!=null?_e:_.flowStepId)!=null?ut:_.flow_step_id)},G=_=>{var Me,Be,He,_e,ut,st,Rt;return N((Rt=(st=(ut=(_e=(He=(Be=(Me=_.callId)!=null?Me:_.call_id)!=null?Be:_.requestId)!=null?He:_.request_id)!=null?_e:_.toolCallId)!=null?ut:_.tool_call_id)!=null?st:_.stepId)!=null?Rt:_.step_id)},fe=o,ge=!1,se=()=>{if(u)return u;let _;return!ge&&fe?(_=fe,ge=!0):fe&&E.current?_=`${fe}_${E.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},ke=(_,Me)=>{x.lastId=Me,_&&x.byStep.set(_,Me)},be=(_,Me)=>{var ut;let Be=(ut=_.reasoningId)!=null?ut:_.id,He=$(_);if(Be){let st=String(Be);return ke(He,st),st}if(He){let st=x.byStep.get(He);if(st)return x.lastId=st,st}if(x.lastId&&!Me)return x.lastId;if(!Me)return null;let _e=`reason-${l()}`;return ke(He,_e),_e},Fe=_=>{let Me=I.get(_);if(Me)return Me;let Be={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return I.set(_,Be),f(Be),Be},xe=(_,Me)=>{w.lastId=Me,_&&w.byCall.set(_,Me)},j=new Set,de=new Map,K=new Set,ye=new Map,le=_=>{if(!_)return!1;let Me=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return Me==="emit_artifact_markdown"||Me==="emit_artifact_component"},te=(_,Me)=>{var ut;let Be=(ut=_.toolId)!=null?ut:_.id,He=G(_);if(Be){let st=String(Be);return xe(He,st),st}if(He){let st=w.byCall.get(He);if(st)return w.lastId=st,st}if(w.lastId&&!Me)return w.lastId;if(!Me)return null;let _e=`tool-${l()}`;return xe(He,_e),_e},Ce=_=>{let Me=P.get(_);if(Me)return Me;let Be={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return P.set(_,Be),f(Be),Be},Ue=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let Me=Number(_);if(!Number.isNaN(Me)&&Number.isFinite(Me))return Me;let Be=Date.parse(_);if(!Number.isNaN(Be))return Be}return Date.now()},ee=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},oe=new Map,ae=new Map,rt=new Map,Ae=new Map,pe=null,$e=(_,Me,Be)=>{var Rt;let He=rt.get(_);He||(He=[],rt.set(_,He));let _e=0,ut=He.length;for(;_e<ut;){let qt=_e+ut>>>1;He[qt].seq<Me?_e=qt+1:ut=qt}((Rt=He[_e])==null?void 0:Rt.seq)===Me?He[_e]={seq:Me,text:Be}:He.splice(_e,0,{seq:Me,text:Be});let st="";for(let qt=0;qt<He.length;qt++)st+=He[qt].text;return st},We=(_,Me)=>{let Be=ee(Me),He=ae.get(_.id),_e=dh(He,Be);_.rawContent=_e;let ut=oe.get(_.id),st=Je=>{var re;let _t=(re=_.content)!=null?re:"";Je.trim()!==""&&(_t.trim().length===0||Je.startsWith(_t)||Je.trimStart().startsWith(_t.trim()))&&(_.content=Je)},Rt=()=>{var Je;if(ut){let _t=(Je=ut.close)==null?void 0:Je.call(ut);_t instanceof Promise&&_t.catch(()=>{})}oe.delete(_.id),ae.delete(_.id),_.streaming=!1,f(_)};if(!ut){st(Be),Rt();return}let qt=kr(_e);if(qt!==null&&qt.trim()!==""){st(qt),Rt();return}let q=Je=>{var we;let _t=typeof Je=="string"?Je:(we=Je==null?void 0:Je.text)!=null?we:null;if(_t!==null&&_t.trim()!=="")return _t;let re=ut.getExtractedText();return re!==null&&re.trim()!==""?re:Be},Ut;try{Ut=ut.processChunk(_e)}catch{st(Be),Rt();return}if(Ut instanceof Promise){Ut.then(Je=>{st(q(Je)),Rt()}).catch(()=>{st(Be),Rt()});return}st(q(Ut)),Rt()},ue=[],X=!1,Ne,Bt=()=>{X||(X=!0,queueMicrotask(()=>{X=!1,Ne()}))},he=new Qa((_,Me)=>{ue.push({payloadType:_,payload:Me}),Bt()}),ce=null,Rn=new Map,$t=(mn=this.config.iterationDisplay)!=null?mn:"separate";for(Ne=()=>{var _,Me,Be,He,_e,ut,st,Rt,qt,q,Ut,Je,_t,re,we,Tt,jt,en,Sn,Pt,Et,xt,Ct,Kt,nt,Fn,to,An,On,ht,Eo,Nn,dr,Pn,Hr,qo,Bo,St,_n,Vn,Tn,Mt,no,oo,$n,jo,Ho,Ko,Un,Dt,kn,ro,Go,Do,Yo,Mo,zn,bo,yt,Yt,Xt,qn,Xo,so,yo,jn,V,ao,ve,Kn,io,vo,us,xo,wo,Co,Fo,pr,ua,ms,ma,Dr,bt,gs,lo,Wn,ga,fa,Fr,Oo,ha,ur,fs,No,hs,Qo,Jo,ba,ya,Gi,mr,Zo,va,bs,er,xa,ys,tr,vs,wa,_o,Ca,nr,Ft,Or,Nr,xs,Lo,Sa,ws,Cs,Aa,_r,Vr,gr,Ta,ka,Ss,As,Ts,ks,En,Gn,Vo,lt,Es,fr,So;for(let $r=0;$r<ue.length;$r++){let Ge=ue[$r].payloadType,T=ue[$r].payload;if(Ge==="reason_start"){let U=(_=be(T,!0))!=null?_:`reason-${l()}`,R=Fe(U);R.reasoning=(Me=R.reasoning)!=null?Me:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(He=R.reasoning.startedAt)!=null?He:Ue((Be=T.startedAt)!=null?Be:T.timestamp),R.reasoning.completedAt=void 0,R.reasoning.durationMs=void 0,R.streaming=!0,R.reasoning.status="streaming",f(R)}else if(Ge==="reason_delta"||Ge==="reason_chunk"){let U=(ut=(_e=be(T,!1))!=null?_e:be(T,!0))!=null?ut:`reason-${l()}`,R=Fe(U);R.reasoning=(st=R.reasoning)!=null?st:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(qt=R.reasoning.startedAt)!=null?qt:Ue((Rt=T.startedAt)!=null?Rt:T.timestamp);let J=(Je=(Ut=(q=T.reasoningText)!=null?q:T.text)!=null?Ut:T.delta)!=null?Je:"";if(J&&T.hidden!==!0){let ie=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ie!==void 0){let Y=$e(U,ie,String(J));R.reasoning.chunks=[Y]}else R.reasoning.chunks.push(String(J))}if(R.reasoning.status=T.done?"complete":"streaming",T.done){R.reasoning.completedAt=Ue((_t=T.completedAt)!=null?_t:T.timestamp);let ie=(re=R.reasoning.startedAt)!=null?re:Date.now();R.reasoning.durationMs=Math.max(0,((we=R.reasoning.completedAt)!=null?we:Date.now())-ie)}R.streaming=R.reasoning.status!=="complete",f(R)}else if(Ge==="reason_complete"){let U=(jt=(Tt=be(T,!1))!=null?Tt:be(T,!0))!=null?jt:`reason-${l()}`,R=I.get(U);if(R!=null&&R.reasoning){R.reasoning.status="complete",R.reasoning.completedAt=Ue((en=T.completedAt)!=null?en:T.timestamp);let ie=(Sn=R.reasoning.startedAt)!=null?Sn:Date.now();R.reasoning.durationMs=Math.max(0,((Pt=R.reasoning.completedAt)!=null?Pt:Date.now())-ie),R.streaming=!1,f(R)}let J=$(T);J&&x.byStep.delete(J)}else if(Ge==="tool_start"){let U=(Et=te(T,!0))!=null?Et:`tool-${l()}`,R=(xt=T.toolName)!=null?xt:T.name;if(le(R)){j.add(U);continue}let J=Ce(U),ie=(Ct=J.toolCall)!=null?Ct:{id:U,status:"pending"};ie.name=R!=null?R:ie.name,ie.status="running",T.args!==void 0?ie.args=T.args:T.parameters!==void 0&&(ie.args=T.parameters),ie.startedAt=(nt=ie.startedAt)!=null?nt:Ue((Kt=T.startedAt)!=null?Kt:T.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,J.toolCall=ie,J.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(J.agentMetadata={executionId:(Fn=Y==null?void 0:Y.executionId)!=null?Fn:T.executionId,iteration:(to=Y==null?void 0:Y.iteration)!=null?to:T.iteration}),f(J)}else if(Ge==="tool_chunk"||Ge==="tool_delta"){let U=(On=(An=te(T,!1))!=null?An:te(T,!0))!=null?On:`tool-${l()}`;if(j.has(U))continue;let R=Ce(U),J=(ht=R.toolCall)!=null?ht:{id:U,status:"running"};J.startedAt=(Nn=J.startedAt)!=null?Nn:Ue((Eo=T.startedAt)!=null?Eo:T.timestamp);let ie=(Hr=(Pn=(dr=T.text)!=null?dr:T.delta)!=null?Pn:T.message)!=null?Hr:"";ie&&(J.chunks=(qo=J.chunks)!=null?qo:[],J.chunks.push(String(ie))),J.status="running",R.toolCall=J,R.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(R.agentMetadata=(_n=R.agentMetadata)!=null?_n:{executionId:(Bo=Y==null?void 0:Y.executionId)!=null?Bo:T.executionId,iteration:(St=Y==null?void 0:Y.iteration)!=null?St:T.iteration}),f(R)}else if(Ge==="tool_complete"){let U=(Tn=(Vn=te(T,!1))!=null?Vn:te(T,!0))!=null?Tn:`tool-${l()}`;if(j.has(U)){j.delete(U);continue}let R=Ce(U),J=(Mt=R.toolCall)!=null?Mt:{id:U,status:"running"};J.status="complete",T.result!==void 0&&(J.result=T.result),typeof T.duration=="number"&&(J.duration=T.duration),J.completedAt=Ue((no=T.completedAt)!=null?no:T.timestamp);let ie=(oo=T.duration)!=null?oo:T.executionTime;if(typeof ie=="number")J.durationMs=ie;else{let Oe=($n=J.startedAt)!=null?$n:Date.now();J.durationMs=Math.max(0,((jo=J.completedAt)!=null?jo:Date.now())-Oe)}R.toolCall=J,R.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(R.agentMetadata=(Un=R.agentMetadata)!=null?Un:{executionId:(Ho=Y==null?void 0:Y.executionId)!=null?Ho:T.executionId,iteration:(Ko=Y==null?void 0:Y.iteration)!=null?Ko:T.iteration}),f(R);let Ie=G(T);Ie&&w.byCall.delete(Ie)}else if(Ge==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,R=(Dt=U!=null?U:T.toolId)!=null?Dt:`local-${l()}`,J=Ce(R),ie=T.toolName,Y=Qr(ie),Ie=(kn=J.toolCall)!=null?kn:{id:R,status:"pending"};Ie.name=ie,Ie.args=T.parameters,Ie.status=Y?"running":"complete",Ie.chunks=(ro=Ie.chunks)!=null?ro:[],Ie.startedAt=(Do=Ie.startedAt)!=null?Do:Ue((Go=T.startedAt)!=null?Go:T.timestamp),Y?(Ie.completedAt=void 0,Ie.duration=void 0,Ie.durationMs=void 0):Ie.completedAt=(Yo=Ie.completedAt)!=null?Yo:Ie.startedAt,J.toolCall=Ie,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(zn=T.executionId)!=null?zn:(Mo=J.agentMetadata)==null?void 0:Mo.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(J)}else if(Ge==="text_start"){if((bo=T.toolContext)!=null&&bo.toolId)continue;let U=T.partId;if(U!==void 0&&E.current!==null&&U!==E.current){let R=u;R&&(R.streaming=!1,f(R),pe=R,u=null,L=!0)}U!==void 0&&(E.current=U)}else if(Ge==="text_end"){if((yt=T.toolContext)!=null&&yt.toolId)continue;let U=u;U&&(U.streaming=!1,f(U),pe=U,u=null,L=!0)}else if(Ge==="step_chunk"||Ge==="step_delta"){let U=T.stepType,R=T.executionType;if(U==="tool"||R==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Oe=String((Xt=(Yt=T.id)!=null?Yt:J.stepId)!=null?Xt:`step-${l()}`),ct=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Ye=`${J.toolId}::${Oe}`,Xe=W.get(Ye);if(ct!==""&&Xe!==void 0&&Xe!==""&&Xe!==ct){let Lt=H.get(k(J.toolId,Oe,Xe));Lt&&Lt.streaming!==!1&&(Lt.streaming=!1,f(Lt))}ct!==""&&W.set(Ye,ct);let Ze=A(J.toolId,Oe,ct,J.executionId),Qt=(yo=(so=(Xo=(qn=T.text)!=null?qn:T.delta)!=null?Xo:T.content)!=null?so:T.chunk)!=null?yo:"";Qt&&(Ze.content+=String(Qt),Ze.streaming=!0,f(Ze)),T.isComplete&&(Ze.streaming=!1,f(Ze));continue}let ie=T.partId;if(ie!==void 0&&E.current!==null&&ie!==E.current){let Oe=u;Oe&&(Oe.streaming=!1,f(Oe),pe=Oe,u=null,L=!0)}ie!==void 0&&(E.current=ie);let Y=ie!==void 0&&(jn=Ae.get(ie))!=null?jn:se();ie!==void 0&&(Y.partId||(Y.partId=ie),Ae.set(ie,Y));let Ie=(Kn=(ve=(ao=(V=T.text)!=null?V:T.delta)!=null?ao:T.content)!=null?ve:T.chunk)!=null?Kn:"";if(Ie){let Oe=typeof T.seq=="number"?T.seq:void 0,ct=ie!=null?ie:Y.id,Ye=Oe!==void 0?$e(ct,Oe,String(Ie)):((io=ae.get(Y.id))!=null?io:"")+Ie;Y.rawContent=Ye,oe.has(Y.id)||oe.set(Y.id,this.createStreamParser());let Xe=oe.get(Y.id),Ze=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(Ze&&ae.set(Y.id,Ye),Xe.__isPlainTextParser===!0){Y.content=Oe!==void 0?Ye:Y.content+Ie,ae.delete(Y.id),oe.delete(Y.id),Y.rawContent=void 0,f(Y);continue}let Lt=Xe.processChunk(Ye);if(Lt instanceof Promise)Lt.then(Ht=>{var bn;let an=typeof Ht=="string"?Ht:(bn=Ht==null?void 0:Ht.text)!=null?bn:null;if(an!==null&&an.trim()!=="")Y.content=an,f(Y);else if(!Ze&&!Ye.trim().startsWith("<")){let fn=u,tn=fn&&fn.id===Y.id?fn:Y;tn.id===Y.id&&(tn.content=Oe!==void 0?Ye:tn.content+Ie,ae.delete(tn.id),oe.delete(tn.id),tn.rawContent=void 0,f(tn))}}).catch(()=>{Y.content=Oe!==void 0?Ye:Y.content+Ie,ae.delete(Y.id),oe.delete(Y.id),Y.rawContent=void 0,f(Y)});else{let Ht=typeof Lt=="string"?Lt:(vo=Lt==null?void 0:Lt.text)!=null?vo:null;Ht!==null&&Ht.trim()!==""?(Y.content=Ht,f(Y)):!Ze&&!Ye.trim().startsWith("<")&&(Y.content=Oe!==void 0?Ye:Y.content+Ie,ae.delete(Y.id),oe.delete(Y.id),Y.rawContent=void 0,f(Y))}}if(T.isComplete){let Oe=(xo=(us=T.result)==null?void 0:us.response)!=null?xo:Y.content;if(Oe){let ct=ae.get(Y.id),Ye=ct!=null?ct:ee(Oe);Y.rawContent=Ye;let Xe=oe.get(Y.id),Ze=null,Qt=!1;if(Xe&&(Ze=Xe.getExtractedText(),Ze===null&&(Ze=kr(Ye)),Ze===null)){let Lt=Xe.processChunk(Ye);Lt instanceof Promise?(Qt=!0,Lt.then(Ht=>{var bn;let an=typeof Ht=="string"?Ht:(bn=Ht==null?void 0:Ht.text)!=null?bn:null;if(an!==null){let fn=u;fn&&fn.id===Y.id&&(fn.content=an,fn.streaming=!1,oe.delete(fn.id),ae.delete(fn.id),f(fn))}})):Ze=typeof Lt=="string"?Lt:(wo=Lt==null?void 0:Lt.text)!=null?wo:null}if(!Qt){Ze!==null&&Ze.trim()!==""?Y.content=Ze:ae.has(Y.id)||(Y.content=ee(Oe));let Lt=oe.get(Y.id);if(Lt){let Ht=(Co=Lt.close)==null?void 0:Co.call(Lt);Ht instanceof Promise&&Ht.catch(()=>{}),oe.delete(Y.id)}ae.delete(Y.id),Y.streaming=!1,f(Y)}}}}else if(Ge==="step_complete"){let U=T.stepType,R=T.executionType;if(U==="tool"||R==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Oe=String((pr=(Fo=T.id)!=null?Fo:J.stepId)!=null?pr:"");if(Oe){let ct=S(J.toolId,Oe);for(let[Ye,Xe]of H)Ye.startsWith(ct)&&Xe.streaming!==!1&&(Xe.streaming=!1,f(Xe));W.delete(`${J.toolId}::${Oe}`)}continue}let ie=T.stopReason;if(L){if(u!==null){let Ye=u;ie&&(Ye.stopReason=ie),oe.delete(Ye.id),ae.delete(Ye.id),Ye.streaming!==!1&&(Ye.streaming=!1,f(Ye))}let Oe=(ua=T.result)==null?void 0:ua.response,ct=pe;ct&&(ie&&(ct.stopReason=ie),Oe!=null?We(ct,Oe):(oe.delete(ct.id),ae.delete(ct.id))),pe=null;continue}let Y=(ms=T.result)==null?void 0:ms.response,Ie=se();if(ie&&(Ie.stopReason=ie),Y!=null){let Oe=oe.get(Ie.id),ct=!1,Ye=!1;if(Oe){let Xe=Oe.getExtractedText(),Ze=ae.get(Ie.id),Qt=Ze!=null?Ze:ee(Y);if(Ie.rawContent=Qt,Xe!==null&&Xe.trim()!=="")Ie.content=Xe,ct=!0;else{let Lt=kr(Qt);if(Lt!==null)Ie.content=Lt,ct=!0;else{let Ht=Oe.processChunk(Qt);if(Ht instanceof Promise)Ye=!0,Ht.then(an=>{var fn;let bn=typeof an=="string"?an:(fn=an==null?void 0:an.text)!=null?fn:null;if(bn!==null&&bn.trim()!==""){let tn=u;tn&&tn.id===Ie.id&&(tn.content=bn,tn.streaming=!1,oe.delete(tn.id),ae.delete(tn.id),f(tn))}else{let tn=Oe.getExtractedText(),co=u;co&&co.id===Ie.id&&(tn!==null&&tn.trim()!==""?co.content=tn:ae.has(co.id)||(co.content=ee(Y)),co.streaming=!1,oe.delete(co.id),ae.delete(co.id),f(co))}});else{let an=typeof Ht=="string"?Ht:(ma=Ht==null?void 0:Ht.text)!=null?ma:null;if(an!==null&&an.trim()!=="")Ie.content=an,ct=!0;else{let bn=Oe.getExtractedText();bn!==null&&bn.trim()!==""&&(Ie.content=bn,ct=!0)}}}}}if(!Ye){if(!Ie.rawContent){let Xe=ae.get(Ie.id);Ie.rawContent=Xe!=null?Xe:ee(Y)}if(!ct&&!ae.has(Ie.id)&&(Ie.content=ee(Y)),Oe){let Xe=(Dr=Oe.close)==null?void 0:Dr.call(Oe);Xe instanceof Promise&&Xe.catch(()=>{})}oe.delete(Ie.id),ae.delete(Ie.id),Ie.streaming=!1,f(Ie)}}else oe.delete(Ie.id),ae.delete(Ie.id),Ie.streaming=!1,f(Ie)}else if(Ge==="flow_complete"){let U=(bt=T.result)==null?void 0:bt.response;if(L){if(u!==null){let R=u;oe.delete(R.id),ae.delete(R.id),R.streaming!==!1&&(R.streaming=!1,f(R))}}else if(U!=null){let R=se(),J=ae.get(R.id),ie=J!=null?J:ee(U);R.rawContent=ie;let Y=ee(U),Ie=oe.get(R.id);if(Ie){let Ye=kr(ie);if(Ye!==null)Y=Ye;else{let Xe=Ie.processChunk(ie);Xe instanceof Promise&&Xe.then(Qt=>{var Ht;let Lt=typeof Qt=="string"?Qt:(Ht=Qt==null?void 0:Qt.text)!=null?Ht:null;Lt!==null&&(R.content=Lt,R.streaming=!1,f(R))});let Ze=Ie.getExtractedText();Ze!==null&&(Y=Ze)}}oe.delete(R.id),ae.delete(R.id);let Oe=Y!==R.content,ct=R.streaming!==!1;Oe&&(R.content=Y),R.streaming=!1,(Oe||ct)&&f(R)}else if(u!==null){let R=u;oe.delete(R.id),ae.delete(R.id),R.streaming!==!1&&(R.streaming=!1,f(R))}n({type:"status",status:"idle"})}else if(Ge==="agent_start")ce={executionId:T.executionId,agentId:(gs=T.agentId)!=null?gs:"virtual",agentName:(lo=T.agentName)!=null?lo:"",status:"running",currentIteration:0,maxTurns:(Wn=T.maxTurns)!=null?Wn:1,startedAt:Ue(T.startedAt)};else if(Ge==="agent_iteration_start"){if(ce&&(ce.currentIteration=T.iteration),$t==="separate"&&T.iteration>1){let U=u;U&&(U.streaming=!1,f(U),Rn.set(T.iteration-1,U),u=null)}}else if(Ge==="agent_turn_start")C=null;else if(Ge==="agent_turn_delta"){if(T.contentType==="text"){let U=se();U.content+=(ga=T.delta)!=null?ga:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:ce==null?void 0:ce.agentName},C=U,f(U)}else if(T.contentType==="thinking"){let U=(fa=T.turnId)!=null?fa:`agent-think-${T.iteration}`,R=Fe(U);R.reasoning=(Fr=R.reasoning)!=null?Fr:{id:U,status:"streaming",chunks:[]},R.reasoning.chunks.push((Oo=T.delta)!=null?Oo:""),R.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},f(R)}else if(T.contentType==="tool_input"){let U=(ha=T.toolCallId)!=null?ha:w.lastId;if(U){let R=P.get(U);R!=null&&R.toolCall&&(R.toolCall.chunks=(ur=R.toolCall.chunks)!=null?ur:[],R.toolCall.chunks.push((fs=T.delta)!=null?fs:""),f(R))}}}else if(Ge==="agent_turn_complete"){let U=T.turnId;if(U){let ie=I.get(U);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Ue(T.completedAt);let Y=(No=ie.reasoning.startedAt)!=null?No:Date.now();ie.reasoning.durationMs=Math.max(0,((hs=ie.reasoning.completedAt)!=null?hs:Date.now())-Y),ie.streaming=!1,f(ie)}}let R=T.stopReason,J=u!=null?u:C;if(R&&J!==null){let ie=T.turnId;(!ie||((Qo=J.agentMetadata)==null?void 0:Qo.turnId)===ie)&&(J.stopReason=R,f(J))}}else if(Ge==="agent_tool_start"){u&&(u.streaming=!1,f(u),u=null);let U=(Jo=T.toolCallId)!=null?Jo:`agent-tool-${l()}`;xe(G(T),U);let R=Ce(U),J=(ba=R.toolCall)!=null?ba:{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};J.name=(Gi=(ya=T.toolName)!=null?ya:T.name)!=null?Gi:J.name,J.status="running",T.parameters!==void 0&&(J.args=T.parameters),J.startedAt=Ue((mr=T.startedAt)!=null?mr:T.timestamp),R.toolCall=J,R.streaming=!0,R.agentMetadata={executionId:T.executionId,iteration:T.iteration},f(R)}else if(Ge==="agent_tool_delta"){let U=(Zo=T.toolCallId)!=null?Zo:w.lastId;if(U){let R=(va=P.get(U))!=null?va:Ce(U);R.toolCall&&(R.toolCall.chunks=(bs=R.toolCall.chunks)!=null?bs:[],R.toolCall.chunks.push((er=T.delta)!=null?er:""),R.toolCall.status="running",R.streaming=!0,f(R))}}else if(Ge==="agent_tool_complete"){let U=(xa=T.toolCallId)!=null?xa:w.lastId;if(U){let R=(ys=P.get(U))!=null?ys:Ce(U);if(R.toolCall){R.toolCall.status="complete",T.result!==void 0&&(R.toolCall.result=T.result),typeof T.executionTime=="number"&&(R.toolCall.durationMs=T.executionTime),R.toolCall.completedAt=Ue((tr=T.completedAt)!=null?tr:T.timestamp),R.streaming=!1,f(R);let J=G(T);J&&w.byCall.delete(J)}}}else if(Ge==="agent_media"){let U=Array.isArray(T.media)?T.media:[],R=[];for(let J of U){if(!J||typeof J!="object")continue;let ie=J,Y=typeof ie.type=="string"?ie.type:void 0,Ie=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Oe=null,ct="";if(Y==="media"){let Ye=typeof ie.data=="string"?ie.data:void 0;if(!Ye)continue;ct=Ie.length>0?Ie:"application/octet-stream",Oe=`data:${ct};base64,${Ye}`}else if(Y==="image-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;ct=Ie,Oe=Ye}else if(Y==="file-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;ct=Ie,Oe=Ye}else continue;if(Oe)if(Y==="image-url"||ct.startsWith("image/"))R.push({type:"image",image:Oe,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))R.push({type:"audio",audio:Oe,mimeType:ct});else if(ct.startsWith("video/"))R.push({type:"video",video:Oe,mimeType:ct});else{let Ye=ct||"application/octet-stream";R.push({type:"file",data:Oe,mimeType:Ye,filename:lh(Ye)})}}if(R.length>0){let J=l(),ie=T.toolCallId,Ie={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:R,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(Ie);let Oe=u;Oe&&(Oe.streaming=!1,f(Oe)),u=null,v.current=null}}else if(Ge!=="agent_iteration_complete"){if(Ge==="agent_reflection"||Ge==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,R={id:U,role:"assistant",content:(vs=T.reflection)!=null?vs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(wa=T.reflection)!=null?wa:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(R)}else if(Ge==="agent_complete"){ce&&(ce.status=T.success?"complete":"error",ce.completedAt=Ue(T.completedAt),ce.stopReason=T.stopReason);let U=u;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(Ge==="agent_error"){let U=typeof T.error=="string"?T.error:(Ca=(_o=T.error)==null?void 0:_o.message)!=null?Ca:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ge!=="agent_ping"){if(Ge==="agent_approval_start"){let U=(nr=T.approvalId)!=null?nr:`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:(Ft=ce==null?void 0:ce.agentId)!=null?Ft:"virtual",executionId:(Nr=(Or=T.executionId)!=null?Or:ce==null?void 0:ce.executionId)!=null?Nr:"",toolName:(xs=T.toolName)!=null?xs:"",toolType:T.toolType,description:(Sa=T.description)!=null?Sa:`Execute ${(Lo=T.toolName)!=null?Lo:"tool"}`,parameters:T.parameters}};f(R)}else if(Ge==="step_await"&&T.awaitReason==="approval_required"){let U=(ws=T.approvalId)!=null?ws:`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:(Cs=ce==null?void 0:ce.agentId)!=null?Cs:"virtual",executionId:(_r=(Aa=T.executionId)!=null?Aa:ce==null?void 0:ce.executionId)!=null?_r:"",toolName:(Vr=T.toolName)!=null?Vr:"",toolType:T.toolType,description:(Ta=T.description)!=null?Ta:`Execute ${(gr=T.toolName)!=null?gr:"tool"}`,parameters:T.parameters}};f(R)}else if(Ge==="agent_approval_complete"){let U=T.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ka=T.decision)!=null?ka:"approved",agentId:(Ss=ce==null?void 0:ce.agentId)!=null?Ss:"virtual",executionId:(Ts=(As=T.executionId)!=null?As:ce==null?void 0:ce.executionId)!=null?Ts:"",toolName:(ks=T.toolName)!=null?ks:"",description:(En=T.description)!=null?En:"",resolvedAt:Date.now()}};f(J)}}else if(Ge==="artifact_start"||Ge==="artifact_delta"||Ge==="artifact_update"||Ge==="artifact_complete"){if(Ge==="artifact_start"){let U=T.artifactType,R=String(T.id),J=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:R,artifactType:U,title:J,component:typeof T.component=="string"?T.component:void 0}),ye.set(R,{markdown:"",title:J}),!K.has(R)){K.add(R);let ie={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:R,title:J,artifactType:U,status:"streaming"}})};de.set(R,ie),f(ie)}}else if(Ge==="artifact_delta"){let U=String(T.id),R=typeof T.delta=="string"?T.delta:String((Gn=T.delta)!=null?Gn:"");n({type:"artifact_delta",id:U,artDelta:R});let J=ye.get(U);J&&(J.markdown+=R)}else if(Ge==="artifact_update"){let U=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:U,component:typeof T.component=="string"?T.component:void 0})}else if(Ge==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let R=de.get(U);if(R){R.streaming=!1;try{let J=JSON.parse((Vo=R.rawContent)!=null?Vo:"{}");if(J.props){J.props.status="complete";let ie=ye.get(U);ie!=null&&ie.markdown&&(J.props.markdown=ie.markdown)}R.rawContent=JSON.stringify(J)}catch{}ye.delete(U),f(R),de.delete(U)}}}else if(Ge==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let R=String((lt=U.id)!=null?lt:`msg-${l()}`),J=U.role,Y={id:R,role:J==="user"?"user":J==="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(Y),Y.rawContent)try{let Ie=JSON.parse(Y.rawContent),Oe=(Es=Ie==null?void 0:Ie.props)==null?void 0:Es.artifactId;typeof Oe=="string"&&K.add(Oe)}catch{}u=null,v.current=null,oe.delete(R),ae.delete(R)}else if(Ge==="error"||Ge==="step_error"||Ge==="dispatch_error"||Ge==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if(Ge==="dispatch_error"){let R=(fr=T.message)!=null?fr:T.error;R!=null&&R!==""&&(U=new Error(String(R)))}else if(Ge==="step_error"||Ge==="flow_error"){let R=T.error;typeof R=="string"&&R!==""?U=new Error(R):R!=null&&typeof R=="object"&&"message"in R&&(U=new Error(String((So=R.message)!=null?So:R)))}else Ge==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let R=u;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}ue.length=0};;){let{done:_,value:Me}=await r.read();if(_)break;a+=s.decode(Me,{stream:!0});let Be=a.split(`
|
|
10
10
|
|
|
11
|
-
`);a=(Dn=
|
|
12
|
-
`),dt="message",ot="";for(let q of $e)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((qe=this.onSSEEvent)==null||qe.call(this,Vt,At),this.parseSSEEvent){S.current=p;let q=await this.handleCustomSSEEvent(At,n,S,g,l,M);if(S.current&&S.current!==p&&(p=S.current),q)continue}pe.push(Vt,At),Ve()}}pe.flushPending(),Ve(),pe.destroy()}};function Qa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Bs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ja="[Image]";function cl(e){return{type:"text",text:e}}var Ru=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Jg=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],_o=[...Ru,...Jg];function Zg(e){return Ru.includes(e)||e.startsWith("image/")}function Za(e){return Zg(e.type)}async function Pu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Za(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 Wu(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 eh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Bu(e,t){let n=eh(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 ei=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 ti=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 m=0;m<a.length;m++)i+=a[m]*a[m];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 Hs=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 ti;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 m=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,p)=>{if(!this.ws)return p(new Error("WebSocket not created"));let w=!1,S=I=>{w||(w=!0,clearTimeout(M),p(new Error(I)))},M=setTimeout(()=>S("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),g())},{once:!0}),this.ws.addEventListener("error",()=>{S("WebSocket connection failed to "+m+"."+u)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!w){let L=I.code!==1006?` (code ${I.code})`:"";S("WebSocket connection failed"+L+"."+u)}},{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 ei(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let m=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:m});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,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 Ds(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Hs(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 Hu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ds({type:"runtype",runtype:e.runtype});if(Sr.isSupported())return Ds({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function dl(e){try{return Hu(e),!0}catch{return!1}}function Du(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=Be.pop())!=null?Dn:"";for(let He of Be){let _e=He.split(`
|
|
12
|
+
`),ut="message",st="";for(let q of _e)q.startsWith("event:")?ut=q.replace("event:","").trim():q.startsWith("data:")&&(st+=q.replace("data:","").trim());if(!st)continue;let Rt;try{Rt=JSON.parse(st)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let qt=ut!=="message"?ut:(eo=Rt.type)!=null?eo:"message";if((ze=this.onSSEEvent)==null||ze.call(this,qt,Rt),this.parseSSEEvent){v.current=u;let q=await this.handleCustomSSEEvent(Rt,n,v,f,l,E);if(v.current&&v.current!==u&&(u=v.current),q)continue}he.push(qt,Rt),Ne()}}he.flushPending(),Ne(),he.destroy()}};function Za(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function _s(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ei="[Image]";function fl(e){return{type:"text",text:e}}var _u=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ph=["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"],Uo=[..._u,...ph];function uh(e){return _u.includes(e)||e.startsWith("image/")}function ti(e){return uh(e.type)}async function Vu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ti(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 $u(e,t=Uo,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 mh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Uu(e,t){let n=mh(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 ni=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 oi=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 m=0;m<a.length;m++)i+=a[m]*a[m];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 Vs=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 oi;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 m=`${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,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let C=!1,v=L=>{C||(C=!0,clearTimeout(E),u(new Error(L)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+m+"."+p)},{once:!0}),this.ws.addEventListener("close",L=>{if(!L.wasClean&&!C){let I=L.code!==1006?` (code ${L.code})`:"";v("WebSocket connection failed"+I+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ni(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 m=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:m});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 Er=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 $s(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Vs(e.runtype);case"browser":if(!Er.isSupported())throw new Error("Browser speech recognition not supported");return new Er(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function zu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return $s({type:"runtype",runtype:e.runtype});if(Er.isSupported())return $s({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function hl(e){try{return zu(e),!0}catch{return!1}}function qu(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 Fs=e=>({isError:!0,content:[{type:"text",text:e}]}),Fu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ni=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 m=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(m!=null&&m.name)&&qr(m.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 m=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":m||(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 Ws(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 dl((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=Ds(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 m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var m,u,g,p,w,S;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((m=l.transcript)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.text)!=null&&p.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(S=this.pendingVoiceAssistantMessageId)!=null?S:(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 m,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(m=this.callbacks).onVoiceStatusChanged)==null||u.call(m,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,m;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:(m=t.browser)==null?void 0:m.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 Ws(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:m,rawContent:u}=t,p={id:a!=null?a:n==="user"?Qa():n==="assistant"?Bs():`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},...m!==void 0&&{voiceProcessing:m},...u!==void 0&&{rawContent:u}};return this.upsertMessage(p),p}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:m,streaming:u=!1,voiceProcessing:g,rawContent:p}=o,S={id:d!=null?d:r==="user"?Qa():r==="assistant"?Bs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...p!==void 0&&{rawContent:p}};n.push(S)}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,m,u,g,p;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=Qa(),s=Bs(),a={id:r,role:"user",content:o||Ja,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 S=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!S){let M=Du(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,S||(w instanceof Error?(u=(m=this.callbacks).onError)==null||u.call(m,w):(p=(g=this.callbacks).onError)==null||p.call(g,new Error(String(w))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Bs();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 m=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!m){let u=Du(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(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,m,u;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let p=null;if(g instanceof Response){if(!g.ok){let w=await g.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${g.status}`)}p=g.body}else g instanceof ReadableStream&&(p=g);p?await this.connectStream(p,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let p=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,p||(u=(m=this.callbacks).onError)==null||u.call(m,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var m,u,g,p,w,S,M,I,L,H,D,W;let o=this.messages.find(v=>v.id===t.id);if(((m=o==null?void 0:o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let r=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!r||!s){(w=(p=this.callbacks).onError)==null||w.call(p,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=(S=t.toolCall)==null?void 0:S.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=(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(([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 C=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!C)return;let T=v[C],F=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:C,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||(W=(D=this.callbacks).onError)==null||W.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)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,m;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var D,W,v,x,k,C,T;let g=(D=u.toolCall)==null?void 0:D.name,p=(W=u.toolCall)==null?void 0:W.id;if(!g||!p)return null;let w=`${t}:${p}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return null;this.webMcpInflightKeys.add(w),o.push(w);let S=this.markWebMcpToolRunning(u),M=new AbortController;this.webMcpResolveControllers.add(M),r.push(M);let I=(x=(v=u.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?x:g,L=this.client.executeWebMcpToolCall(g,(k=u.toolCall)==null?void 0:k.args,M.signal),H;if(!L)H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{H=await L}catch(F){let $=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return $||(T=(C=this.callbacks).onError)==null||T.call(C,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(u,Fs($?"Aborted by cancel()":Fu(F)),S),this.webMcpInflightKeys.delete(w),null}return M.signal.aborted?(this.markWebMcpToolComplete(u,Fs("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:I,output:H,toolMessage:u,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(p=>p!==null),i.length===0)return;let u={};for(let p of i)u[p.resumeKey]=p.output;let g=await this.client.resumeFlow(t,u,{signal:s.signal});if(!g.ok){let p=await g.json().catch(()=>null);throw new Error((d=p==null?void 0:p.error)!=null?d:`Resume failed: ${g.status}`)}for(let p of i)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(m=(l=this.callbacks).onError)==null||m.call(l,u instanceof Error?u:new Error(String(u)));else for(let p of i)this.markWebMcpToolComplete(p.toolMessage,Fs("Aborted by cancel()"),p.startedAt)}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 p,w,S,M,I,L,H,D,W,v,x,k;let n=(p=t.agentMetadata)==null?void 0:p.executionId,o=(w=t.toolCall)==null?void 0:w.name,r=(S=t.toolCall)==null?void 0:S.id;if(!n){(I=(M=this.callbacks).onError)==null||I.call(M,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let C=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return;this.webMcpInflightKeys.add(C);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(C)}catch(T){(H=(L=this.callbacks).onError)==null||H.call(L,T instanceof Error?T:new Error(String(T)))}finally{this.webMcpInflightKeys.delete(C)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(D=t.toolCall)==null?void 0:D.args,m=this.client.executeWebMcpToolCall(o,l,d),u="execute",g=a;try{let C;if(m?C=await m:C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Fs("Aborted by cancel()"),a);return}let T=(v=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?v:o;u="resume",await this.resumeWithToolOutput(n,T,C,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,C,a,g)},signal:d})}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));(u==="execute"||T||d.aborted)&&this.markWebMcpToolComplete(t,Fs(T||d.aborted?"Aborted by cancel()":Fu(C)),a),T||(k=(x=this.callbacks).onError)==null||k.call(x,C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),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 m,u,g,p,w,S,M,I,L,H;if(s!==o)return r;let a={...r,...n};((m=r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=n.toolCall)==null?void 0:u.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(p=n.toolCall)==null?void 0:p.id;if(i&&qr(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let D=`${d}:${l}`,W=this.webMcpInflightKeys.has(D),v=this.webMcpResolvedKeys.has(D),x=(S=r.toolCall)==null?void 0:S.name,k=((M=r.agentMetadata)==null?void 0:M.executionId)===d&&((I=r.toolCall)==null?void 0:I.id)===l&&x!==void 0&&qr(x)&&((L=r.toolCall)==null?void 0:L.status)==="complete";(W||v||k)&&(a.agentMetadata={...(H=a.agentMetadata)!=null?H:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,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 th,ArrowDown as nh,ArrowUp as oh,ArrowUpRight as rh,Bot as sh,ChevronDown as ah,ChevronUp as ih,ChevronRight as lh,ChevronLeft as ch,Check as dh,Clipboard as ph,ClipboardCopy as uh,Copy as mh,File as fh,FileCode as gh,FileSpreadsheet as hh,FileText as bh,ImagePlus as yh,Loader as vh,LoaderCircle as xh,Mic as wh,Paperclip as Ch,RefreshCw as Sh,Search as Ah,Send as Th,ShieldAlert as kh,ShieldCheck as Eh,ShieldX as Mh,Square as Lh,ThumbsDown as Ih,ThumbsUp as Rh,Upload as Ph,Volume2 as Wh,X as Bh,User as Hh,Mail as Dh,Phone as Fh,Calendar as Oh,Clock as Nh,Building as _h,MapPin as Vh,Lock as $h,Key as Uh,CreditCard as zh,AtSign as qh,Hash as jh,Globe as Kh,Link as Gh,CircleCheck as Yh,CircleX as Xh,TriangleAlert as Qh,Info as Jh,Ban as Zh,Shield as eb,ArrowLeft as tb,ArrowRight as nb,ExternalLink as ob,Ellipsis as rb,EllipsisVertical as sb,Menu as ab,House as ib,Plus as lb,Minus as cb,Pencil as db,Trash as pb,Trash2 as ub,Save as mb,Download as fb,Share as gb,Funnel as hb,Settings as bb,RotateCw as yb,Maximize as vb,Minimize as xb,ShoppingCart as wb,ShoppingBag as Cb,Package as Sb,Truck as Ab,Tag as Tb,Gift as kb,Receipt as Eb,Wallet as Mb,Store as Lb,DollarSign as Ib,Percent as Rb,Play as Pb,Pause as Wb,VolumeX as Bb,Camera as Hb,Image as Db,Film as Fb,Headphones as Ob,MessageCircle as Nb,MessageSquare as _b,Bell as Vb,Heart as $b,Star as Ub,Eye as zb,EyeOff as qb,Bookmark as jb,CalendarDays as Kb,History as Gb,Timer as Yb,Folder as Xb,FolderOpen as Qb,Files as Jb,Sparkles as Zb,Zap as ey,Sun as ty,Moon as ny,Flag as oy,Monitor as ry,Smartphone as sy}from"lucide";var ay={activity:th,"arrow-down":nh,"arrow-up":oh,"arrow-up-right":rh,bot:sh,"chevron-down":ah,"chevron-up":ih,"chevron-right":lh,"chevron-left":ch,check:dh,clipboard:ph,"clipboard-copy":uh,copy:mh,file:fh,"file-code":gh,"file-spreadsheet":hh,"file-text":bh,"image-plus":yh,loader:vh,"loader-circle":xh,mic:wh,paperclip:Ch,"refresh-cw":Sh,search:Ah,send:Th,"shield-alert":kh,"shield-check":Eh,"shield-x":Mh,square:Lh,"thumbs-down":Ih,"thumbs-up":Rh,upload:Ph,"volume-2":Wh,x:Bh,user:Hh,mail:Dh,phone:Fh,calendar:Oh,clock:Nh,building:_h,"map-pin":Vh,lock:$h,key:Uh,"credit-card":zh,"at-sign":qh,hash:jh,globe:Kh,link:Gh,"circle-check":Yh,"circle-x":Xh,"triangle-alert":Qh,info:Jh,ban:Zh,shield:eb,"arrow-left":tb,"arrow-right":nb,"external-link":ob,ellipsis:rb,"ellipsis-vertical":sb,menu:ab,house:ib,plus:lb,minus:cb,pencil:db,trash:pb,"trash-2":ub,save:mb,download:fb,share:gb,funnel:hb,settings:bb,"rotate-cw":yb,maximize:vb,minimize:xb,"shopping-cart":wb,"shopping-bag":Cb,package:Sb,truck:Ab,tag:Tb,gift:kb,receipt:Eb,wallet:Mb,store:Lb,"dollar-sign":Ib,percent:Rb,play:Pb,pause:Wb,"volume-x":Bb,camera:Hb,image:Db,film:Fb,headphones:Ob,"message-circle":Nb,"message-square":_b,bell:Vb,heart:$b,star:Ub,eye:zb,"eye-off":qb,bookmark:jb,"calendar-days":Kb,history:Gb,timer:Yb,folder:Xb,"folder-open":Qb,files:Jb,sparkles:Zb,zap:ey,sun:ty,moon:ny,flag:oy,monitor:ry,smartphone:sy},Te=(e,t=24,n="currentColor",o=2)=>{let r=ay[e];return r?iy(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 iy(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,m])=>{l!=="stroke"&&d.setAttribute(l,String(m))}),r.appendChild(d)}),r}var oi={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ly(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cy(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 Os=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:oi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:oi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:oi.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:oi.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 m=Wu(l,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let u=(r=m.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Pu(l),g=Za(l)?URL.createObjectURL(l):null,p={id:ly(),file:l,previewUrl:g,contentPart:u};this.attachments.push(p),this.renderPreview(p)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let 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=Za(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=cy(t.file.type),d=Te(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Bu(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 dy}from"idiomorph";var ri=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;dy.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 si={index:-1,draft:""};function Ou(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:{...si}}}function Nu(e,t){var n,o,r,s,a,i,d,l,m,u,g,p,w,S,M,I,L,H,D,W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve,Q,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,(m=(l=e.llmContent)==null?void 0:l.length)!=null?m:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(w=(p=e.toolCall)==null?void 0:p.status)!=null?w:"",(M=(S=e.toolCall)==null?void 0:S.name)!=null?M:"",(H=(L=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:L.length)!=null?H:0,(x=(v=(W=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:W[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:(C=e.toolCall)!=null&&C.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:F.length)!=null?$:0,(fe=(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?fe:0,(ve=(Oe=(be=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Oe.slice(-32))!=null?ve:"",(Le=(Q=e.contentParts)==null?void 0:Q.length)!=null?Le:0,(Y=e.stopReason)!=null?Y:"",t].join("\0")}function _u(){return new Map}function Vu(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 Uu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ai(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Ns(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,t){return Ns(e)-e.scrollTop<=t}function ii(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,m=n-o;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:n}:!t&&r&&(!l||m>0)?{action:"resume",delta:m,nextLastScrollTop:n}:t&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:m,nextLastScrollTop:n}:{action:"none",delta:m,nextLastScrollTop:n}}function li(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 gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,or=hn+1;var Vs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},py=["pre","code","a","script","style"],ci=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Vs.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Vs.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Vs.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Vs.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Vs.buffer}},uy=[{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"}],qu=new Map;for(let e of uy)qu.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=qu.get(e))!=null?o:null},di=(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},
|
|
14
|
+
_Details: ${n.message}_`:o}var Us=e=>({isError:!0,content:[{type:"text",text:e}]}),ju=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ri=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 m=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(m!=null&&m.name)&&Qr(m.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 m=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":m||(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 Ns(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 hl((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=$s(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 m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var m,p,f,u,C,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((m=l.transcript)!=null&&m.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}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(L=>L.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}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 m,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(m=this.callbacks).onVoiceStatusChanged)==null||p.call(m,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,m;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:(m=t.browser)==null?void 0:m.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 Ns(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:m,rawContent:p}=t,u={id:a!=null?a:n==="user"?Za():n==="assistant"?_s():`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},...m!==void 0&&{voiceProcessing:m},...p!==void 0&&{rawContent:p}};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:m,streaming:p=!1,voiceProcessing:f,rawContent:u}=o,v={id:d!=null?d:r==="user"?Za():r==="assistant"?_s():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};n.push(v)}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,m,p,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=Za(),s=_s(),a={id:r,role:"user",content:o||ei,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(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let E=qu(C,this.config.errorMessage);if(E){let L={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(L)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(C instanceof Error?(p=(m=this.callbacks).onError)==null||p.call(m,C):(u=(f=this.callbacks).onError)==null||u.call(f,new Error(String(C))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=_s();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 m=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!m){let p=qu(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,m||(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,o){var m,p,f,u,C;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===r),i={id:r,role:"assistant",content:"",createdAt:(m=a==null?void 0:a.createdAt)!=null?m:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(p=this.abortController)==null||p.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(l?v=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let E=null;if(v instanceof Response){if(!v.ok){let L=await v.json().catch(()=>null);throw new Error((f=L==null?void 0:L.error)!=null?f:`Approval request failed: ${v.status}`)}E=v.body}else v instanceof ReadableStream&&(E=v);E?await this.connectStream(E,{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(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(C=(u=this.callbacks).onError)==null||C.call(u,v instanceof Error?v:new Error(String(v)))}}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 m,p,f,u,C,v,E,L,I,P,H,W;let o=this.messages.find(x=>x.id===t.id);if(((m=o==null?void 0:o.agentMetadata)==null?void 0:m.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){(C=(u=this.callbacks).onError)==null||C.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 x=(v=t.toolCall)==null?void 0:v.args,w=Array.isArray(x==null?void 0:x.questions)?x.questions:[];if(w.length===1){let k=typeof((E=w[0])==null?void 0:E.question)=="string"?w[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(L=this.abortController)==null||L.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let x=typeof n=="string"?n:Object.entries(n).map(([w,k])=>`${w}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:x,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let x=a!=null?a:{};l.forEach((w,k)=>{let S=typeof(w==null?void 0:w.question)=="string"?w.question:"";if(!S)return;let A=x[S],N=Array.isArray(A)?A.join(", "):typeof A=="string"?A:"";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:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let x=await this.client.resumeFlow(r,{[s]:n});if(!x.ok){let w=await x.json().catch(()=>null);throw new Error((P=w==null?void 0:w.error)!=null?P:`Resume failed: ${x.status}`)}x.body?await this.connectStream(x.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(x){let w=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(W=(H=this.callbacks).onError)==null||W.call(H,x instanceof Error?x:new Error(String(x)))}}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)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,m;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var H,W,x,w,k,S,A;let f=(H=p.toolCall)==null?void 0:H.name,u=(W=p.toolCall)==null?void 0:W.id;if(!f||!u)return null;let C=`${t}:${u}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return null;this.webMcpInflightKeys.add(C),o.push(C);let v=this.markWebMcpToolRunning(p),E=new AbortController;this.webMcpResolveControllers.add(E),r.push(E);let L=(w=(x=p.agentMetadata)==null?void 0:x.webMcpToolCallId)!=null?w:f,I=this.client.executeWebMcpToolCall(f,(k=p.toolCall)==null?void 0:k.args,E.signal),P;if(!I)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await I}catch(N){let $=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return $||(A=(S=this.callbacks).onError)==null||A.call(S,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(p,Us($?"Aborted by cancel()":ju(N)),v),this.webMcpInflightKeys.delete(C),null}return E.signal.aborted?(this.markWebMcpToolComplete(p,Us("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:L,output:P,toolMessage:p,startedAt:v,completedAt:Date.now()}})),i=[];try{if(i=a.filter(u=>u!==null),i.length===0)return;let p={};for(let u of i)p[u.resumeKey]=u.output;let f=await this.client.resumeFlow(t,p,{signal:s.signal});if(!f.ok){let u=await f.json().catch(()=>null);throw new Error((d=u==null?void 0:u.error)!=null?d:`Resume failed: ${f.status}`)}for(let u of i)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(m=(l=this.callbacks).onError)==null||m.call(l,p instanceof Error?p:new Error(String(p)));else for(let u of i)this.markWebMcpToolComplete(u.toolMessage,Us("Aborted by cancel()"),u.startedAt)}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 u,C,v,E,L,I,P,H,W,x,w,k;let n=(u=t.agentMetadata)==null?void 0:u.executionId,o=(C=t.toolCall)==null?void 0:C.name,r=(v=t.toolCall)==null?void 0:v.id;if(!n){(L=(E=this.callbacks).onError)==null||L.call(E,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let S=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))return;this.webMcpInflightKeys.add(S);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(S)}catch(A){(P=(I=this.callbacks).onError)==null||P.call(I,A instanceof Error?A:new Error(String(A)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(H=t.toolCall)==null?void 0:H.args,m=this.client.executeWebMcpToolCall(o,l,d),p="execute",f=a;try{let S;if(m?S=await m:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Us("Aborted by cancel()"),a);return}let A=(x=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?x:o;p="resume",await this.resumeWithToolOutput(n,A,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,f)},signal:d})}catch(S){let A=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(p==="execute"||A||d.aborted)&&this.markWebMcpToolComplete(t,Us(A||d.aborted?"Aborted by cancel()":ju(S)),a),A||(k=(w=this.callbacks).onError)==null||k.call(w,S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),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 m,p,f,u,C,v,E,L,I,P;if(s!==o)return r;let a={...r,...n};((m=r.agentMetadata)==null?void 0:m.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=(u=n.toolCall)==null?void 0:u.id;if(i&&Qr(i)&&d&&l&&((C=n.agentMetadata)==null?void 0:C.awaitingLocalTool)===!0){let H=`${d}:${l}`,W=this.webMcpInflightKeys.has(H),x=this.webMcpResolvedKeys.has(H),w=(v=r.toolCall)==null?void 0:v.name,k=((E=r.agentMetadata)==null?void 0:E.executionId)===d&&((L=r.toolCall)==null?void 0:L.id)===l&&w!==void 0&&Qr(w)&&((I=r.toolCall)==null?void 0:I.status)==="complete";(W||x||k)&&(a.agentMetadata={...(P=a.agentMetadata)!=null?P:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,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},Po=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as gh,ArrowDown as fh,ArrowUp as hh,ArrowUpRight as bh,Bot as yh,ChevronDown as vh,ChevronUp as xh,ChevronRight as wh,ChevronLeft as Ch,Check as Sh,Clipboard as Ah,ClipboardCopy as Th,Copy as kh,File as Eh,FileCode as Mh,FileSpreadsheet as Lh,FileText as Ih,ImagePlus as Rh,Loader as Ph,LoaderCircle as Wh,Mic as Bh,Paperclip as Hh,RefreshCw as Dh,Search as Fh,Send as Oh,ShieldAlert as Nh,ShieldCheck as _h,ShieldX as Vh,Square as $h,ThumbsDown as Uh,ThumbsUp as zh,Upload as qh,Volume2 as jh,X as Kh,User as Gh,Mail as Yh,Phone as Xh,Calendar as Qh,Clock as Jh,Building as Zh,MapPin as eb,Lock as tb,Key as nb,CreditCard as ob,AtSign as rb,Hash as sb,Globe as ab,Link as ib,CircleCheck as lb,CircleX as cb,TriangleAlert as db,Info as pb,Ban as ub,Shield as mb,ArrowLeft as gb,ArrowRight as fb,ExternalLink as hb,Ellipsis as bb,EllipsisVertical as yb,Menu as vb,House as xb,Plus as wb,Minus as Cb,Pencil as Sb,Trash as Ab,Trash2 as Tb,Save as kb,Download as Eb,Share as Mb,Funnel as Lb,Settings as Ib,RotateCw as Rb,Maximize as Pb,Minimize as Wb,ShoppingCart as Bb,ShoppingBag as Hb,Package as Db,Truck as Fb,Tag as Ob,Gift as Nb,Receipt as _b,Wallet as Vb,Store as $b,DollarSign as Ub,Percent as zb,Play as qb,Pause as jb,VolumeX as Kb,Camera as Gb,Image as Yb,Film as Xb,Headphones as Qb,MessageCircle as Jb,MessageSquare as Zb,Bell as ey,Heart as ty,Star as ny,Eye as oy,EyeOff as ry,Bookmark as sy,CalendarDays as ay,History as iy,Timer as ly,Folder as cy,FolderOpen as dy,Files as py,Sparkles as uy,Zap as my,Sun as gy,Moon as fy,Flag as hy,Monitor as by,Smartphone as yy}from"lucide";var vy={activity:gh,"arrow-down":fh,"arrow-up":hh,"arrow-up-right":bh,bot:yh,"chevron-down":vh,"chevron-up":xh,"chevron-right":wh,"chevron-left":Ch,check:Sh,clipboard:Ah,"clipboard-copy":Th,copy:kh,file:Eh,"file-code":Mh,"file-spreadsheet":Lh,"file-text":Ih,"image-plus":Rh,loader:Ph,"loader-circle":Wh,mic:Bh,paperclip:Hh,"refresh-cw":Dh,search:Fh,send:Oh,"shield-alert":Nh,"shield-check":_h,"shield-x":Vh,square:$h,"thumbs-down":Uh,"thumbs-up":zh,upload:qh,"volume-2":jh,x:Kh,user:Gh,mail:Yh,phone:Xh,calendar:Qh,clock:Jh,building:Zh,"map-pin":eb,lock:tb,key:nb,"credit-card":ob,"at-sign":rb,hash:sb,globe:ab,link:ib,"circle-check":lb,"circle-x":cb,"triangle-alert":db,info:pb,ban:ub,shield:mb,"arrow-left":gb,"arrow-right":fb,"external-link":hb,ellipsis:bb,"ellipsis-vertical":yb,menu:vb,house:xb,plus:wb,minus:Cb,pencil:Sb,trash:Ab,"trash-2":Tb,save:kb,download:Eb,share:Mb,funnel:Lb,settings:Ib,"rotate-cw":Rb,maximize:Pb,minimize:Wb,"shopping-cart":Bb,"shopping-bag":Hb,package:Db,truck:Fb,tag:Ob,gift:Nb,receipt:_b,wallet:Vb,store:$b,"dollar-sign":Ub,percent:zb,play:qb,pause:jb,"volume-x":Kb,camera:Gb,image:Yb,film:Xb,headphones:Qb,"message-circle":Jb,"message-square":Zb,bell:ey,heart:ty,star:ny,eye:oy,"eye-off":ry,bookmark:sy,"calendar-days":ay,history:iy,timer:ly,folder:cy,"folder-open":dy,files:py,sparkles:uy,zap:my,sun:gy,moon:fy,flag:hy,monitor:by,smartphone:yy},Ee=(e,t=24,n="currentColor",o=2)=>{let r=vy[e];return r?xy(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 xy(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,m])=>{l!=="stroke"&&d.setAttribute(l,String(m))}),r.appendChild(d)}),r}var si={allowedTypes:Uo,maxFileSize:10*1024*1024,maxFiles:4};function wy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Cy(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 zs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:si.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:si.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:si.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:si.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 m=$u(l,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let p=(r=m.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await Vu(l),f=ti(l)?URL.createObjectURL(l):null,u={id:wy(),file:l,previewUrl:f,contentPart:p};this.attachments.push(u),this.renderPreview(u)}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=ti(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=Cy(t.file.type),d=Ee(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Uu(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=Ee("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 Sy}from"idiomorph";var ai=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Sy.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 ii={index:-1,draft:""};function Ku(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:{...ii}}}function Gu(e,t){var n,o,r,s,a,i,d,l,m,p,f,u,C,v,E,L,I,P,H,W,x,w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe,j,de,K;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,(m=(l=e.llmContent)==null?void 0:l.length)!=null?m:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(u=e.toolCall)==null?void 0:u.status)!=null?C:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(P=(I=(L=e.toolCall)==null?void 0:L.chunks)==null?void 0:I.length)!=null?P:0,(w=(x=(W=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:x.slice(-32))!=null?w:"",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,($=(N=(A=e.reasoning)==null?void 0:A.chunks)==null?void 0:N.length)!=null?$:0,(se=(ge=(fe=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:fe[e.reasoning.chunks.length-1])==null?void 0:ge.length)!=null?se:0,(xe=(Fe=(be=(ke=e.reasoning)==null?void 0:ke.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Fe.slice(-32))!=null?xe:"",(de=(j=e.contentParts)==null?void 0:j.length)!=null?de:0,(K=e.stopReason)!=null?K:"",t].join("\0")}function Yu(){return new Map}function Xu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Qu(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Ju(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function li(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function qs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function js(e,t){return qs(e)-e.scrollTop<=t}function ci(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,m=n-o;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:n}:!t&&r&&(!l||m>0)?{action:"resume",delta:m,nextLastScrollTop:n}:t&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:m,nextLastScrollTop:n}:{action:"none",delta:m,nextLastScrollTop:n}}function di(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 xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,ar=wn+1;var Ks={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ay=["pre","code","a","script","style"],pi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ks.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ks.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ks.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ks.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ks.buffer}},Ty=[{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"}],em=new Map;for(let e of Ty)em.set(e.name,e);var Gs=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=em.get(e))!=null?o:null},ui=(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},ky=(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},Ey=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},bl=/\s/,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},Ly=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(bl.test(s[i])){let l=i;for(;l<s.length&&bl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let m=i;for(;m<s.length&&!bl.test(s[m]);)l.appendChild(ky(o,s[m],t,n.value)),n.value+=1,m+=1;a.appendChild(l),i=m}r.replaceChild(a,e)},Iy=(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(Ey(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Ys=(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:Ay).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},m=t==="char"?Ly:Iy;for(let u of i)m(u,n,l);return r.innerHTML},mi=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Xs=(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},Zu=new WeakMap,Ry=(e,t)=>{var s;if(!e.styles)return;let n=Zu.get(t);if(n||(n=new Set,Zu.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)},yl=new WeakMap,Py=(e,t)=>{if(!e.onAttach)return;let n=yl.get(t);if(n||(n=new Map,yl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},tm=e=>{let t=yl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},vl=(e,t)=>{Ry(e,t),Py(e,t)};function xl(e,t=wn){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 Qs=0,ir=null;function wl(e=document){var n;if(Qs++,Qs===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;ir={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,Qs=Math.max(0,Qs-1),Qs===0&&ir)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=ir.originalOverflow,r.style.position=ir.originalPosition,r.style.top=ir.originalTop,r.style.width=ir.originalWidth,s.scrollTo(0,ir.scrollY),ir=null}}}var gi={side:"right",width:"420px",animate:!0,reveal:"resize"},hn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Js=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Wo=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:gi.side,width:(r=t==null?void 0:t.width)!=null?r:gi.width,animate:(s=t==null?void 0:t.animate)!=null?s:gi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:gi.reveal}};var ko={"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 Zs=(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 Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
20
20
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
21
|
</span>
|
|
22
22
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
23
|
-
`,n.addEventListener("click",t);let o=s=>{var H,D,W,v,x,k,C,T,F,$,j,me,se,fe;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=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(u.style.height=ie,u.style.width=ie,u.innerHTML="",a.agentIconName){let be=parseFloat(ie)||24,Oe=Te(a.agentIconName,be*.6,"var(--persona-text-inverse, #ffffff)",2);Oe?(u.appendChild(Oe),u.style.display=""):(u.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ie=(C=a.agentIconSize)!=null?C:"40px";g.style.height=ie,g.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let p=n.querySelector("[data-role='launcher-call-to-action-icon']");if(p){let ie=(T=a.callToActionIconSize)!=null?T:"32px";p.style.height=ie,p.style.width=ie,a.callToActionIconBackgroundColor?(p.style.backgroundColor=a.callToActionIconBackgroundColor,p.classList.remove("persona-bg-persona-primary")):(p.style.backgroundColor="",p.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(p.style.color=a.callToActionIconColor,p.classList.remove("persona-text-persona-call-to-action")):(p.style.color="",p.classList.add("persona-text-persona-call-to-action"));let be=0;if(a.callToActionIconPadding?(p.style.boxSizing="border-box",p.style.padding=a.callToActionIconPadding,be=(parseFloat(a.callToActionIconPadding)||0)*2):(p.style.boxSizing="",p.style.padding=""),a.callToActionIconHidden)p.style.display="none";else if(p.style.display=i?"none":"",p.innerHTML="",a.callToActionIconName){let Oe=parseFloat(ie)||24,ve=Math.max(Oe-be,8),Q=Te(a.callToActionIconName,ve,"currentColor",2);Q?p.appendChild(Q):p.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else p.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let w=a.position&&xo[a.position]?xo[a.position]:xo["bottom-right"],S="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:`${S} ${w}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:hn));let I="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:I,n.style.boxShadow=(se=a.shadow)!=null?se: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=(fe=a.collapsedMaxWidth)!=null?fe:"",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 xy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",mi=(e,t={})=>{var S,M,I,L,H,D;let{showClose:n=!0,wrapperClassName:o=xy,buttonSize:r,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},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 m=(I=a.closeButtonTooltipText)!=null?I:"Close chat",u=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let g=(H=a.closeButtonIconName)!=null?H:"x",p=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let w=Te(g,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=p,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&m){let W=null,v=()=>{if(W)return;let k=l.ownerDocument,C=k.body;if(!C)return;W=Eo(k,"div","persona-clear-chat-tooltip"),W.textContent=m;let T=Eo(k,"div");T.className="persona-clear-chat-tooltip-arrow",W.appendChild(T);let F=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(or),W.style.left=`${F.left+F.width/2}px`,W.style.top=`${F.top-8}px`,W.style.transform="translate(-50%, -100%)",C.appendChild(W)},x=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=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}},wy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",fi=(e,t={})=>{var W,v,x,k,C,T,F,$,j,me,se,fe,ie;let{wrapperClassName:n=wy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?v:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(C=a.iconColor)!=null?C:"",m=(T=a.backgroundColor)!=null?T:"",u=(F=a.borderWidth)!=null?F:"",g=($=a.borderColor)!=null?$:"",p=(j=a.borderRadius)!=null?j:"",w=(me=a.paddingX)!=null?me:"",S=(se=a.paddingY)!=null?se:"",M=(fe=a.tooltipText)!=null?fe:"Clear chat",I=(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=Te(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),m&&(H.style.backgroundColor=m,H.classList.remove("hover:persona-bg-gray-100")),u||g){let be=u||"0px",Oe=g||"transparent";H.style.border=`${be} solid ${Oe}`,H.classList.remove("persona-border-none")}if(p&&(H.style.borderRadius=p,H.classList.remove("persona-rounded-full")),w&&(H.style.paddingLeft=w,H.style.paddingRight=w),S&&(H.style.paddingTop=S,H.style.paddingBottom=S),L.appendChild(H),I&&M){let be=null,Oe=()=>{if(be)return;let Q=H.ownerDocument,Le=Q.body;if(!Le)return;be=Eo(Q,"div","persona-clear-chat-tooltip"),be.textContent=M;let Y=Eo(Q,"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)};L.addEventListener("mouseenter",Oe),L.addEventListener("mouseleave",ve),H.addEventListener("focus",Oe),H.addEventListener("blur",ve),L._cleanupTooltip=()=>{ve(),L.removeEventListener("mouseenter",Oe),L.removeEventListener("mouseleave",ve),H.removeEventListener("focus",Oe),H.removeEventListener("blur",ve)}}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))"},Ar=e=>{var W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,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=(W=t==null?void 0:t.launcher)!=null?W:{},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 Q=parseFloat(s)||24,Le=Te(d,Q*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(T=(C=t==null?void 0:t.launcher)==null?void 0:C.agentIconText)!=null?T:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let Q=b("img");Q.src=t.launcher.iconUrl,Q.alt="",Q.className="persona-rounded-xl persona-object-cover",Q.style.height=s,Q.style.width=s,l.replaceChildren(Q)}else l.textContent=(j=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?j:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=b("span","persona-text-base persona-font-semibold");u.style.color=Mn.titleColor,u.textContent=(se=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?se:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(ie=(fe=t==null?void 0:t.launcher)==null?void 0:fe.subtitle)!=null?ie:"Here to help you get answers fast",m.append(u,g),i?o.append(m):o.append(l,m);let p=(be=r.clearChat)!=null?be:{},w=(Oe=p.enabled)!=null?Oe:!0,S=(ve=p.placement)!=null?ve:"inline",M=null,I=null;if(w){let Le=fi(t,{wrapperClassName:S==="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,S==="top-right"&&(I.style.right="48px"),S==="inline"&&o.appendChild(I)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&S==="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}=mi(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},Gs=(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 Kr(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 p of t){if(p.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",p.id),p.destructive&&w.setAttribute("data-destructive",""),p.icon){let M=Te(p.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let S=document.createElement("span");S.textContent=p.label,w.appendChild(S),w.addEventListener("click",M=>{M.stopPropagation(),m(),n(p.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let p=o.getBoundingClientRect();a.style.top=`${p.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-p.right}px`,a.style.left="auto"):(a.style.left=`${p.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let p=w=>{!a.contains(w.target)&&!o.contains(w.target)&&m()};document.addEventListener("click",p,!0),i=()=>document.removeEventListener("click",p,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():m()}function g(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:m,toggle:u,destroy:g}}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[m,u]of Object.entries(i))d.setAttribute(m,u);return d}function hl(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 m=b("button",l);if(m.type="button",m.setAttribute("aria-label",n),t){let g=Te(t,s!=null?s:14,"currentColor",2);g&&m.appendChild(g)}let u=b("span");if(u.textContent=n,m.appendChild(u),i&&m.addEventListener("click",i),d)for(let[g,p]of Object.entries(d))m.setAttribute(g,p);return m}function Ku(e){var p,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 m=b("span","persona-combo-btn-label");m.textContent=t,l.appendChild(m);let u=Te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(p=d.borderRadius)!=null?p:"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 S,M;l.style.backgroundColor=(S=d.background)!=null?S:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Kr({items:o,onSelect:S=>{l.setAttribute("aria-expanded","false"),r(S)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",S=>{S.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),l.click())}),{element:l,setLabel:S=>{m.textContent=S,l.setAttribute("aria-label",S)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let S=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Cy=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 Sy(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=Kr({items:a.menuItems,onSelect:m=>n==null?void 0:n(m),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",m=>{m.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Ay=e=>{var L,H,D,W,v,x,k,C,T;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,m;if(d)l=Ku({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,m=(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"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Mn.titleColor,m.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(m),Sy(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 u=(C=a.closeButtonSize)!=null?C:"32px",g=b("div",""),p=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");p.style.height=u,p.style.width=u,p.type="button",p.setAttribute("aria-label","Close chat"),p.style.display=n?"":"none",p.style.color=a.closeButtonColor||Mn.actionIconColor;let w=(T=a.closeButtonIconName)!=null?T:"x",S=Te(w,"28px","currentColor",1);S?p.appendChild(S):p.textContent="\xD7",o&&p.addEventListener("click",o),g.appendChild(p),i.appendChild(g);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:m,headerSubtitle:I,closeButton:p,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Gu={default:Cy,minimal:Ay},Ty=e=>{var t;return(t=Gu[e])!=null?t:Gu.default},gi=(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}),m=b("div");m.style.display="none";let u=b("span"),g=b("span"),p=b("button");p.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:m,headerTitle:u,headerSubtitle:g,closeButton:p,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Ty(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var hi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},bi=e=>{var W,v,x,k,C,T,F,$,j,me,se,fe;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},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=(C=t.tooltipText)!=null?C:"Send message",i=(T=t.stopTooltipText)!=null?T:"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",m=(se=t.showTooltip)!=null?se:!1,u=(fe=t.size)!=null?fe:"40px",g=t.backgroundColor,p=t.textColor,w=b("div","persona-send-button-wrapper"),S=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");S.type="submit",S.setAttribute("data-persona-composer-submit","");let M=null,I=null;if(n){S.style.width=u,S.style.height=u,S.style.minWidth=u,S.style.minHeight=u,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",p?S.style.color=p:S.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(u)||24,be=(p==null?void 0:p.trim())||"currentColor";r?(M=Te(r,ie,be,2),M?S.appendChild(M):S.textContent=o):S.textContent=o,I=Te(s,ie,be,2),g?S.style.backgroundColor=g:S.classList.add("persona-bg-persona-primary")}else S.textContent=d,p?S.style.color=p:S.classList.add("persona-text-white");t.borderWidth&&(S.style.borderWidth=t.borderWidth,S.style.borderStyle="solid"),t.borderColor&&(S.style.borderColor=t.borderColor),t.paddingX?(S.style.paddingLeft=t.paddingX,S.style.paddingRight=t.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),t.paddingY?(S.style.paddingTop=t.paddingY,S.style.paddingBottom=t.paddingY):(S.style.paddingTop="",S.style.paddingBottom="");let L=null;m&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,w.appendChild(L)),S.setAttribute("aria-label",a),w.appendChild(S);let H="send";return{button:S,wrapper:w,setMode:ie=>{if(ie===H)return;H=ie;let be=ie==="stop"?i:a;if(S.setAttribute("aria-label",be),L&&(L.textContent=be),n){if(M&&I){let Oe=ie==="stop"?I:M;S.replaceChildren(Oe)}}else S.textContent=ie==="stop"?l:d}}},yi=e=>{var L,H,D,W,v,x,k,C,T,F,$,j;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=(W=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?W:"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",m=(x=t.iconSize)!=null?x:a,u=parseFloat(m)||24,g=(C=t.backgroundColor)!=null?C:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,p=(F=t.iconColor)!=null?F:(T=e==null?void 0:e.sendButton)==null?void 0:T.textColor;d.style.width=m,d.style.height=m,d.style.minWidth=m,d.style.minHeight=m,d.style.fontSize="18px",d.style.lineHeight="1",p?d.style.color=p:d.style.color="var(--persona-text, #111827)";let S=Te(l,u,p||"currentColor",1.5);S?d.appendChild(S):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let 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}},vi=e=>{var w,S,M,I,L,H,D,W;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(M=(S=e==null?void 0:e.sendButton)==null?void 0:S.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=((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,m=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Te(i,m,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",p=b("div","persona-send-button-tooltip");return p.textContent=g,s.appendChild(p),{button:a,wrapper:s,input:r,previewsContainer:o}},xi=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},wi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ci=e=>{var w,S,M,I,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=wi(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=hi(t);a();let i=bi(t),d=yi(t),l=vi(t),m=xi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let u=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),p=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&p.append(d.wrapper),p.append(i.wrapper),u.append(g,p),r.append(u),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,m),{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:(S=d==null?void 0:d.wrapper)!=null?S:null,statusText:m,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:u,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Yu=()=>{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}},Xu=e=>{var w,S,M,I,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=wi();o.style.display="none";let r=xi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=hi(t);s.style.maxHeight="100px",a();let i=bi(t),d=yi(t),l=vi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let m=b("form","persona-widget-composer persona-pill-composer");m.setAttribute("data-persona-composer-form",""),m.style.outline="none";let u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),m.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&&m.append(l.input),m.append(u,s,g),l&&n.append(l.previewsContainer),n.append(m,o,r);let p=m;return{footer:n,suggestions:o,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(S=d==null?void 0:d.wrapper)!=null?S: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:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:p,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Qu=e=>{var m,u,g,p,w,S,M,I,L,H,D,W,v,x,k,C,T;let t=(u=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?u:!0,n=pn(e);if(js(e)){let F=(p=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?p:{},$=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=(S=e==null?void 0:e.launcher)==null?void 0:S.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=(L=e==null?void 0:e.launcher)==null?void 0:L.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=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?W:"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=(T=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?T: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}},ky=(e,t)=>{var D,W,v,x,k,C,T,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}=mi(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=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:W.enabled)!=null?v:!0,a=null,i=null;if(s){let j=fi(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 m=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");m.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",m.setAttribute("data-persona-intro-card","");let u=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(T=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",m.append(u,g);let p=b("div","persona-flex persona-flex-col persona-gap-3"),w=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;w&&(p.style.maxWidth=w,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,p);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=Xu({config:e}),{root:L,textNode:H}=Yu();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:p,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:u,introSubtitle:g,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:L,peekTextNode:H}},Ju=(e,t=!0)=>{var M,I,L,H,D,W,v,x,k;if(js(e))return ky(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?gi(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=(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=(W=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let m=b("div","persona-flex persona-flex-col persona-gap-3"),u=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;u&&(m.style.maxWidth=u,m.style.marginLeft="auto",m.style.marginRight="auto",m.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,m);let p=Ci({config:e}),w=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?Gs(n,s,e):(s.header.style.display="none",Gs(n,s,e)),n.append(a);let S=b("div","persona-composer-overlay persona-pointer-events-none");return S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20",w||(p.footer.style.display="none"),n.append(p.footer),n.append(S),{container:n,body:a,messagesWrapper:m,composerOverlay:S,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.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:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions,setSendButtonMode:p.setSendButtonMode}};var Ey=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}},My=(e,t)=>{if(!e)return null;let n=Ey(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ly=(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},Iy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},yl=320,em=320,Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Wy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),By=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Hy=(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 u;let l=b("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${yl}px`,l.style.maxHeight=`${em}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let m=!1;r+=1,l.addEventListener("error",()=>{m||(m=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{m=!0}),Iy(i.image)?(l.src=i.image,o.appendChild(l)):(m=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),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","audio");let n=0;return e.forEach(o=>{if(!bl(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=`${yl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Fy=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(!bl(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=`${yl}px`,r.style.maxHeight=`${em}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Oy=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(!bl(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}},Ys=()=>{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},Ny=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ys};if(t){let r=t(o);if(r!==null)return r}return Ys()},_y=(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},Zu=(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},Vy=(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 p,w,S,M,I,L;let o=(p=t.showCopy)!=null?p:!0,r=(w=t.showUpvote)!=null?w:!0,s=(S=t.showDownvote)!=null?S:!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=(L=t.layout)!=null?L:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${m} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let g=(H,D,W)=>{let v=bn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",W),v};return o&&u.appendChild(g("copy","Copy message","copy")),r&&u.appendChild(g("thumbs-up","Upvote","upvote")),s&&u.appendChild(g("thumbs-down","Downvote","downvote")),u},vl=(e,t,n,o,r,s)=>{var Q,Le,Y,xe,Se,de,we,ze,te,ne,re,nt,ye,le,Ue,He,ce;let a=n!=null?n:{},i=(Q=a.layout)!=null?Q:"bubble",d=a.avatar,l=a.timestamp,m=(Le=d==null?void 0:d.show)!=null?Le:!1,u=(Y=l==null?void 0:l.show)!=null?Y:!1,g=(xe=d==null?void 0:d.position)!=null?xe:"left",p=(Se=l==null?void 0:l.position)!=null?Se:"below",w=Vy(e.role,i),S=b("div",w.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Ry(e),I=(we=(de=e.content)==null?void 0:de.trim())!=null?we:"",H=M.length>0&&I===Ja,D=ci((te=(ze=s==null?void 0:s.widgetConfig)==null?void 0:ze.features)==null?void 0:te.streamAnimation),W=(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,W):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)&&S.classList.add(v.bubbleClass);let C=document.createElement("div");C.classList.add("persona-message-content"),k&&v&&(v.containerClass&&C.classList.add(v.containerClass),C.style.setProperty("--persona-stream-step",`${D.speed}ms`),C.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let T=k?di((le=e.content)!=null?le:"",D.buffer,v,e,!!e.streaming):(Ue=e.content)!=null?Ue:"",F=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;k&&(v==null?void 0:v.wrap)==="char"?$=Us(F,"char",e.id,{skipTags:v.skipTags}):k&&(v==null?void 0:v.wrap)==="word"&&($=Us(F,"word",e.id,{skipTags:v.skipTags}));let j=null;if(H?(j=document.createElement("div"),j.innerHTML=$,j.style.display="none",C.appendChild(j)):C.innerHTML=$,k&&(v!=null&&v.useCaret)&&!H&&I){let G=pi(),Ve=C.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=Ve[Ve.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(G,Et.nextSibling);else{let pe=C.lastElementChild;pe?pe.appendChild(G):C.appendChild(G)}}if(u&&p==="inline"&&e.createdAt){let G=Zu(e,l);G.classList.add("persona-ml-2","persona-inline"),C.appendChild(G)}if(M.length>0){let G=Hy(M,!H&&!!I,()=>{H&&j&&(j.style.display="")});G?S.appendChild(G):H&&j&&(j.style.display="")}let me=Py(e);if(me.length>0){let G=Dy(me);G&&S.appendChild(G)}let se=Wy(e);if(se.length>0){let G=Fy(se);G&&S.appendChild(G)}let fe=By(e);if(fe.length>0){let G=Oy(fe);G&&S.appendChild(G)}if(S.appendChild(C),u&&p==="below"&&e.createdAt){let G=Zu(e,l);G.classList.add("persona-mt-1"),S.appendChild(G)}let ie=e.role==="assistant"?My(e.stopReason,(ce=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(T&&T.trim()),Ve=D.placeholder==="skeleton",Et=Ve&&D.buffer==="line"&&G;if(G)Et&&S.appendChild(zs());else if(Ve)S.appendChild(zs());else{let pe=Ny("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);pe&&S.appendChild(pe)}}if(ie&&e.stopReason&&!e.streaming&&(I||(C.style.display="none"),S.appendChild(Ly(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let G=$y(e,o,r);S.appendChild(G)}if(!m||e.role==="system")return S;let Oe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=_y(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Oe.append(S,ve):Oe.append(ve,S),S.classList.remove("persona-max-w-[85%]"),S.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Oe};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 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
|
-
`):""},
|
|
25
|
-
`);let r=
|
|
26
|
-
`):""},Ky=(e,t)=>{var m,u,g,p,w;let n=e.toolCall,o=(m=t==null?void 0:t.features)==null?void 0:m.toolCallDisplay,r=(u=o==null?void 0:o.collapsedMode)!=null?u:"tool-call",s=jy(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Tu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(p=t==null?void 0:t.toolCall)!=null?p:{},l=a;return r==="tool-name"?l=((w=n.name)==null?void 0:w.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=il(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=il(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},nm=(e,t,n)=>{var m;let o=Yr.has(e),r=(m=n==null?void 0:n.toolCall)!=null?m:{},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 u=r.toggleTextColor||r.headerTextColor||"currentColor",g=Te(o?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},wl=(e,t)=>{var $,j,me,se,fe,ie,be,Oe,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&&Yr.has(e.id),{summary:d,previewText:l,isActive:m}=Ky(e,t),u=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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(p.style.color=o.headerTextColor);let w=String((se=n.startedAt)!=null?se:Date.now()),S=()=>{let Q=b("span","");return Q.setAttribute("data-tool-elapsed",w),Q.textContent=Ps(n),Q},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(fe=s.collapsedMode)!=null?fe:"tool-call",isActive:m,config:t!=null?t:{},elapsed:Ps(n),createElapsedElement:S});typeof M=="string"&&M.trim()?(p.textContent=M,g.appendChild(p)):M instanceof HTMLElement?g.appendChild(M):(p.textContent=d,g.appendChild(p));let I=(be=s.loadingAnimation)!=null?be:"none",L=o.activeTextTemplate,H=o.completeTextTemplate,D=m?L:H,W=M instanceof HTMLElement,v=(Q,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,Q.appendChild(de),xe++}return xe},x=(Q,Le)=>{var de;p.textContent="";let Y=((de=n.name)==null?void 0:de.trim())||"tool",xe=Ga(Q,Y),Se=0;for(let we of xe){let ze=we.styles.length>0?(()=>{let te=b("span",we.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return p.appendChild(te),te})():p;if(we.isDuration&&m)ze.appendChild(S());else{let te=we.isDuration?Ps(n):we.text;Le?Se=v(ze,te,Se):ze.appendChild(document.createTextNode(te))}}};if(!W)if(m&&I!=="none"){let Q=(Oe=o.loadingAnimationDuration)!=null?Oe:2e3;if(p.setAttribute("data-preserve-animation","true"),I==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),D&&x(D,!1);else if(p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let Le=p.textContent||d;p.textContent="",v(p,Le,0)}}else D&&x(D,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,Q,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),u.append(g,Y)}else u.append(g);let C=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(C.setAttribute("data-persona-collapsed-preview","tool"),C.style.display="none",C.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&l){let Q=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});qy(C,Q)||(C.textContent=l),C.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,C),r;let T=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(T.style.display=i?"":"none",o.contentBackgroundColor&&(T.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(T.style.color=o.contentTextColor),o.contentPaddingX&&(T.style.paddingLeft=o.contentPaddingX,T.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(T.style.paddingTop=o.contentPaddingY,T.style.paddingBottom=o.contentPaddingY),n.name){let Q=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Q.style.color=o.contentTextColor:o.headerTextColor&&(Q.style.color=o.headerTextColor),Q.textContent=n.name,T.appendChild(Q)}if(n.args!==void 0){let Q=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=jr(n.args),Q.append(Le,Y),T.appendChild(Q)}if(n.chunks&&n.chunks.length){let Q=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(""),Q.append(Le,Y),T.appendChild(Q)}if(n.status==="complete"&&n.result!==void 0){let Q=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=jr(n.result),Q.append(Le,Y),T.appendChild(Q)}if(n.status==="complete"&&typeof n.duration=="number"){let Q=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Q.style.color=o.contentTextColor),Q.textContent=`Duration: ${n.duration}ms`,T.appendChild(Q)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,Q,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",C.style.display=i?"none":C.textContent||C.childNodes.length?"":"none"})(),r.append(u,C,T),r};import{parse as Gy,ARR as Yy,OBJ as Xy,STR as Qy}from"partial-json";var Jy="ask_user_question",Cl=8,Xr="data-persona-ask-sheet-for",Zy="Other",ev="Other\u2026",rm="Type your own answer here",sm="Send",tv="Next",nv="Back",ov="Submit all",rv="Skip",sv=3,Sl="data-ask-current-index",Al="data-ask-question-count",am="data-ask-answers",Tl="data-ask-grouped",im="data-ask-layout",av=e=>e.layout==="pills"?"pills":"rows",iv=e=>e.getAttribute(im)==="pills"?"pills":"rows",om=!1,lm=e=>e.replace(/["\\]/g,"\\$&"),Tr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Jy,kl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Qr=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=Gy(r,Qy|Xy|Yy);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Xs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Cl&&!om&&(om=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cl}.`)),t.slice(0,Cl)},lv=e=>{var t;return(t=Xs(e)[0])!=null?t:null},cv=(e,t)=>{var n;return(n=Xs(e)[t])!=null?n:null},dv=(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))},cm=(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},pv=(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=cm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},uv=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},mv=(e,t,n,o)=>{var m,u,g;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<sv;p++)s.appendChild(uv(o));return s}if(d.forEach((p,w)=>{s.appendChild(pv(p,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let p=o==="rows"?Zy:ev;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 S=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=(m=t.freeTextPlaceholder)!=null?m:rm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:p),S.appendChild(M),w.appendChild(S);let I=cm(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=(g=t.freeTextLabel)!=null?g:p,s.appendChild(w)}}return s},dm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:rm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:sm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},fv=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:sm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},gv=(e,t,n)=>{var l,m,u,g;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:nv,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=(m=n.skipLabel)!=null?m:rv,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?(u=n.submitAllLabel)!=null?u:ov:(g=n.nextLabel)!=null?g:tv,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(am);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},pm=(e,t)=>{e.setAttribute(am,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(Sl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},hv=(e,t)=>{e.setAttribute(Sl,String(Math.max(0,Math.floor(t))))},Jr=e=>{var n;let t=Number((n=e.getAttribute(Al))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},sr=e=>e.getAttribute(Tl)==="true",bv=(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},yv=(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)))},Si=(e,t)=>{let{payload:n}=Qr(t),o=Xs(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},um=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 u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",m=r.has(l);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});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=""},mm=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}},El=(e,t,n)=>{let o=kl(n),r=iv(e),{payload:s,complete:a}=Qr(t),i=sr(e),d=lo(e),l=Jr(e),m=i?cv(s,d):lv(s),u=!!(m!=null&&m.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let p=e.querySelector('[data-ask-stepper="true"]');p&&p.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let L=typeof(m==null?void 0:m.question)=="string"?m.question:"";w.textContent=L,w.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let L=mv(m,o,a,r);S.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(dm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(fv(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=gv(d,l,o);I?I.replaceWith(L):e.appendChild(L)}else I&&I.remove();um(e),mm(e)},vv=(e,t,n)=>{let o=kl(t),r=av(o),s=e.toolCall.id,a=Xs(n),i=Math.max(1,a.length),d=i>1,l=bv(e,a),m=d?yv(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Xr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Al,String(i)),u.setAttribute(Sl,String(m)),u.setAttribute(Tl,d?"true":"false"),u.setAttribute(im,r),pm(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),dv(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),p=b("div","persona-ask-sheet-question persona-flex-1");p.setAttribute("data-ask-question","true"),p.textContent="",g.appendChild(p);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",g.appendChild(w),u.appendChild(g);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"),u.appendChild(M),r!=="rows"&&u.appendChild(dm(o,r)),El(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},xv=(e,t,n)=>{let{payload:o}=Qr(t),r=Math.max(1,Xs(o).length);r>Jr(e)&&(e.setAttribute(Al,String(r)),r>1&&!sr(e)&&e.setAttribute(Tl,"true")),El(e,t,n)};var Ai=(e,t,n)=>{if(!n||!Tr(e)||kl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Xr}]`).forEach(l=>{l.getAttribute(Xr)!==r&&l.remove()});let a=n.querySelector(`[${Xr}="${lm(r)}"]`);if(a){xv(a,e,t);return}let{payload:i}=Qr(e),d=vv(e,t,i);n.appendChild(d)},Zr=(e,t)=>{if(!e)return;let n=t?`[${Xr}="${lm(t)}"]`:`[${Xr}]`;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)})},Ml=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,pm(e,n),um(e),mm(e)},Ti=(e,t,n,o)=>{let r=Jr(e),s=Math.max(0,Math.min(r-1,o));hv(e,s),El(e,t,n)};var Ll=(e,t)=>{var S,M,I,L,H,D,W,v,x,k,C,T;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=(S=o==null?void 0:o.backgroundColor)!=null?S:"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",m=Te(d,20,l,2);m&&i.appendChild(m);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),p=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(p.style.color=o.titleColor),p.textContent=(L=o==null?void 0:o.title)!=null?L:"Approval Required",g.appendChild(p),!r){let F=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",n.status),n.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):n.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):n.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),g.appendChild(F)}u.appendChild(g);let w=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(w.style.color=o.descriptionColor),w.textContent=n.description,u.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=jr(n.parameters),u.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,(W=o==null?void 0:o.approveButtonTextColor)!=null?W:"#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 fe=Te("shield-x",14,(C=o==null?void 0:o.denyButtonTextColor)!=null?C:"var(--persona-feedback-error, #dc2626)",2);fe&&(fe.style.marginRight="4px",se.appendChild(fe));let ie=document.createTextNode((T=o==null?void 0:o.denyLabel)!=null?T:"Deny");se.appendChild(ie),F.append($,se),u.appendChild(F)}return a.append(i,u),s.appendChild(a),s};var fm=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(p=>p.role==="user"))return;let m=document.createDocumentFragment(),u=r?r.isStreaming():!1,g=p=>{switch(p){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(p=>{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=p,w.disabled=u,i!=null&&i.fontFamily&&(w.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(p))}),m.appendChild(w),t.push(w)}),e.appendChild(m)}}};var Qs=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 Js=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 wv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Cv=new Set(["step_start","execution_start"]),Sv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Av=new Set(["step_complete","agent_turn_complete"]),Tv=new Set(["flow_complete","agent_complete"]),gm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),bm=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 bm(n)?n:void 0};function Il(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ki(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function kv(e,t){return typeof t.type=="string"?t.type:e}function Ev(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 Mv(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 hm(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 Lv(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 Iv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Iv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ki(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!bm(n)){gm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=kv(t,n),r=this.now();if(wv.has(o)){this.startRun(r);return}if(Cv.has(o)){this.run||this.startRun(r);return}if(Sv.has(o)){if(!Mv(o,n))return;let a=Ev(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+Il(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ki(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Av.has(o)){if(!this.run)return;let a=this.run,i=hm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Il(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:ki(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(Tv.has(o)){if(!this.run)return;let a=this.run,i=hm(n),d=i!=null?i:a.exactOutputTokens+Il(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:ki(d,m),outputTokens:d,durationMs:m,source:l},this.run=null;return}if(gm.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=Lv(n);return s!=null?s:o-t.startedAt}};function es(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Rv={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)"}},Pv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Wv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Bv=100;function Hv(e,t){let n={...Rv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Pv}function Dv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Fv(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 Ov(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 Nv(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 _v(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 Vv(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 Uv(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 Rl(e,t,n,o,r,s,a,i){var g;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");es(l,(g=o.classNames)==null?void 0:g.eventRow);let m=a.find(p=>p.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let p=m.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(p)return l.appendChild(p),l}return l.appendChild(u()),l;function u(){var $,j;let p=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 S=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&&S.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]"),L=($=o.timestampFormat)!=null?$:"relative";I.textContent=L==="relative"?Dv(e.timestamp,n):Fv(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=Hv(e.type,o.badgeColors),W=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");W.style.backgroundColor=D.bg,W.style.color=D.text,W.style.borderColor=D.text+"50",W.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Wv,x=Ov(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 C=b("div","persona-flex-1 persona-min-w-0"),T=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&&T.appendChild(F),T.addEventListener("click",async me=>{me.stopPropagation(),await Nv(_v(e)),T.innerHTML="";let se=Te("check","12px","currentColor",1.5);se&&T.appendChild(se),setTimeout(()=>{T.innerHTML="";let fe=Te("clipboard","12px","currentColor",1.5);fe&&T.appendChild(fe)},1500)}),w.appendChild(S),w.appendChild(I),H&&w.appendChild(H),w.appendChild(W),k&&w.appendChild(k),w.appendChild(C),w.appendChild(T),p.appendChild(w),d&&p.appendChild(Uv(e,a,i)),p}}function ym(e){var w,S,M,I,L;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=(S=i==null?void 0:i.iconName)!=null?S:"arrow-down",m=(M=i==null?void 0:i.label)!=null?M:"",u=(L=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?L:{},g=s.find(H=>H.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let H=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>p().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return p();function p(){let H=u.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");es(D,H==null?void 0:H.panel);let W=[],v="",x="",k=null,C=[],T={},F=0,$=ai(),j=0,me=0,se=!1,fe=null,ie=!1,be=0,Oe=new Set,ve=new Map,Q="",Le="",Y=null,xe,Se,de,we,ze,te=null,ne=null,re=null;function nt(){let oe=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ge=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");es(ge,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),ge.appendChild(xt),ge.appendChild(xe),ne&&ge.appendChild(ne),ge.appendChild($t),ge.appendChild(Se),ge.appendChild(de);let gt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");es(gt,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"),es(we,H==null?void 0:H.searchInput),we.type="text",we.placeholder="Search event payloads...",ze=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"),ze.type="button",ze.style.display="none";let et=Te("x","12px","currentColor",2);return et&&ze.appendChild(et),gt.appendChild(zt),gt.appendChild(we),gt.appendChild(ze),oe.appendChild(ge),oe.appendChild(gt),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:ge=>{v=ge,Dn(),_()},onSearchChange:ge=>{x=ge,Dn(),_()}});ye=oe!=null?oe:nt()}else ye=nt();let Ue=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");Ue.style.display="none";function He(){if(!a||!te||!ne)return;let oe=a();te.textContent=Vv(oe);let ge=$v(oe);re&&(re.textContent=ge,ge||(re.style.display="none")),ge?ne.setAttribute("aria-label",ge):ne.removeAttribute("aria-label")}let ce=b("div","persona-flex-1 persona-min-h-0 persona-relative"),G=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.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");es(Ve,H==null?void 0:H.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Et=Te(l,"14px","currentColor",2);Et&&Ve.appendChild(Et);let pe=b("span","");pe.textContent=m,Ve.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(G),ce.appendChild(ae),ce.appendChild(Ve),D.setAttribute("tabindex","0"),D.appendChild(ye),D.appendChild(Ue),D.appendChild(ce);function Ln(){let oe=t.getAll(),ge={};for(let wt of oe)ge[wt.type]=(ge[wt.type]||0)+1;let xt=Object.keys(ge).sort(),$t=xt.length!==C.length||!xt.every((wt,gt)=>wt===C[gt]),Jt=!$t&&xt.some(wt=>ge[wt]!==T[wt]),yn=oe.length!==Object.values(T).reduce((wt,gt)=>wt+gt,0);if(!$t&&!Jt&&!yn||(C=xt,T=ge,!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 gt=b("option","");gt.value=wt,gt.textContent=`${wt} (${ge[wt]||0})`,Se.appendChild(gt)}Tt&&xt.includes(Tt)?Se.value=Tt:Tt&&(Se.value="",v="")}else for(let wt=1;wt<Se.options.length;wt++){let gt=Se.options[wt];gt.textContent=`${gt.value} (${ge[gt.value]||0})`}}function Nt(){let oe=t.getAll();if(v&&(oe=oe.filter(ge=>ge.type===v)),x){let ge=x.toLowerCase();oe=oe.filter(xt=>xt.type.toLowerCase().includes(ge)||xt.payload.toLowerCase().includes(ge))}return oe}function ln(){return v!==""||x!==""}function Dn(){F=0,j=0,$.resume(),Ve.style.display="none"}function Jn(oe){Oe.has(oe)?Oe.delete(oe):Oe.add(oe),Y=oe;let ge=G.scrollTop,xt=$.isFollowing();ie=!0,$.pause(),_(),G.scrollTop=ge,xt&&$.resume(),ie=!1}function qe(){return _s(G,50)}function _(){me=Date.now(),se=!1,He(),Ln();let oe=t.getEvictedCount();oe>0?(Ue.textContent=`${oe.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",W=Nt();let ge=W.length,xt=t.getSize()>0;xe&&(xe.textContent=String(t.getSize())),ge===0&&xt&&ln()?(ae.textContent=x?`No events matching '${x}'`:"No events matching filter",ae.style.display="",G.style.display="none"):(ae.style.display="none",G.style.display=""),de&&(de.title=ln()?`Copy Filtered (${ge})`:"Copy All"),d&&!$.isFollowing()&&ge>F&&(j+=ge-F,pe.textContent=m?`${m}${j>0?` (${j})`:""}`:"",Ve.style.display=""),F=ge;let $t=t.getAll(),Jt=$t.length>0?$t[0].timestamp:0,yn=new Set(W.map(gt=>gt.id));for(let gt of Oe)yn.has(gt)||Oe.delete(gt);let Tt=v!==Q||x!==Le,wt=ve.size===0&&W.length>0;if(Tt||wt||W.length===0){G.innerHTML="",ve.clear();let gt=document.createDocumentFragment();for(let bt=0;bt<W.length;bt++){let zt=Rl(W[bt],bt,Jt,u,Oe,Jn,s,r);ve.set(W[bt].id,zt),gt.appendChild(zt)}G.appendChild(gt),Q=v,Le=x,Y=null}else{if(Y!==null){let bt=ve.get(Y);if(bt&&bt.parentNode===G){let zt=W.findIndex(et=>et.id===Y);if(zt>=0){let et=Rl(W[zt],zt,Jt,u,Oe,Jn,s,r);G.insertBefore(et,bt),bt.remove(),ve.set(Y,et)}}Y=null}let gt=new Set(W.map(bt=>bt.id));for(let[bt,zt]of ve)gt.has(bt)||(zt.remove(),ve.delete(bt));for(let bt=0;bt<W.length;bt++){let zt=W[bt];if(!ve.has(zt.id)){let et=Rl(zt,bt,Jt,u,Oe,Jn,s,r);ve.set(zt.id,et),G.appendChild(et)}}}$.isFollowing()&&(G.scrollTop=G.scrollHeight)}function ke(){if(Date.now()-me>=Bv){fe!==null&&(cancelAnimationFrame(fe),fe=null),_();return}se||(se=!0,fe=requestAnimationFrame(()=>{fe=null,_()}))}let De=(oe,ge)=>{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},ge)},Fe=async()=>{if(de){de.disabled=!0;try{let oe;ln()?oe=W:n?(oe=await n(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let ge=oe.map(xt=>{try{return JSON.parse(xt.payload)}catch{return xt.payload}});await navigator.clipboard.writeText(JSON.stringify(ge,null,2)),De("check",1500)}catch{De("x",1500)}}},$e=()=>{Se&&(v=Se.value,Dn(),_())},dt=()=>{!we||!ze||(ze.style.display=we.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=we.value,Dn(),_()},150))},ot=()=>{!we||!ze||(we.value="",x="",ze.style.display="none",k&&clearTimeout(k),Dn(),_())},At=()=>{if(ie)return;let oe=G.scrollTop,{action:ge,nextLastScrollTop:xt}=ii({following:$.isFollowing(),currentScrollTop:oe,lastScrollTop:be,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=xt,ge==="resume"?($.resume(),j=0,Ve.style.display="none"):ge==="pause"&&($.pause(),d&&(pe.textContent=m,Ve.style.display=""))},Vt=oe=>{let ge=li({following:$.isFollowing(),deltaY:oe.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});ge==="pause"?($.pause(),d&&(pe.textContent=m,Ve.style.display="")):ge==="resume"&&($.resume(),j=0,Ve.style.display="none")},q=()=>{d&&(G.scrollTop=G.scrollHeight,$.resume(),j=0,Ve.style.display="none")},_t=oe=>{let ge=oe.target;if(!ge||ge.closest("button"))return;let xt=ge.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",Fe),Se&&Se.addEventListener("change",$e),we&&we.addEventListener("input",dt),ze&&ze.addEventListener("click",ot),G.addEventListener("scroll",At),G.addEventListener("wheel",Vt,{passive:!0}),G.addEventListener("click",_t),Ve.addEventListener("click",q),D.addEventListener("keydown",Qe);function Ft(){k&&clearTimeout(k),fe!==null&&(cancelAnimationFrame(fe),fe=null),se=!1,ve.clear(),de&&de.removeEventListener("click",Fe),Se&&Se.removeEventListener("change",$e),we&&we.removeEventListener("input",dt),ze&&ze.removeEventListener("click",ot),G.removeEventListener("scroll",At),G.removeEventListener("wheel",Vt),G.removeEventListener("click",_t),Ve.removeEventListener("click",q),D.removeEventListener("keydown",Qe)}return{element:D,update:ke,destroy:Ft}}}function vm(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 m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let p=document.createElement("span");p.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(p)}else u.textContent=a;if(l.append(m,u),i.append(d,l),r==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var xm=(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",m=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>vm(e,t)});if(m)return m}return vm(e,t)};var Pl=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 Pl;Mr.register("PersonaArtifactCard",xm);function zv(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 wm(e,t){var Se,de,we,ze;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=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?$a(e.markdown):null,i=Ua(e.sanitize),d=te=>{let ne=a?a(te):Is(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,m=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let u=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");u.setAttribute("data-persona-theme-zone","artifact-pane"),r&&u.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&g.classList.add("persona-artifact-toolbar-document");let p=b("span","persona-text-xs persona-font-medium persona-truncate");p.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;m(),(te=t.onDismiss)==null||te.call(t)});let S="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"}),L=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,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(W&&v&&v.length>0),k=null,C,T=null,F=null;if(r&&(D||W)&&!x){if(C=D?hl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let te=Te("chevron-down",14,"currentColor",2);te&&C.appendChild(te)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),C=D?hl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=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(C,T)):r?C=bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):C=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,Ue;let te=(ye=ve.find(He=>He.id===Q))!=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"&&(Ue=te.markdown)!=null?Ue:"",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===Q))!=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(C.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()}),T&&(v!=null&&v.length)){let te=()=>{var re;return(re=u.closest("[data-persona-root]"))!=null?re:document.body},ne=()=>{F=Kr({items:v.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:nt,jsonPayload:ye,id:le}=me(),Ue=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ue?await Ue({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:T,position:"bottom-right",portal:te()})};u.isConnected?ne():requestAnimationFrame(ne),T.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;m(),(te=t.onDismiss)==null||te.call(t)});let fe=()=>{r&&(I.setAttribute("aria-pressed",S==="rendered"?"true":"false"),L.setAttribute("aria-pressed",S==="source"?"true":"false"))};I.addEventListener("click",()=>{S="rendered",fe(),Y()}),L.addEventListener("click",()=>{S="source",fe(),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?(g.replaceChildren(),M.append(I,L),k?H.append(k,$,j):H.append(C,$,j),g.append(M,ie,H),fe()):(g.appendChild(p),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.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"),Oe=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,Oe.style.padding=s),u.appendChild(g),u.appendChild(be),u.appendChild(Oe);let ve=[],Q=null,Le=!1,Y=()=>{var nt,ye,le,Ue;let te=r&&ve.length<=1;be.classList.toggle("persona-hidden",te),be.replaceChildren();for(let He 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=He.title||He.id.slice(0,8),He.id===Q&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(He.id)),be.appendChild(ce)}Oe.replaceChildren();let ne=Q&&ve.find(He=>He.id===Q)||ve[ve.length-1];if(!ne)return;if(r){let He=ne.artifactType==="markdown"?"MD":(nt=ne.component)!=null?nt:"Component",G=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${G} \xB7 ${He}`}else p.textContent="Artifacts";if(ne.artifactType==="markdown"){if(r&&S==="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:"",Oe.appendChild(ce);return}let He=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");He.innerHTML=d((le=ne.markdown)!=null?le:""),Oe.appendChild(He);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 G=re((Ue=ne.props)!=null?Ue:{},ce);if(G){Oe.appendChild(G);return}}catch{}}Oe.appendChild(zv(ne))},xe=()=>{var ne;let te=ve.length>0;if(u.classList.toggle("persona-hidden",!te),l){let re=typeof u.closest=="function"?u.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"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(te){var ne,re,nt;ve=te.artifacts,Q=(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"),u.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 Cm(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 qv(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 Ei(e,t){var d,l,m,u,g,p,w,S,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"),qv(e),Cm(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",(m=n==null?void 0:n.splitGap)!=null?m:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(p=n==null?void 0:n.paneBackground)==null?void 0:p.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=(S=n==null?void 0:n.documentToolbarIconColor)==null?void 0:S.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"),Cm(e,t)}var Sm=["panel","seamless"];function Mi(e,t){var i,d,l,m,u,g;for(let p of Sm)e.classList.remove(`persona-artifact-appearance-${p}`);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=Sm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(m=n==null?void 0:n.paneBorderRadius)==null?void 0:m.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let p=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;p&&e.style.setProperty("--persona-artifact-unified-outer-radius",p)}}function Am(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 jv(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 Kv(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 Gv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Yv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Tm(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 km(e,t,n,o,r,s){let a=jv(r,200),i=Yv(t,n,o,200);i=Math.max(a,i);let d=Kv(s);return d!==null&&(i=Math.min(i,d)),Gv(e,a,i)}var Em={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"}},Wl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,S,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(S=Em[a])!=null?S:Em.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 m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var v,x;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${I.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=I.label,L.appendChild(H);let D=(v=I.type)!=null?v:"text",W;D==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=D),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${I.name}`,W.name=I.name,W.placeholder=(x=I.placeholder)!=null?x:"",I.required&&(W.required=!0),L.appendChild(W),m.appendChild(L)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),p=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");p.type="submit",p.textContent=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(g),u.appendChild(p),m.appendChild(u),s.replaceChildren(d,m),m.addEventListener("submit",async I=>{var W,v;I.preventDefault();let L=(W=n.formEndpoint)!=null?W:"/form",H=new FormData(m),D={};H.forEach((x,k)=>{D[k]=x}),D.type=a,p.disabled=!0,g.textContent="Submitting\u2026";try{let x=await fetch(L,{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();g.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){g.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{p.disabled=!1}})})};var Bl=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()}},Hl=new Bl;var Mm=()=>{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 Xv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Qv=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},Fl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Xv(e),n=Qv(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}},Dl=e=>typeof e=="string"?e:e==null?"":String(e),ea={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Dl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Dl(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:Dl(n.text)}}},Lm=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ol=e=>{let t=new Set(Lm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Lm(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,m)=>l||(m==null?void 0:m({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 m=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:m});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:n}};var Jv=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}},Zv=e=>e.map(t=>({...t,streaming:!1})),ex=e=>e.map(t=>({...t,status:"complete"})),Im=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Jv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Zv(n.messages):void 0,artifacts:n.artifacts?ex(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 G0,STR as Y0,OBJ as X0}from"partial-json";function Rm(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 Pm(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 Wm(e){let t=Pm(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 Bm(e){let t=Pm(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 tx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hm(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=tx}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let p=document.createElement("div");p.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,p.appendChild(w);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,p.appendChild(S),g.appendChild(p);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=`
|
|
23
|
+
`,n.addEventListener("click",t);let o=s=>{var P,H,W,x,w,k,S,A,N,$,G,fe,ge;let a=(P=s.launcher)!=null?P:{},i=hn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let se=(H=a.title)!=null?H:"Chat Assistant";d.textContent=se,d.setAttribute("title",se)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let se=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=se,l.setAttribute("title",se)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let se=(x=a.agentIconSize)!=null?x:"40px";if(p.style.height=se,p.style.width=se,p.innerHTML="",a.agentIconName){let ke=parseFloat(se)||24,be=Ee(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);be?(p.appendChild(be),p.style.display=""):(p.textContent=(w=a.agentIconText)!=null?w:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let se=(S=a.agentIconSize)!=null?S:"40px";f.style.height=se,f.style.width=se,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 se=(A=a.callToActionIconSize)!=null?A:"32px";u.style.height=se,u.style.width=se,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 ke=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,ke=(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 be=parseFloat(se)||24,Fe=Math.max(be-ke,8),xe=Ee(a.callToActionIconName,Fe,"currentColor",2);xe?u.appendChild(xe):u.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else u.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let C=a.position&&ko[a.position]?ko[a.position]:ko["bottom-right"],v="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",E="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?E:`${v} ${C}`,i||(n.style.zIndex=String((G=a.zIndex)!=null?G:wn));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(fe=a.border)!=null?fe:L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(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 Wy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",fi=(e,t={})=>{var v,E,L,I,P,H;let{showClose:n=!0,wrapperClassName:o=Wy,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=r!=null?r:a.closeButtonSize)!=null?E:"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 m=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let f=(P=a.closeButtonIconName)!=null?P:"x",u=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||In.actionIconColor;let C=Ee(f,s,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):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 W=a.closeButtonBorderWidth||"0px",x=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${x}`,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&&m){let W=null,x=()=>{if(W)return;let k=l.ownerDocument,S=k.body;if(!S)return;W=Po(k,"div","persona-clear-chat-tooltip"),W.textContent=m;let A=Po(k,"div");A.className="persona-clear-chat-tooltip-arrow",W.appendChild(A);let N=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(ar),W.style.left=`${N.left+N.width/2}px`,W.style.top=`${N.top-8}px`,W.style.transform="translate(-50%, -100%)",S.appendChild(W)},w=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",x),d.addEventListener("mouseleave",w),l.addEventListener("focus",x),l.addEventListener("blur",w),d._cleanupTooltip=()=>{w(),d.removeEventListener("mouseenter",x),d.removeEventListener("mouseleave",w),l.removeEventListener("focus",x),l.removeEventListener("blur",w)}}return{button:l,wrapper:d}},By="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",hi=(e,t={})=>{var W,x,w,k,S,A,N,$,G,fe,ge,se,ke;let{wrapperClassName:n=By,buttonSize:o,iconSize:r="20px"}=t,a=(x=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?x:{},i=(w=o!=null?o:a.size)!=null?w:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(S=a.iconColor)!=null?S:"",m=(A=a.backgroundColor)!=null?A:"",p=(N=a.borderWidth)!=null?N:"",f=($=a.borderColor)!=null?$:"",u=(G=a.borderRadius)!=null?G:"",C=(fe=a.paddingX)!=null?fe:"",v=(ge=a.paddingY)!=null?ge:"",E=(se=a.tooltipText)!=null?se:"Clear chat",L=(ke=a.showTooltip)!=null?ke:!0,I=b("div",n),P=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");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",E),P.style.color=l||In.actionIconColor;let H=Ee(d,r,"currentColor",1);if(H&&(H.style.display="block",P.appendChild(H)),m&&(P.style.backgroundColor=m,P.classList.remove("hover:persona-bg-gray-100")),p||f){let be=p||"0px",Fe=f||"transparent";P.style.border=`${be} solid ${Fe}`,P.classList.remove("persona-border-none")}if(u&&(P.style.borderRadius=u,P.classList.remove("persona-rounded-full")),C&&(P.style.paddingLeft=C,P.style.paddingRight=C),v&&(P.style.paddingTop=v,P.style.paddingBottom=v),I.appendChild(P),L&&E){let be=null,Fe=()=>{if(be)return;let j=P.ownerDocument,de=j.body;if(!de)return;be=Po(j,"div","persona-clear-chat-tooltip"),be.textContent=E;let K=Po(j,"div");K.className="persona-clear-chat-tooltip-arrow",be.appendChild(K);let ye=P.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(ar),be.style.left=`${ye.left+ye.width/2}px`,be.style.top=`${ye.top-8}px`,be.style.transform="translate(-50%, -100%)",de.appendChild(be)},xe=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};I.addEventListener("mouseenter",Fe),I.addEventListener("mouseleave",xe),P.addEventListener("focus",Fe),P.addEventListener("blur",xe),I._cleanupTooltip=()=>{xe(),I.removeEventListener("mouseenter",Fe),I.removeEventListener("mouseleave",xe),P.removeEventListener("focus",Fe),P.removeEventListener("blur",xe)}}return{button:P,wrapper:I}};var In={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))"},Mr=e=>{var W,x,w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe;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=(W=t==null?void 0:t.launcher)!=null?W:{},s=(x=r.headerIconSize)!=null?x:"48px",a=(w=r.closeButtonPlacement)!=null?w:"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,de=Ee(d,j*.6,"currentColor",1);de?l.replaceChildren(de):l.textContent=(A=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?A:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.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=(G=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?G:"\u{1F4AC}";let m=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=In.titleColor,p.textContent=(ge=(fe=t==null?void 0:t.launcher)==null?void 0:fe.title)!=null?ge:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=In.subtitleColor,f.textContent=(ke=(se=t==null?void 0:t.launcher)==null?void 0:se.subtitle)!=null?ke:"Here to help you get answers fast",m.append(p,f),i?o.append(m):o.append(l,m);let u=(be=r.clearChat)!=null?be:{},C=(Fe=u.enabled)!=null?Fe:!0,v=(xe=u.placement)!=null?xe:"inline",E=null,L=null;if(C){let de=hi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=de.button,L=de.wrapper,v==="top-right"&&(L.style.right="48px"),v==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:H}=fi(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(H),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:P,closeButtonWrapper:H,clearChatButton:E,clearChatButtonWrapper:L}},ea=(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 Zr(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(ar)):(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 E=document.createElement("hr");a.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",u.id),u.destructive&&C.setAttribute("data-destructive",""),u.icon){let E=Ee(u.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let v=document.createElement("span");v.textContent=u.label,C.appendChild(v),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(u.id)}),a.appendChild(C)}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=C=>{!a.contains(C.target)&&!o.contains(C.target)&&m()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():m()}function f(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:m,toggle:p,destroy:f}}function Cn(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=Ee(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[m,p]of Object.entries(i))d.setAttribute(m,p);return d}function Cl(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 m=b("button",l);if(m.type="button",m.setAttribute("aria-label",n),t){let f=Ee(t,s!=null?s:14,"currentColor",2);f&&m.appendChild(f)}let p=b("span");if(p.textContent=n,m.appendChild(p),i&&m.addEventListener("click",i),d)for(let[f,u]of Object.entries(d))m.setAttribute(f,u);return m}function nm(e){var u,C;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 m=b("span","persona-combo-btn-label");m.textContent=t,l.appendChild(m);let p=Ee(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(C=d.padding)!=null?C:"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 v,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Zr({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),r(v)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",v=>{v.stopPropagation();let E=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),f.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{m.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Hy=e=>{var o;let t=Mr({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 Dy(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=Ee(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=Zr({items:a.menuItems,onSelect:m=>n==null?void 0:n(m),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",m=>{m.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Fy=e=>{var I,P,H,W,x,w,k,S,A;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,m;if(d)l=nm({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=In.titleColor,m=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=In.titleColor,m.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(m),Dy(l,r==null?void 0:r.trailingActions,(x=r==null?void 0:r.onAction)!=null?x:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=r.onTitleClick;l.addEventListener("click",G=>{G.target.closest("button")||$()}),l.addEventListener("keydown",G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),$())})}let N=r==null?void 0:r.titleRowHover;N&&(l.style.borderRadius=(w=N.borderRadius)!=null?w:"10px",l.style.padding=(k=N.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 $,G;l.style.backgroundColor=($=N.background)!=null?$:"",l.style.borderColor=(G=N.border)!=null?G:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(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=p,u.style.width=p,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||In.actionIconColor;let C=(A=a.closeButtonIconName)!=null?A:"x",v=Ee(C,"28px","currentColor",1);v?u.appendChild(v):u.textContent="\xD7",o&&u.addEventListener("click",o),f.appendChild(u),i.appendChild(f);let E=b("div");E.style.display="none";let L=b("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:m,headerSubtitle:L,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},om={default:Hy,minimal:Fy},Oy=e=>{var t;return(t=om[e])!=null?t:om.default},bi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),m=b("div");m.style.display="none";let p=b("span"),f=b("span"),u=b("button");u.style.display="none";let C=b("div");return C.style.display="none",{header:l,iconHolder:m,headerTitle:p,headerSubtitle:f,closeButton:u,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Oy(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 yi=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}},vi=e=>{var W,x,w,k,S,A,N,$,G,fe,ge,se;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(x=t.useIcon)!=null?x:!1,o=(w=t.iconText)!=null?w:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(A=t.stopTooltipText)!=null?A:"Stop generating",d=($=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?$:"Send",l=(fe=(G=e==null?void 0:e.copy)==null?void 0:G.stopButtonLabel)!=null?fe:"Stop",m=(ge=t.showTooltip)!=null?ge:!1,p=(se=t.size)!=null?se:"40px",f=t.backgroundColor,u=t.textColor,C=b("div","persona-send-button-wrapper"),v=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");v.type="submit",v.setAttribute("data-persona-composer-submit","");let E=null,L=null;if(n){v.style.width=p,v.style.height=p,v.style.minWidth=p,v.style.minHeight=p,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",u?v.style.color=u:v.style.color="var(--persona-button-primary-fg, #ffffff)";let ke=parseFloat(p)||24,be=(u==null?void 0:u.trim())||"currentColor";r?(E=Ee(r,ke,be,2),E?v.appendChild(E):v.textContent=o):v.textContent=o,L=Ee(s,ke,be,2),f?v.style.backgroundColor=f:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,u?v.style.color=u:v.classList.add("persona-text-white");t.borderWidth&&(v.style.borderWidth=t.borderWidth,v.style.borderStyle="solid"),t.borderColor&&(v.style.borderColor=t.borderColor),t.paddingX?(v.style.paddingLeft=t.paddingX,v.style.paddingRight=t.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),t.paddingY?(v.style.paddingTop=t.paddingY,v.style.paddingBottom=t.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let I=null;m&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,C.appendChild(I)),v.setAttribute("aria-label",a),C.appendChild(v);let P="send";return{button:v,wrapper:C,setMode:ke=>{if(ke===P)return;P=ke;let be=ke==="stop"?i:a;if(v.setAttribute("aria-label",be),I&&(I.textContent=be),n){if(E&&L){let Fe=ke==="stop"?L:E;v.replaceChildren(Fe)}}else v.textContent=ke==="stop"?l:d}}},xi=e=>{var I,P,H,W,x,w,k,S,A,N,$,G;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(o||r))return null;let a=(W=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?W:"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=(x=t.iconName)!=null?x:"mic",m=(w=t.iconSize)!=null?w:a,p=parseFloat(m)||24,f=(S=t.backgroundColor)!=null?S:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,u=(N=t.iconColor)!=null?N:(A=e==null?void 0:e.sendButton)==null?void 0:A.textColor;d.style.width=m,d.style.height=m,d.style.minWidth=m,d.style.minHeight=m,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let v=Ee(l,p,u||"currentColor",1.5);v?d.appendChild(v):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 E=($=t.tooltipText)!=null?$:"Start voice recognition";if(((G=t.showTooltip)!=null?G:!1)&&E){let fe=b("div","persona-send-button-tooltip");fe.textContent=E,i.appendChild(fe)}return{button:d,wrapper:i}},wi=e=>{var C,v,E,L,I,P,H,W;let t=(C=e==null?void 0:e.attachments)!=null?C:{};if(t.enabled!==!0)return null;let n=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"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=((L=t.allowedTypes)!=null?L:Uo).join(","),r.multiple=((I=t.maxFiles)!=null?I:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(P=t.buttonTooltipText)!=null?P:"Attach file");let i=(H=t.buttonIconName)!=null?H:"paperclip",d=n,l=parseFloat(d)||40,m=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=Ee(i,m,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",x=>{x.preventDefault(),r.click()}),s.appendChild(a);let f=(W=t.buttonTooltipText)!=null?W:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=f,s.appendChild(u),{button:a,wrapper:s,input:r,previewsContainer:o}},Ci=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},Si=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ai=e=>{var C,v,E,L,I,P;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=Si(),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}=yi(t);a();let i=vi(t),d=xi(t),l=wi(t),m=Ci(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"),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),p.append(f,u),r.append(p),r.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,m),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:m,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:p,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var rm=()=>{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=Ee("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=Ee("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},sm=e=>{var C,v,E,L,I,P;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Si();o.style.display="none";let r=Ci(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=yi(t);s.style.maxHeight="100px",a();let i=vi(t),d=xi(t),l=wi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let m=b("form","persona-widget-composer persona-pill-composer");m.setAttribute("data-persona-composer-form",""),m.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),m.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&m.append(l.input),m.append(p,s,f),l&&n.append(l.previewsContainer),n.append(m,o,r);let u=m;return{footer:n,suggestions:o,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:r,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:u,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var am=e=>{var m,p,f,u,C,v,E,L,I,P,H,W,x,w,k,S,A;let t=(p=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?p:!0,n=hn(e);if(Js(e)){let N=(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=(C=N.expandedSize)!=null?C:"anchored",$.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:wn);let G=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");G.style.width="100%",$.appendChild(G);let fe=b("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(L=N.expandedSize)!=null?L:"anchored",fe.style.zIndex=String((P=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?P:wn),{wrapper:$,panel:G,pillRoot:fe}}if(n){let N=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 N.appendChild($),{wrapper:N,panel:$}}if(!t){let N=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"),G=(W=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?W:"100%";return N.style.width=G,$.style.width="100%",N.appendChild($),{wrapper:N,panel:$}}let r=(x=e==null?void 0:e.launcher)!=null?x:{},s=r.position&&ko[r.position]?ko[r.position]:ko["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?k:wn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(A=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?A:e==null?void 0:e.launcherWidth,l=d!=null?d:go;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ny=(e,t)=>{var H,W,x,w,k,S,A,N,$;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}=fi(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=(x=(W=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:W.enabled)!=null?x:!0,a=null,i=null;if(s){let G=hi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=G.button,i=G.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 m=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");m.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",m.setAttribute("data-persona-intro-card","");let p=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(k=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?k:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(A=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",m.append(p,f);let u=b("div","persona-flex persona-flex-col persona-gap-3"),C=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;C&&(u.style.maxWidth=C,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,u);let E=b("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let L=sm({config:e}),{root:I,textNode:P}=rm();return n.append(d,r,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.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:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:P}},im=(e,t=!0)=>{var E,L,I,P,H,W,x,w,k;if(Js(e))return Ny(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=(E=e==null?void 0:e.layout)==null?void 0:E.header,r=((L=e==null?void 0:e.layout)==null?void 0:L.showHeader)!==!1,s=o?bi(e,o,{showClose:t}):Mr({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=hn(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=(P=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let m=b("div","persona-flex persona-flex-col persona-gap-3"),p=(x=e==null?void 0:e.layout)==null?void 0:x.contentMaxWidth;p&&(m.style.maxWidth=p,m.style.marginLeft="auto",m.style.marginRight="auto",m.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,m);let u=Ai({config:e}),C=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?ea(n,s,e):(s.header.style.display="none",ea(n,s,e)),n.append(a);let v=b("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",C||(u.footer.style.display="none"),n.append(u.footer),n.append(v),{container:n,body:a,messagesWrapper:m,composerOverlay:v,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 _y=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}},Vy=(e,t)=>{if(!e)return null;let n=_y(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},$y=(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},Uy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Sl=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(":"))},Al=320,cm=320,zy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),qy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),jy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ky=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Gy=(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=`${Al}px`,l.style.maxHeight=`${cm}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 m=!1;r+=1,l.addEventListener("error",()=>{m||(m=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{m=!0}),Uy(i.image)?(l.src=i.image,o.appendChild(l)):(m=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Yy=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(!Sl(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=`${Al}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xy=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(!Sl(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=`${Al}px`,r.style.maxHeight=`${cm}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}},Qy=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(!Sl(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}},ta=()=>{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},Jy=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ta};if(t){let r=t(o);if(r!==null)return r}return ta()},Zy=(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},lm=(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},ev=(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},tv=(e,t,n)=>{var u,C,v,E,L,I;let o=(u=t.showCopy)!=null?u:!0,r=(C=t.showUpvote)!=null?C:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let P=b("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let a=(E=t.visibility)!=null?E:"hover",i=(L=t.align)!=null?L:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],m={"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} ${m} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(P,H,W)=>{let x=Cn({icon:P,label:H,size:14,className:"persona-message-action-btn"});return x.setAttribute("data-action",W),x};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},Tl=(e,t,n,o,r,s)=>{var j,de,K,ye,le,te,Ce,Ue,ee,oe,ae,rt,Ae,pe,$e,We,ue;let a=n!=null?n:{},i=(j=a.layout)!=null?j:"bubble",d=a.avatar,l=a.timestamp,m=(de=d==null?void 0:d.show)!=null?de:!1,p=(K=l==null?void 0:l.show)!=null?K:!1,f=(ye=d==null?void 0:d.position)!=null?ye:"left",u=(le=l==null?void 0:l.position)!=null?le:"below",C=ev(e.role,i),v=b("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=zy(e),L=(Ce=(te=e.content)==null?void 0:te.trim())!=null?Ce:"",P=E.length>0&&L===ei,H=pi((ee=(Ue=s==null?void 0:s.widgetConfig)==null?void 0:Ue.features)==null?void 0:ee.streamAnimation),W=(rt=(ae=(oe=s==null?void 0:s.widgetConfig)==null?void 0:oe.features)==null?void 0:ae.streamAnimation)==null?void 0:rt.plugins,x=e.role==="assistant"&&H.type!=="none"?Gs(H.type,W):null,w=e.role==="assistant"&&((Ae=x==null?void 0:x.isAnimating)==null?void 0:Ae.call(x,e))===!0,k=e.role==="assistant"&&x!==null&&(!!e.streaming||w);k&&(x!=null&&x.bubbleClass)&&v.classList.add(x.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),k&&x&&(x.containerClass&&S.classList.add(x.containerClass),S.style.setProperty("--persona-stream-step",`${H.speed}ms`),S.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let A=k?ui((pe=e.content)!=null?pe:"",H.buffer,x,e,!!e.streaming):($e=e.content)!=null?$e:"",N=t({text:A,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=N;k&&(x==null?void 0:x.wrap)==="char"?$=Ys(N,"char",e.id,{skipTags:x.skipTags}):k&&(x==null?void 0:x.wrap)==="word"&&($=Ys(N,"word",e.id,{skipTags:x.skipTags}));let G=null;if(P?(G=document.createElement("div"),G.innerHTML=$,G.style.display="none",S.appendChild(G)):S.innerHTML=$,k&&(x!=null&&x.useCaret)&&!P&&L){let X=mi(),Ne=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bt=Ne[Ne.length-1];if(Bt!=null&&Bt.parentNode)Bt.parentNode.insertBefore(X,Bt.nextSibling);else{let he=S.lastElementChild;he?he.appendChild(X):S.appendChild(X)}}if(p&&u==="inline"&&e.createdAt){let X=lm(e,l);X.classList.add("persona-ml-2","persona-inline"),S.appendChild(X)}if(E.length>0){let X=Gy(E,!P&&!!L,()=>{P&&G&&(G.style.display="")});X?v.appendChild(X):P&&G&&(G.style.display="")}let fe=qy(e);if(fe.length>0){let X=Yy(fe);X&&v.appendChild(X)}let ge=jy(e);if(ge.length>0){let X=Xy(ge);X&&v.appendChild(X)}let se=Ky(e);if(se.length>0){let X=Qy(se);X&&v.appendChild(X)}if(v.appendChild(S),p&&u==="below"&&e.createdAt){let X=lm(e,l);X.classList.add("persona-mt-1"),v.appendChild(X)}let ke=e.role==="assistant"?Vy(e.stopReason,(ue=(We=s==null?void 0:s.widgetConfig)==null?void 0:We.copy)==null?void 0:ue.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(A&&A.trim()),Ne=H.placeholder==="skeleton",Bt=Ne&&H.buffer==="line"&&X;if(X)Bt&&v.appendChild(Xs());else if(Ne)v.appendChild(Xs());else{let he=Jy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);he&&v.appendChild(he)}}if(ke&&e.stopReason&&!e.streaming&&(L||(S.style.display="none"),v.appendChild($y(e.stopReason,ke))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=tv(e,o,r);v.appendChild(X)}if(!m||e.role==="system")return v;let Fe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),xe=Zy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Fe.append(v,xe):Fe.append(xe,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Fe};var es=new Set,nv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ov=(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
|
+
`):""},dm=(e,t)=>{let n=es.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=Ee(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")},kl=(e,t)=>{var ge,se,ke,be,Fe,xe,j,de,K,ye,le;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=(se=(ge=t==null?void 0:t.features)==null?void 0:ge.reasoningDisplay)!=null?se:{},s=r.expandable!==!1,a=s&&es.has(e.id),i=n.status!=="complete",d=ov(e,(ke=r.previewMaxLines)!=null?ke: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 m=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",u=(be=t==null?void 0:t.reasoning)!=null?be:{},C=String((Fe=n.startedAt)!=null?Fe:Date.now()),v=()=>{let te=b("span","");return te.setAttribute("data-tool-elapsed",C),te.textContent=Ya(n),te},E=(xe=u.renderCollapsedSummary)==null?void 0:xe.call(u,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ya(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(p.textContent=E,m.appendChild(p)):E instanceof HTMLElement?m.appendChild(E):(p.textContent=f,m.appendChild(p));let L=b("span","persona-text-xs persona-text-persona-primary");L.textContent=Wu(n),m.appendChild(L);let I=(j=r.loadingAnimation)!=null?j:"none",P=u.activeTextTemplate,H=u.completeTextTemplate,W=i?P:H,x=E instanceof HTMLElement,w=(te,Ce,Ue)=>{let ee=Ue;for(let oe of Ce){let ae=b("span","persona-tool-char");ae.style.setProperty("--char-index",String(ee)),ae.textContent=oe===" "?"\xA0":oe,te.appendChild(ae),ee++}return ee},k=(te,Ce)=>{p.textContent="";let Ue=Xa(te,""),ee=0;for(let oe of Ue){let ae=oe.styles.length>0?(()=>{let rt=b("span",oe.styles.map(Ae=>`persona-tool-text-${Ae}`).join(" "));return p.appendChild(rt),rt})():p;if(oe.isDuration&&i)ae.appendChild(v());else{let rt=oe.isDuration?Ya(n):oe.text;Ce?ee=w(ae,rt,ee):ae.appendChild(document.createTextNode(rt))}}};if(!x&&W)if(L.style.display="none",p.style.display="",i&&I!=="none"){let te=(de=u.loadingAnimationDuration)!=null?de:2e3;p.setAttribute("data-preserve-animation","true"),I==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`),k(W,!1)):(p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`),I==="shimmer-color"&&(u.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),k(W,!0))}else k(W,!1);else if(!x&&i&&I!=="none"){p.style.display="";let te=(K=u.loadingAnimationDuration)!=null?K:2e3;if(p.setAttribute("data-preserve-animation","true"),I==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`);else{p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`),I==="shimmer-color"&&(u.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let Ce=p.textContent||f;p.textContent="",w(p,Ce,0)}n.status==="complete"&&(p.style.display="none")}else x||(n.status==="complete"?p.style.display="none":p.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let Ce=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?S.appendChild(Ce):S.textContent=a?"Hide":"Show";let Ue=b("div","persona-flex persona-items-center persona-ml-auto");Ue.append(S),l.append(m,Ue)}else l.append(m);let A=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(A.setAttribute("data-persona-collapsed-preview","reasoning"),A.style.display="none",A.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let te=(le=(ye=t==null?void 0:t.reasoning)==null?void 0:ye.renderCollapsedPreview)==null?void 0:le.call(ye,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});nv(A,te)||(A.textContent=d),A.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,A),o;let N=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=a?"":"none";let $=n.chunks.join(""),G=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(G),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let Ce=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?S.appendChild(Ce):S.textContent=a?"Hide":"Show"}N.style.display=a?"":"none",A.style.display=a?"none":A.textContent||A.childNodes.length?"":"none"})(),o.append(l,A,N),o};var ts=new Set,rv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sv=(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
|
+
`);let r=Jr(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
+
`):""},av=(e,t)=>{var m,p,f,u,C;let n=e.toolCall,o=(m=t==null?void 0:t.features)==null?void 0:m.toolCallDisplay,r=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",s=sv(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Bu(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=((C=n.name)==null?void 0:C.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=ml(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ml(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},pm=(e,t,n)=>{var m;let o=ts.has(e),r=(m=n==null?void 0:n.toolCall)!=null?m:{},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=Ee(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")},El=(e,t)=>{var $,G,fe,ge,se,ke,be,Fe,xe;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),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(fe=(G=t==null?void 0:t.features)==null?void 0:G.toolCallDisplay)!=null?fe:{},a=s.expandable!==!1,i=a&&ts.has(e.id),{summary:d,previewText:l,isActive:m}=av(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"),u=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(u.style.color=o.headerTextColor);let C=String((ge=n.startedAt)!=null?ge:Date.now()),v=()=>{let j=b("span","");return j.setAttribute("data-tool-elapsed",C),j.textContent=Os(n),j},E=(ke=o.renderCollapsedSummary)==null?void 0:ke.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(se=s.collapsedMode)!=null?se:"tool-call",isActive:m,config:t!=null?t:{},elapsed:Os(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(u.textContent=E,f.appendChild(u)):E instanceof HTMLElement?f.appendChild(E):(u.textContent=d,f.appendChild(u));let L=(be=s.loadingAnimation)!=null?be:"none",I=o.activeTextTemplate,P=o.completeTextTemplate,H=m?I:P,W=E instanceof HTMLElement,x=(j,de,K)=>{let ye=K;for(let le of de){let te=b("span","persona-tool-char");te.style.setProperty("--char-index",String(ye)),te.textContent=le===" "?"\xA0":le,j.appendChild(te),ye++}return ye},w=(j,de)=>{var te;u.textContent="";let K=((te=n.name)==null?void 0:te.trim())||"tool",ye=Xa(j,K),le=0;for(let Ce of ye){let Ue=Ce.styles.length>0?(()=>{let ee=b("span",Ce.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return u.appendChild(ee),ee})():u;if(Ce.isDuration&&m)Ue.appendChild(v());else{let ee=Ce.isDuration?Os(n):Ce.text;de?le=x(Ue,ee,le):Ue.appendChild(document.createTextNode(ee))}}};if(!W)if(m&&L!=="none"){let j=(Fe=o.loadingAnimationDuration)!=null?Fe:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),H&&w(H,!1);else if(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),L==="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)),H)w(H,!0);else{let de=u.textContent||d;u.textContent="",x(u,de,0)}}else H&&w(H,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let j=o.toggleTextColor||o.headerTextColor||"currentColor",de=Ee(i?"chevron-up":"chevron-down",16,j,2);de?k.appendChild(de):k.textContent=i?"Hide":"Show";let K=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(k),p.append(f,K)}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&&m&&s.activePreview&&l){let j=(xe=o.renderCollapsedPreview)==null?void 0:xe.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});rv(S,j)||(S.textContent=l),S.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,S),r;let A=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(A.style.display=i?"":"none",o.contentBackgroundColor&&(A.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(A.style.color=o.contentTextColor),o.contentPaddingX&&(A.style.paddingLeft=o.contentPaddingX,A.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(A.style.paddingTop=o.contentPaddingY,A.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,A.appendChild(j)}if(n.args!==void 0){let j=b("div","persona-space-y-1"),de=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(de.style.color=o.labelTextColor),de.textContent="Arguments";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(K.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(K.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(K.style.color=o.codeBlockTextColor),K.textContent=Jr(n.args),j.append(de,K),A.appendChild(j)}if(n.chunks&&n.chunks.length){let j=b("div","persona-space-y-1"),de=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(de.style.color=o.labelTextColor),de.textContent="Activity";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(K.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(K.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(K.style.color=o.codeBlockTextColor),K.textContent=n.chunks.join(""),j.append(de,K),A.appendChild(j)}if(n.status==="complete"&&n.result!==void 0){let j=b("div","persona-space-y-1"),de=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(de.style.color=o.labelTextColor),de.textContent="Result";let K=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");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(K.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(K.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(K.style.color=o.codeBlockTextColor),K.textContent=Jr(n.result),j.append(de,K),A.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`,A.appendChild(j)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let j=o.toggleTextColor||o.headerTextColor||"currentColor",de=Ee(i?"chevron-up":"chevron-down",16,j,2);de?k.appendChild(de):k.textContent=i?"Hide":"Show"}A.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(p,S,A),r};import{parse as iv,ARR as lv,OBJ as cv,STR as dv}from"partial-json";var pv="ask_user_question",Ml=8,ns="data-persona-ask-sheet-for",uv="Other",mv="Other\u2026",mm="Type your own answer here",gm="Send",gv="Next",fv="Back",hv="Submit all",bv="Skip",yv=3,Ll="data-ask-current-index",Il="data-ask-question-count",fm="data-ask-answers",Rl="data-ask-grouped",hm="data-ask-layout",vv=e=>e.layout==="pills"?"pills":"rows",xv=e=>e.getAttribute(hm)==="pills"?"pills":"rows",um=!1,bm=e=>e.replace(/["\\]/g,"\\$&"),Lr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===pv,Pl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},os=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=iv(r,dv|cv|lv);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},na=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Ml&&!um&&(um=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ml}.`)),t.slice(0,Ml)},wv=e=>{var t;return(t=na(e)[0])!=null?t:null},Cv=(e,t)=>{var n;return(n=na(e)[t])!=null?n:null},Sv=(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))},ym=(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},Av=(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=ym(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Tv=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},kv=(e,t,n,o)=>{var m,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(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<yv;u++)s.appendChild(Tv(o));return s}if(d.forEach((u,C)=>{s.appendChild(Av(u,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?uv:mv;if(o==="rows"){let C=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(m=t.freeTextPlaceholder)!=null?m:mm,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:u),v.appendChild(E),C.appendChild(v);let L=ym(o,a,d.length);L&&C.appendChild(L),s.appendChild(C)}else{let C=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(f=t.freeTextLabel)!=null?f:u,s.appendChild(C)}}return s},vm=(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:mm,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:gm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Ev=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:gm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Mv=(e,t,n)=>{var l,m,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:fv,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=(m=n.skipLabel)!=null?m:bv,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:hv:(f=n.nextLabel)!=null?f:gv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Ir=e=>{let t=e.getAttribute(fm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},xm=(e,t)=>{e.setAttribute(fm,JSON.stringify(t))},fo=e=>{var n;let t=Number((n=e.getAttribute(Ll))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Lv=(e,t)=>{e.setAttribute(Ll,String(Math.max(0,Math.floor(t))))},rs=e=>{var n;let t=Number((n=e.getAttribute(Il))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},lr=e=>e.getAttribute(Rl)==="true",Iv=(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},Rv=(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)))},Ti=(e,t)=>{let{payload:n}=os(t),o=na(n),r=Ir(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},wm=e=>{let t=Ir(e),n=fo(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:"",m=r.has(l);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});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=""},Cm=e=>{if(!lr(e))return;let t=Ir(e),n=fo(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}},Wl=(e,t,n)=>{let o=Pl(n),r=xv(e),{payload:s,complete:a}=os(t),i=lr(e),d=fo(e),l=rs(e),m=i?Cv(s,d):wv(s),p=!!(m!=null&&m.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 C=e.querySelector('[data-ask-question="true"]');if(C){let I=typeof(m==null?void 0:m.question)=="string"?m.question:"";C.textContent=I,C.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=kv(m,o,a,r);v.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(vm(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!E?e.appendChild(Ev(o)):(!p||i)&&E&&E.remove(),e.setAttribute("data-multi-select",p?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=Mv(d,l,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();wm(e),Cm(e)},Pv=(e,t,n)=>{let o=Pl(t),r=vv(o),s=e.toolCall.id,a=na(n),i=Math.max(1,a.length),d=i>1,l=Iv(e,a),m=d?Rv(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(ns,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Il,String(i)),p.setAttribute(Ll,String(m)),p.setAttribute(Rl,d?"true":"false"),p.setAttribute(hm,r),xm(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`),Sv(p,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 C=b("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",f.appendChild(C),p.appendChild(f);let E=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 E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),p.appendChild(E),r!=="rows"&&p.appendChild(vm(o,r)),Wl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Wv=(e,t,n)=>{let{payload:o}=os(t),r=Math.max(1,na(o).length);r>rs(e)&&(e.setAttribute(Il,String(r)),r>1&&!lr(e)&&e.setAttribute(Rl,"true")),Wl(e,t,n)};var ki=(e,t,n)=>{if(!n||!Lr(e)||Pl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ns}]`).forEach(l=>{l.getAttribute(ns)!==r&&l.remove()});let a=n.querySelector(`[${ns}="${bm(r)}"]`);if(a){Wv(a,e,t);return}let{payload:i}=os(e),d=Pv(e,t,i);n.appendChild(d)},ss=(e,t)=>{if(!e)return;let n=t?`[${ns}="${bm(t)}"]`:`[${ns}]`;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)})},Bl=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),cr=(e,t)=>{let n=Ir(e),o=fo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,xm(e,n),wm(e),Cm(e)},Ei=(e,t,n,o)=>{let r=rs(e),s=Math.max(0,Math.min(r-1,o));Lv(e,s),Wl(e,t,n)};var Mi=new Map,Bv=e=>{let n=(e.startsWith(Tr)?e.slice(Tr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Sm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Am=(e,t)=>{var o,r,s;let n=(r=(o=Sm(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Mi.get(e))!=null?s:n==="expanded"},Tm=(e,t,n)=>{var a,i;let o=Sm(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ee(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},km=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Am(e,n);Tm(o,s,n),r.style.display=s?"":"none"};var Li=(e,t)=>{var w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe;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=(w=o==null?void 0:o.backgroundColor)!=null?w:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(k=o==null?void 0:o.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!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)":(S=o==null?void 0:o.titleColor)!=null?S:"currentColor",m=Ee(d,20,l,2);m&&i.appendChild(m);let p=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=(A=o==null?void 0:o.title)!=null?A:"Approval Required",f.appendChild(u),!r){let j=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");j.setAttribute("data-approval-status",n.status),n.status==="approved"?(j.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",j.style.color="var(--persona-palette-colors-success-700, #15803d)",j.textContent="Approved"):n.status==="denied"?(j.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",j.style.color="var(--persona-palette-colors-error-700, #b91c1c)",j.textContent="Denied"):n.status==="timeout"&&(j.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",j.style.color="var(--persona-palette-colors-warning-700, #b45309)",j.textContent="Timeout"),f.appendChild(j)}p.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Tr)?ul(n.toolName):void 0,E=(N=o==null?void 0:o.formatDescription)==null?void 0:N.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{}}),L=!n.toolName,I=E||(L?n.description:`The assistant wants to use \u201C${v!=null?v:Bv(n.toolName)}\u201D.`),P=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=I,p.appendChild(P);let H=($=o==null?void 0:o.detailsDisplay)!=null?$:"collapsed",W=!!n.description&&!L,x=W||!!n.parameters;if(H!=="hidden"&&x){let j=Am(e.id,t),de=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(de.style.color=o.descriptionColor);let K=b("span");K.setAttribute("data-approval-details-label","true");let ye=b("span","persona-inline-flex persona-items-center");ye.setAttribute("data-approval-details-chevron","true"),de.append(K,ye),Tm(de,j,t),p.appendChild(de);let le=b("div");if(le.setAttribute("data-approval-details","true"),le.style.display=j?"":"none",W){let te=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(te.style.color=o.descriptionColor),te.textContent=n.description,le.appendChild(te)}if(n.parameters){let te=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&&(te.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(te.style.color=o.parameterTextColor),te.style.fontSize="0.75rem",te.style.lineHeight="1rem",te.textContent=Jr(n.parameters),le.appendChild(te)}p.appendChild(le)}if(r){let j=b("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let de=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");de.type="button",de.style.backgroundColor=(G=o==null?void 0:o.approveButtonColor)!=null?G:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(fe=o==null?void 0:o.approveButtonTextColor)!=null?fe:"#ffffff",de.setAttribute("data-approval-action","approve");let K=Ee("shield-check",14,(ge=o==null?void 0:o.approveButtonTextColor)!=null?ge:"#ffffff",2);K&&(K.style.marginRight="4px",de.appendChild(K));let ye=document.createTextNode((se=o==null?void 0:o.approveLabel)!=null?se:"Approve");de.appendChild(ye);let le=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");le.type="button",le.style.backgroundColor=(ke=o==null?void 0:o.denyButtonColor)!=null?ke:"transparent",le.style.color=(be=o==null?void 0:o.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",le.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,le.setAttribute("data-approval-action","deny");let te=Ee("shield-x",14,(Fe=o==null?void 0:o.denyButtonTextColor)!=null?Fe:"var(--persona-feedback-error, #dc2626)",2);te&&(te.style.marginRight="4px",le.appendChild(te));let Ce=document.createTextNode((xe=o==null?void 0:o.denyLabel)!=null?xe:"Deny");le.appendChild(Ce),j.append(de,le),p.appendChild(j)}return a.append(i,p),s.appendChild(a),s};var Em=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 m=document.createDocumentFragment(),p=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 C=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");C.type="button",C.textContent=u,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(u))}),m.appendChild(C),t.push(C)}),e.appendChild(m)}}};var oa=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 ra=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 Hv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Dv=new Set(["step_start","execution_start"]),Fv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ov=new Set(["step_complete","agent_turn_complete"]),Nv=new Set(["flow_complete","agent_complete"]),Mm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Im=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Rr=(e,t)=>{let n=e[t];return Im(n)?n:void 0};function Hl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function _v(e,t){return typeof t.type=="string"?t.type:e}function Vv(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 $v(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 Lm(e){var o,r,s,a,i;let t=Rr(e,"result"),n=[Rr(e,"tokens"),Rr(e,"totalTokens"),t?Rr(t,"tokens"):void 0,Rr(e,"usage"),t?Rr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Zn(d.output))!=null?o:Zn(d.outputTokens))!=null?r:Zn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Zn(e.outputTokens))!=null?s:Zn(e.completionTokens))!=null?i:t?(a=Zn(t.outputTokens))!=null?a:Zn(t.completionTokens):void 0}function Uv(e){var n,o,r,s,a;let t=Rr(e,"result");return(a=(r=(o=(n=Zn(e.executionTime))!=null?n:Zn(e.executionTimeMs))!=null?o:Zn(e.execution_time))!=null?r:Zn(e.duration))!=null?a:t?(s=Zn(t.executionTime))!=null?s:Zn(t.executionTimeMs):void 0}function zv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var sa=class{constructor(t=zv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ii(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!Im(n)){Mm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=_v(t,n),r=this.now();if(Hv.has(o)){this.startRun(r);return}if(Dv.has(o)){this.run||this.startRun(r);return}if(Fv.has(o)){if(!$v(o,n))return;let a=Vv(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+Hl(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ii(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ov.has(o)){if(!this.run)return;let a=this.run,i=Lm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Hl(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ii(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(Nv.has(o)){if(!this.run)return;let a=this.run,i=Lm(n),d=i!=null?i:a.exactOutputTokens+Hl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ii(d,m),outputTokens:d,durationMs:m,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=Uv(n);return s!=null?s:o-t.startedAt}};function as(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var qv={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)"}},jv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Kv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Gv=100;function Yv(e,t){let n={...qv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return jv}function Xv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Qv(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 Jv(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 Zv(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 ex(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 tx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function nx(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 ox(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 Dl(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");as(l,(f=o.classNames)==null?void 0:f.eventRow);let m=a.find(u=>u.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let u=m.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(p()),l;function p(){var $,G;let u=b("div",""),C=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");C.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Ee(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let L=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=($=o.timestampFormat)!=null?$:"relative";L.textContent=I==="relative"?Xv(e.timestamp,n):Qv(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let H=Yv(e.type,o.badgeColors),W=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");W.style.backgroundColor=H.bg,W.style.color=H.text,W.style.borderColor=H.text+"50",W.textContent=e.type;let x=(G=o.descriptionFields)!=null?G:Kv,w=Jv(e.payload,x),k=null;w&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=w);let S=b("div","persona-flex-1 persona-min-w-0"),A=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"),N=Ee("clipboard","12px","currentColor",1.5);return N&&A.appendChild(N),A.addEventListener("click",async fe=>{fe.stopPropagation(),await Zv(ex(e)),A.innerHTML="";let ge=Ee("check","12px","currentColor",1.5);ge&&A.appendChild(ge),setTimeout(()=>{A.innerHTML="";let se=Ee("clipboard","12px","currentColor",1.5);se&&A.appendChild(se)},1500)}),C.appendChild(v),C.appendChild(L),P&&C.appendChild(P),C.appendChild(W),k&&C.appendChild(k),C.appendChild(S),C.appendChild(A),u.appendChild(C),d&&u.appendChild(ox(e,a,i)),u}}function Rm(e){var C,v,E,L,I;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(C=r==null?void 0:r.features)==null?void 0:C.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",m=(E=i==null?void 0:i.label)!=null?E:"",p=(I=(L=r==null?void 0:r.features)==null?void 0:L.eventStream)!=null?I:{},f=s.find(P=>P.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let P=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return u();function u(){let P=p.classNames,H=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");as(H,P==null?void 0:P.panel);let W=[],x="",w="",k=null,S=[],A={},N=0,$=li(),G=0,fe=0,ge=!1,se=null,ke=!1,be=0,Fe=new Set,xe=new Map,j="",de="",K=null,ye,le,te,Ce,Ue,ee=null,oe=null,ae=null;function rt(){let re=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=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");as(we,P==null?void 0:P.headerBar);let Tt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Tt.textContent="Events",ye=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"),ye.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",ee=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"),ee.textContent="-- tok/s",ae=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"),ae.style.display="none",ae.style.pointerEvents="none";let to=oe,An=ae,On=()=>{if(!An.textContent)return;let Eo=to.getBoundingClientRect(),Nn=re.getBoundingClientRect();An.style.left=`${Eo.left-Nn.left}px`,An.style.top=`${Eo.bottom-Nn.top+4}px`,An.style.display="block"},ht=()=>{An.style.display="none"};oe.addEventListener("mouseenter",On),oe.addEventListener("mouseleave",ht),oe.appendChild(Fn),oe.appendChild(ee)}let jt=b("div","persona-flex-1");le=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 en=b("option","");en.value="",en.textContent="All events",le.appendChild(en),te=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"),te.type="button",te.title="Copy All";let Pt=Ee("clipboard-copy","12px","currentColor",1.5);Pt&&te.appendChild(Pt);let Et=b("span","persona-text-xs");Et.textContent="Copy All",te.appendChild(Et),we.appendChild(Tt),we.appendChild(ye),oe&&we.appendChild(oe),we.appendChild(jt),we.appendChild(le),we.appendChild(te);let xt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");as(xt,P==null?void 0:P.searchBar);let Ct=Ee("search","14px","var(--persona-muted, #9ca3af)",1.5),Kt=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");Ct&&Kt.appendChild(Ct),Ce=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"),as(Ce,P==null?void 0:P.searchInput),Ce.type="text",Ce.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 nt=Ee("x","12px","currentColor",2);return nt&&Ue.appendChild(nt),xt.appendChild(Kt),xt.appendChild(Ce),xt.appendChild(Ue),re.appendChild(we),re.appendChild(xt),ae&&re.appendChild(ae),re}let Ae,pe=s.find(re=>re.renderEventStreamToolbar);if(pe!=null&&pe.renderEventStreamToolbar&&r){let re=pe.renderEventStreamToolbar({config:r,defaultRenderer:()=>rt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:we=>{x=we,Dn(),_()},onSearchChange:we=>{w=we,Dn(),_()}});Ae=re!=null?re:rt()}else Ae=rt();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 We(){if(!a||!ee||!oe)return;let re=a();ee.textContent=tx(re);let we=nx(re);ae&&(ae.textContent=we,we||(ae.style.display="none")),we?oe.setAttribute("aria-label",we):oe.removeAttribute("aria-label")}let ue=b("div","persona-flex-1 persona-min-h-0 persona-relative"),X=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let Ne=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");as(Ne,P==null?void 0:P.scrollIndicator),Ne.style.display="none",Ne.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Bt=Ee(l,"14px","currentColor",2);Bt&&Ne.appendChild(Bt);let he=b("span","");he.textContent=m,Ne.appendChild(he);let ce=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ce.style.display="none",ue.appendChild(X),ue.appendChild(ce),ue.appendChild(Ne),H.setAttribute("tabindex","0"),H.appendChild(Ae),H.appendChild($e),H.appendChild(ue);function Rn(){let re=t.getAll(),we={};for(let Et of re)we[Et.type]=(we[Et.type]||0)+1;let Tt=Object.keys(we).sort(),jt=Tt.length!==S.length||!Tt.every((Et,xt)=>Et===S[xt]),en=!jt&&Tt.some(Et=>we[Et]!==A[Et]),Sn=re.length!==Object.values(A).reduce((Et,xt)=>Et+xt,0);if(!jt&&!en&&!Sn||(S=Tt,A=we,!le))return;let Pt=le.value;if(le.options[0].textContent="All events",jt){for(;le.options.length>1;)le.remove(1);for(let Et of Tt){let xt=b("option","");xt.value=Et,xt.textContent=`${Et} (${we[Et]||0})`,le.appendChild(xt)}Pt&&Tt.includes(Pt)?le.value=Pt:Pt&&(le.value="",x="")}else for(let Et=1;Et<le.options.length;Et++){let xt=le.options[Et];xt.textContent=`${xt.value} (${we[xt.value]||0})`}}function $t(){let re=t.getAll();if(x&&(re=re.filter(we=>we.type===x)),w){let we=w.toLowerCase();re=re.filter(Tt=>Tt.type.toLowerCase().includes(we)||Tt.payload.toLowerCase().includes(we))}return re}function mn(){return x!==""||w!==""}function Dn(){N=0,G=0,$.resume(),Ne.style.display="none"}function eo(re){Fe.has(re)?Fe.delete(re):Fe.add(re),K=re;let we=X.scrollTop,Tt=$.isFollowing();ke=!0,$.pause(),_(),X.scrollTop=we,Tt&&$.resume(),ke=!1}function ze(){return js(X,50)}function _(){fe=Date.now(),ge=!1,We(),Rn();let re=t.getEvictedCount();re>0?($e.textContent=`${re.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",W=$t();let we=W.length,Tt=t.getSize()>0;ye&&(ye.textContent=String(t.getSize())),we===0&&Tt&&mn()?(ce.textContent=w?`No events matching '${w}'`:"No events matching filter",ce.style.display="",X.style.display="none"):(ce.style.display="none",X.style.display=""),te&&(te.title=mn()?`Copy Filtered (${we})`:"Copy All"),d&&!$.isFollowing()&&we>N&&(G+=we-N,he.textContent=m?`${m}${G>0?` (${G})`:""}`:"",Ne.style.display=""),N=we;let jt=t.getAll(),en=jt.length>0?jt[0].timestamp:0,Sn=new Set(W.map(xt=>xt.id));for(let xt of Fe)Sn.has(xt)||Fe.delete(xt);let Pt=x!==j||w!==de,Et=xe.size===0&&W.length>0;if(Pt||Et||W.length===0){X.innerHTML="",xe.clear();let xt=document.createDocumentFragment();for(let Ct=0;Ct<W.length;Ct++){let Kt=Dl(W[Ct],Ct,en,p,Fe,eo,s,r);xe.set(W[Ct].id,Kt),xt.appendChild(Kt)}X.appendChild(xt),j=x,de=w,K=null}else{if(K!==null){let Ct=xe.get(K);if(Ct&&Ct.parentNode===X){let Kt=W.findIndex(nt=>nt.id===K);if(Kt>=0){let nt=Dl(W[Kt],Kt,en,p,Fe,eo,s,r);X.insertBefore(nt,Ct),Ct.remove(),xe.set(K,nt)}}K=null}let xt=new Set(W.map(Ct=>Ct.id));for(let[Ct,Kt]of xe)xt.has(Ct)||(Kt.remove(),xe.delete(Ct));for(let Ct=0;Ct<W.length;Ct++){let Kt=W[Ct];if(!xe.has(Kt.id)){let nt=Dl(Kt,Ct,en,p,Fe,eo,s,r);xe.set(Kt.id,nt),X.appendChild(nt)}}}$.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Me(){if(Date.now()-fe>=Gv){se!==null&&(cancelAnimationFrame(se),se=null),_();return}ge||(ge=!0,se=requestAnimationFrame(()=>{se=null,_()}))}let Be=(re,we)=>{if(!te)return;te.innerHTML="";let Tt=Ee(re,"12px","currentColor",1.5);Tt&&te.appendChild(Tt);let jt=b("span","persona-text-xs");jt.textContent="Copy All",te.appendChild(jt),setTimeout(()=>{te.innerHTML="";let en=Ee("clipboard-copy","12px","currentColor",1.5);en&&te.appendChild(en);let Sn=b("span","persona-text-xs");Sn.textContent="Copy All",te.appendChild(Sn),te.disabled=!1},we)},He=async()=>{if(te){te.disabled=!0;try{let re;mn()?re=W:n?(re=await n(),re.length===0&&(re=t.getAll())):re=t.getAll();let we=re.map(Tt=>{try{return JSON.parse(Tt.payload)}catch{return Tt.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),Be("check",1500)}catch{Be("x",1500)}}},_e=()=>{le&&(x=le.value,Dn(),_())},ut=()=>{!Ce||!Ue||(Ue.style.display=Ce.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{w=Ce.value,Dn(),_()},150))},st=()=>{!Ce||!Ue||(Ce.value="",w="",Ue.style.display="none",k&&clearTimeout(k),Dn(),_())},Rt=()=>{if(ke)return;let re=X.scrollTop,{action:we,nextLastScrollTop:Tt}=ci({following:$.isFollowing(),currentScrollTop:re,lastScrollTop:be,nearBottom:ze(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=Tt,we==="resume"?($.resume(),G=0,Ne.style.display="none"):we==="pause"&&($.pause(),d&&(he.textContent=m,Ne.style.display=""))},qt=re=>{let we=di({following:$.isFollowing(),deltaY:re.deltaY,nearBottom:ze(),resumeWhenNearBottom:!0});we==="pause"?($.pause(),d&&(he.textContent=m,Ne.style.display="")):we==="resume"&&($.resume(),G=0,Ne.style.display="none")},q=()=>{d&&(X.scrollTop=X.scrollHeight,$.resume(),G=0,Ne.style.display="none")},Ut=re=>{let we=re.target;if(!we||we.closest("button"))return;let Tt=we.closest("[data-event-id]");if(!Tt)return;let jt=Tt.getAttribute("data-event-id");jt&&eo(jt)},Je=re=>{if((re.metaKey||re.ctrlKey)&&re.key==="f"){re.preventDefault(),Ce==null||Ce.focus(),Ce==null||Ce.select();return}re.key==="Escape"&&(Ce&&document.activeElement===Ce?(st(),Ce.blur(),H.focus()):o&&o())};te&&te.addEventListener("click",He),le&&le.addEventListener("change",_e),Ce&&Ce.addEventListener("input",ut),Ue&&Ue.addEventListener("click",st),X.addEventListener("scroll",Rt),X.addEventListener("wheel",qt,{passive:!0}),X.addEventListener("click",Ut),Ne.addEventListener("click",q),H.addEventListener("keydown",Je);function _t(){k&&clearTimeout(k),se!==null&&(cancelAnimationFrame(se),se=null),ge=!1,xe.clear(),te&&te.removeEventListener("click",He),le&&le.removeEventListener("change",_e),Ce&&Ce.removeEventListener("input",ut),Ue&&Ue.removeEventListener("click",st),X.removeEventListener("scroll",Rt),X.removeEventListener("wheel",qt),X.removeEventListener("click",Ut),Ne.removeEventListener("click",q),H.removeEventListener("keydown",Je)}return{element:H,update:Me,destroy:_t}}}function Pm(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 m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.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 u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(u)}else p.textContent=a;if(l.append(m,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 Wm=(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",m=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Pm(e,t)});if(m)return m}return Pm(e,t)};var Fl=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)})}},Pr=new Fl;Pr.register("PersonaArtifactCard",Wm);function rx(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 Bm(e,t){var le,te,Ce,Ue;let n=(te=(le=e.features)==null?void 0:le.artifacts)==null?void 0:te.layout,r=((Ce=n==null?void 0:n.toolbarPreset)!=null?Ce:"default")==="document",s=(Ue=n==null?void 0:n.panePadding)==null?void 0:Ue.trim(),a=e.markdown?za(e.markdown):null,i=qa(e.sanitize),d=ee=>{let oe=a?a(ee):Ds(ee);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,m=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};l&&l.addEventListener("click",()=>{var ee;m(),(ee=t.onDismiss)==null||ee.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 u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let C=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var ee;m(),(ee=t.onDismiss)==null||ee.call(t)});let v="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),L=r?Cn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Cn({icon:"eye",label:"Rendered view"}),I=r?Cn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Cn({icon:"code-2",label:"Source"}),P=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,x=n==null?void 0:n.documentToolbarCopyMenuItems,w=!!(W&&x&&x.length>0),k=null,S,A=null,N=null;if(r&&(H||W)&&!w){if(S=H?Cl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let ee=Ee("chevron-down",14,"currentColor",2);ee&&S.appendChild(ee)}}else r&&w?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=H?Cl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),A=Cn({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,A)):r?S=Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Cn({icon:"copy",label:"Copy"});let $=r?Cn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"refresh-cw",label:"Refresh"}),G=r?Cn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"x",label:"Close"}),fe=()=>{var Ae,pe,$e;let ee=(Ae=xe.find(We=>We.id===j))!=null?Ae:xe[xe.length-1],oe=(pe=ee==null?void 0:ee.id)!=null?pe:null,ae=(ee==null?void 0:ee.artifactType)==="markdown"&&($e=ee.markdown)!=null?$e:"",rt=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:ae,jsonPayload:rt,id:oe}},ge=async()=>{var Ae;let{markdown:ee,jsonPayload:oe}=fe(),ae=(Ae=xe.find(pe=>pe.id===j))!=null?Ae:xe[xe.length-1],rt=(ae==null?void 0:ae.artifactType)==="markdown"?ee:ae?oe:"";try{await navigator.clipboard.writeText(rt)}catch{}};if(S.addEventListener("click",async()=>{let ee=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(ee&&w){let{markdown:oe,jsonPayload:ae,id:rt}=fe();try{await ee({actionId:"primary",artifactId:rt,markdown:oe,jsonPayload:ae})}catch{}return}await ge()}),A&&(x!=null&&x.length)){let ee=()=>{var ae;return(ae=p.closest("[data-persona-root]"))!=null?ae:document.body},oe=()=>{N=Zr({items:x.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:rt,jsonPayload:Ae,id:pe}=fe(),$e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:ae,artifactId:pe,markdown:rt,jsonPayload:Ae}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(rt):ae==="json"||ae==="source"?await navigator.clipboard.writeText(Ae):await navigator.clipboard.writeText(rt||Ae)}catch{}},anchor:k!=null?k:A,position:"bottom-right",portal:ee()})};p.isConnected?oe():requestAnimationFrame(oe),A.addEventListener("click",ae=>{ae.stopPropagation(),N==null||N.toggle()})}$.addEventListener("click",async()=>{var ee;try{await((ee=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:ee.call(n))}catch{}K()}),G.addEventListener("click",()=>{var ee;m(),(ee=t.onDismiss)==null||ee.call(t)});let se=()=>{r&&(L.setAttribute("aria-pressed",v==="rendered"?"true":"false"),I.setAttribute("aria-pressed",v==="source"?"true":"false"))};L.addEventListener("click",()=>{v="rendered",se(),K()}),I.addEventListener("click",()=>{v="source",se(),K()});let ke=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(),E.append(L,I),k?P.append(k,$,G):P.append(S,$,G),f.append(E,ke,P),se()):(f.appendChild(u),f.appendChild(C)),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),p.appendChild(f),p.appendChild(be),p.appendChild(Fe);let xe=[],j=null,de=!1,K=()=>{var rt,Ae,pe,$e;let ee=r&&xe.length<=1;be.classList.toggle("persona-hidden",ee),be.replaceChildren();for(let We of xe){let ue=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");ue.type="button",ue.textContent=We.title||We.id.slice(0,8),We.id===j&&ue.classList.add("persona-bg-persona-container","persona-border-persona-border"),ue.addEventListener("click",()=>t.onSelect(We.id)),be.appendChild(ue)}Fe.replaceChildren();let oe=j&&xe.find(We=>We.id===j)||xe[xe.length-1];if(!oe)return;if(r){let We=oe.artifactType==="markdown"?"MD":(rt=oe.component)!=null?rt:"Component",X=(oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ke.textContent=`${X} \xB7 ${We}`}else u.textContent="Artifacts";if(oe.artifactType==="markdown"){if(r&&v==="source"){let ue=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ue.textContent=(Ae=oe.markdown)!=null?Ae:"",Fe.appendChild(ue);return}let We=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((pe=oe.markdown)!=null?pe:""),Fe.appendChild(We);return}let ae=oe.component?Pr.get(oe.component):void 0;if(ae){let ue={message:{id:oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ae(($e=oe.props)!=null?$e:{},ue);if(X){Fe.appendChild(X);return}}catch{}}Fe.appendChild(rx(oe))},ye=()=>{var oe;let ee=xe.length>0;if(p.classList.toggle("persona-hidden",!ee),l){let ae=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,Ae=((oe=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ee&&Ae&&de?(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(ee){var oe,ae,rt;xe=ee.artifacts,j=(rt=(ae=ee.selectedId)!=null?ae:(oe=ee.artifacts[ee.artifacts.length-1])==null?void 0:oe.id)!=null?rt:null,xe.length>0&&(de=!0),K(),ye()},setMobileOpen(ee){de=ee,!ee&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ye()}}}function ho(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Hm(e,t){var 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"),!ho(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 sx(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 Ri(e,t){var d,l,m,p,f,u,C,v,E,L;if(!ho(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"),sx(e),Hm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(m=n==null?void 0:n.splitGap)!=null?m:"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=(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=(C=n==null?void 0:n.panePadding)==null?void 0:C.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(L=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:L.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Hm(e,t)}var Dm=["panel","seamless"];function Pi(e,t){var i,d,l,m,p,f;for(let u of Dm)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"),!ho(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=Dm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(m=n==null?void 0:n.paneBorderRadius)==null?void 0:m.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 u=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Fm(e,t){var n,o,r;return!t||!ho(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function ax(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 ix(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 lx(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function cx(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Om(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 Nm(e,t,n,o,r,s){let a=ax(r,200),i=cx(t,n,o,200);i=Math.max(a,i);let d=ix(s);return d!==null&&(i=Math.min(i,d)),lx(e,a,i)}var _m={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"}},Ol=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var C,v,E;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=_m[a])!=null?v:_m.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 L=b("p","persona-text-sm persona-text-persona-muted");L.textContent=i.description,d.appendChild(L)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(L=>{var x,w;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${L.name}`;let P=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=L.label,I.appendChild(P);let H=(x=L.type)!=null?x:"text",W;H==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=H),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${L.name}`,W.name=L.name,W.placeholder=(w=L.placeholder)!=null?w:"",L.required&&(W.required=!0),I.appendChild(W),m.appendChild(I)});let p=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),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=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(f),p.appendChild(u),m.appendChild(p),s.replaceChildren(d,m),m.addEventListener("submit",async L=>{var W,x;L.preventDefault();let I=(W=n.formEndpoint)!=null?W:"/form",P=new FormData(m),H={};P.forEach((w,k)=>{H[k]=w}),H.type=a,u.disabled=!0,f.textContent="Submitting\u2026";try{let w=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!w.ok)throw new Error(`Form submission failed (${w.status})`);let k=await w.json();f.textContent=(x=k.message)!=null?x:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(w){f.textContent=w instanceof Error?w.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Nl=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()}},_l=new Nl;var Vm=()=>{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 dx=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},px=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},$l=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=dx(e),n=px(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}},Vl=e=>typeof e=="string"?e:e==null?"":String(e),aa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Vl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Vl(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:Vl(n.text)}}},$m=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ul=e=>{let t=new Set($m(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set($m(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,m)=>l||(m==null?void 0:m({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 m=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:m});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(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:n}};var ux=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}},mx=e=>e.map(t=>({...t,streaming:!1})),gx=e=>e.map(t=>({...t,status:"complete"})),Um=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?ux(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?mx(n.messages):void 0,artifacts:n.artifacts?gx(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 cS,STR as dS,OBJ as pS}from"partial-json";function zm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Pr.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 qm(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 jm(e){let t=qm(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 Km(e){let t=qm(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 fx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gm(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=fx}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,u.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,u.appendChild(v),f.appendChild(u);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let x=1;x<=5;x++){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",`${x} star${x>1?"s":""}: ${l[x-1]}`),w.title=l[x-1],w.dataset.rating=String(x),w.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
29
29
|
</svg>
|
|
30
|
-
`,x.addEventListener("click",()=>{u=v,I.forEach((k,C)=>{let T=C<v;k.classList.toggle("selected",T),k.setAttribute("aria-checked",C===v-1?"true":"false")})}),I.push(x),M.appendChild(x)}g.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),g.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(),m.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let v=(L==null?void 0:L.value.trim())||void 0;await t(u,v),m.remove()}catch(v){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(W),g.appendChild(H),m.appendChild(g),m}function Dm(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:m="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,p=document.createElement("div");p.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,w.appendChild(S);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,w.appendChild(M),p.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 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=m,L.appendChild(H),L.appendChild(D);let W=document.createElement("div");W.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",()=>{g=F,v.forEach((j,me)=>{j.classList.toggle("selected",me===F),j.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),W.appendChild($)}I.appendChild(L),I.appendChild(W),p.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),p.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=i,C.addEventListener("click",()=>{n==null||n(),u.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let F=(x==null?void 0:x.value.trim())||void 0;await t(g,F),u.remove()}catch(F){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),k.appendChild(C),k.appendChild(T),p.appendChild(k),u.appendChild(p),u}var ts="persona-chat-history",nx=30*1e3,ox={"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 rx(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=ox[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 Li(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 sx(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 ax(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nl=e=>!e||typeof e!="object"?{}:{...e},Fm=e=>e.map(t=>({...t,streaming:!1})),Om=(e,t,n)=>{let o=e!=null&&e.markdown?$a(e.markdown):null,r=Ua(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,m,u;let a=(l=s.text)!=null?l:"",i=(m=s.message.rawContent)!=null?m:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):o?d=o(a):d=Is(a),r?r(d):d}};function Nm(e){var i,d,l,m;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=(m=e==null?void 0:e.iconStrokeWidth)!=null?m:.5,a=Te(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=b("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var _m=(e,t,n)=>{var ac,ic,lc,cc,dc,pc,uc,mc,fc,gc,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,Zc;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=Jp(t),r=Hl.getForInstance(o.plugins);o.components&&Mr.registerAll(o.components);let s=Mm(),i=o.persistState===!1?null:(ac=o.storageAdapter)!=null?ac:Im(),d={},l=null,m=!1,u=c=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:y}=f;return y&&(m=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return u(h)});else{let f=c!=null?c:{messages:[],metadata:{}},h=u(f);h.metadata&&(d=Nl(h.metadata)),(ic=h.messages)!=null&&ic.length&&(o={...o,initialMessages:h.messages}),(lc=h.artifacts)!=null&&lc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(cc=h.selectedArtifactId)!=null?cc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=u({messages:[],metadata:{}});(dc=c.messages)!=null&&dc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,p=c=>{var h;d=(h=c({...d}))!=null?h:{},Wr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Fl],S=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ea.message,ea.messageAndClick],M=Ol({parsers:w,handlers:S,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(uc=(pc=o.launcher)==null?void 0:pc.enabled)!=null?uc:!0,L=(fc=(mc=o.launcher)==null?void 0:mc.autoExpand)!=null?fc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=L,W=I,v=(bc=(hc=o.layout)==null?void 0:hc.header)==null?void 0:bc.layout,x=!1,k=()=>js(o),C=()=>I||k(),T=k()?!1:I?L:!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=Om(o,M,j),se=(vc=(yc=o.features)==null?void 0:yc.showReasoning)!=null?vc:!0,fe=(wc=(xc=o.features)==null?void 0:xc.showToolCalls)!=null?wc:!0,ie=(Sc=(Cc=o.features)==null?void 0:Cc.showEventStreamToggle)!=null?Sc:!1,be=(Tc=(Ac=o.features)==null?void 0:Ac.scrollToBottom)!=null?Tc:{},ve=`${(Ec=typeof o.persistState=="object"?(kc=o.persistState)==null?void 0:kc.keyPrefix:void 0)!=null?Ec:"persona-"}event-stream`,Q=ie?new Js(ve):null,Le=(Ic=(Lc=(Mc=o.features)==null?void 0:Mc.eventStream)==null?void 0:Lc.maxEvents)!=null?Ic:2e3,Y=ie?new Qs(Le,Q):null,xe=ie?new Zs:null,Se=null,de=!1,we=null,ze=0;Q==null||Q.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 f,h;s.emit("message:copy",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,c)},onFeedback:c=>{var f,h;s.emit("message:feedback",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,c)}},ne=(Rc=o.statusIndicator)!=null?Rc:{},re=c=>{var f,h,y,P;return c==="idle"?(f=ne.idleText)!=null?f:gn.idle:c==="connecting"?(h=ne.connectingText)!=null?h:gn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:gn.connected:c==="error"?(P=ne.errorText)!=null?P:gn.error:gn[c]};function nt(c,f,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let P=document.createElement("a");P.href=h.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=f,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=f}let{wrapper:ye,panel:le,pillRoot:Ue}=Qu(o),He=Ju(o,C()),{container:ce,body:G,messagesWrapper:Ve,suggestions:Et,textarea:pe,sendButton:ae,sendButtonWrapper:Ln,composerForm:Nt,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:qe,iconHolder:_,headerTitle:ke,headerSubtitle:De,header:Fe,footer:$e,actionsRow:dt,leftActions:ot,rightActions:At}=He,Vt=He.setSendButtonMode,q=He.micButton,_t=He.micButtonWrapper,Qe=He.attachmentButton,Ft=He.attachmentButtonWrapper,oe=He.attachmentInput,ge=He.attachmentPreviewsContainer;ce.classList.add("persona-relative"),G.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"),gt=b("span","");Tt.append(wt,gt),ce.appendChild(Tt);let bt=()=>{let f=$e.style.display==="none"?0:$e.offsetHeight;Tt.style.bottom=`${f+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 f=Te(Jt(),"14px","currentColor",2);f?(wt.appendChild(f),wt.style.display=""):wt.style.display="none",gt.textContent=$t(),gt.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 f=Ar({config:o,showClose:C()});return Gs(ce,f,o),f.header},onClose:()=>Bt(!1,"user")});if(c){let f=ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Fe=c)}}let vn=()=>{var f,h,y,P;if(!Y)return;if(de=!0,!Se&&Y&&(Se=ym({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&&(G.style.display="none",(f=$e.parentNode)==null||f.insertBefore(Se.element,$e),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-ze>=200&&(Se==null||Se.update(),ze=N),we=requestAnimationFrame(c)};ze=0,we=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,f,h;if(de){if(de=!1,Se&&Se.element.remove(),G.style.display="",ut){ut.style.boxShadow="";let y=(h=(f=(c=o.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&ut.classList.remove(P))}we!==null&&(cancelAnimationFrame(we),we=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Wc=(Pc=o.features)==null?void 0:Pc.eventStream)==null?void 0:Wc.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=b("button",f),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=He.clearChatButtonWrapper,P=He.closeButtonWrapper,N=y||P;N&&N.parentNode===Fe?Fe.insertBefore(ut,N):Fe.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}let wo=c=>{var y,P,N;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let 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=f.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=f.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(N=f.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,f=Nn.renderComposer({config:o,defaultRenderer:()=>Ci({config:o}).footer,onSubmit:h=>{var V;if(!E||E.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(cl(y))),E.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:((Bc=o.voiceRecognition)==null?void 0:Bc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});f&&($e.replaceWith(f),$e=f)}let ir=c=>{let f=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),P=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");f&&(Nt=f),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"]'),ge=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(dt=O)};wo($e),ir($e);let In=(Nc=(Hc=o.layout)==null?void 0:Hc.contentMaxWidth)!=null?Nc:k()?(Oc=(Fc=(Dc=o.launcher)==null?void 0:Dc.composerBar)==null?void 0:Fc.contentMaxWidth)!=null?Oc:"720px":void 0;if(In&&(Ve.style.maxWidth=In,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.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&&ge&&!k()&&(ge.style.maxWidth=In,ge.style.marginLeft="auto",ge.style.marginRight="auto"),(_c=o.attachments)!=null&&_c.enabled&&oe&&ge){et=Os.fromConfig(o.attachments),et.setPreviewsContainer(ge),oe.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,f=Nm(c);ce.appendChild(f)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},f=N=>{switch(N){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;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")Fe.insertBefore(V,Fe.firstChild);else if(N==="header-right")Fe.appendChild(V);else{let O=Fe.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):Fe.appendChild(V)}break;case"body-top":{let O=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):G.insertBefore(V,G.firstChild);break}case"body-bottom":G.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:()=>f(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"?(Gr.has(P)?Gr.delete(P):Gr.add(P),tm(P,y)):N==="tool"&&(Yr.has(P)?Yr.delete(P):Yr.add(P),nm(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 f=c.target;(c.key==="Enter"||c.key===" ")&&f.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 N=h.getAttribute("data-action");if(N==="copy"){let O=E.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 Z=Te("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},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",Z=y.querySelector(`[data-action="${ue}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Xe=Te(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(Z.innerHTML="",Z.appendChild(Xe))}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 Ne=E.getMessages().find(tt=>tt.id===P);Ne&&te.onFeedback&&te.onFeedback({type:N,messageId:Ne.id,message:Ne})}}}),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 N=h.getAttribute("data-approval-action");if(!N)return;let V=N==="approve"?"approved":"denied",O=E.getMessages().find(ue=>ue.id===P);if(!(O!=null&&O.approval))return;let Ae=y.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?E.resolveWebMcpApproval(P,V):E.resolveApproval(O.approval,V)});let yt=null,_n=null,Vn={artifacts:[],selectedId:null},xn=!1,It={current:null};Ve.addEventListener("click",c=>{var Z,he,Ee,Ne,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=(Z=o.features)==null?void 0:Z.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ee.call(he,{type:"download",artifactId:y}))===!0)return;let N=E.getArtifactById(y),V=N==null?void 0:N.markdown,z=(N==null?void 0:N.title)||"artifact";if(!V){let Xe=h.closest("[data-open-artifact]"),at=Xe==null?void 0:Xe.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Re=E.getMessages().find(je=>je.id===it);if(Re!=null&&Re.rawContent)try{let je=JSON.parse(Re.rawContent);V=(Ne=je==null?void 0:je.props)==null?void 0:Ne.markdown,z=((tt=je==null?void 0:je.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)}),Ve.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,E.selectArtifact(y),zn())}),Ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let eo=He.composerOverlay,to=(c,f,h)=>{var z,O,Ae,ue;let y=f.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})),Zr(eo,P);let V=It.current.getMessages().find(Z=>{var he;return((he=Z.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 f=It.current;if(!f)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=f.getMessages().find(N=>{var V;return((V=N.toolCall)==null?void 0:V.id)===h});y&&f.persistAskUserQuestionProgress(y,{answers:Si(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([f,h])=>`${f}: ${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 f=lo(c),h=Jr(c);if(f>=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&&(Ti(c,y,o,f+1),$n(c))};eo.addEventListener("click",c=>{var N,V,z,O,Ae,ue,Z,he,Ee,Ne,tt,Xe,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})),Zr(eo,Pe);let Re=(V=It.current)==null?void 0:V.getMessages().find(je=>{var R;return((R=je.toolCall)==null?void 0:R.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",je=sr(y);if(je&&Re){let R=kr(y)[lo(y)],Me=new Set(Array.isArray(R)?R:[]);Me.has(Pe)?Me.delete(Pe):Me.add(Pe),ar(y,Array.from(Me)),$n(y);return}if(je){ar(y,Pe),$n(y),Io(y);return}if(Re){let R=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",R?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!R);let Me=y.querySelector('[data-ask-user-action="submit-multi"]');Me&&(Me.disabled=Ml(y).length===0);return}to(y,Pe,{source:"pick",values:[Pe]});return}if(P==="submit-multi"){let Pe=Ml(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=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Re=It.current.getMessages().find(Ge=>{var Ce;return((Ce=Ge.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),R=(Ee=(he=je==null?void 0:je.value)==null?void 0:he.trim())!=null?Ee:"";if(R){let Ge=kr(y)[lo(y)];(typeof Ge!="string"||Ge!==R)&&ar(y,R)}let Me=P==="next"?1:-1,Be=lo(y)+Me;Ti(y,Re,o,Be),$n(y);return}if(P==="submit-all"){if(!It.current)return;let Pe=(Ne=y.getAttribute("data-tool-call-id"))!=null?Ne:"",Re=It.current.getMessages().find(Ge=>{var Ce;return((Ce=Ge.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),R=(Xe=(tt=je==null?void 0:je.value)==null?void 0:tt.trim())!=null?Xe:"";R&&ar(y,R);let Me=Si(y,Re);It.current.persistAskUserQuestionProgress(Re,{answers:Me,currentIndex:lo(y)});let Be=Uo(Me);to(y,Be||"(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 je=sr(y),R=lo(y),Me=Jr(y),Be=R>=Me-1;if(!je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Zr(eo,Pe),(it=Re.agentMetadata)!=null&&it.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Re),It.current.resolveAskUserQuestion(Re,"(dismissed)"));return}ar(y,"");let Ge=y.querySelector('[data-ask-free-text-input="true"]');if(Ge&&(Ge.value=""),Be){let Ce=Si(y,Re),Lt=Uo(Ce);to(y,Lt||"(skipped)",{source:"submit-all",structured:Ce});return}Ti(y,Re,o,R+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 f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=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;Ei(e,o),Mi(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,f=le.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=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"),f=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),yt=wm(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=f,f.appendChild(c),f.appendChild(yt.element),yt.backdrop&&le.appendChild(yt.backdrop),le.appendChild(f),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=Z=>{var at,it;if(!yt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;Z.preventDefault(),Ro();let he=Z.clientX,Ee=yt.element.getBoundingClientRect().width,Ne=(it=(at=o.features)==null?void 0:at.artifacts)==null?void 0:it.layout,tt=Pe=>{let Re=Un.getBoundingClientRect().width,je=e.classList.contains("persona-artifact-appearance-seamless"),R=je?0:Tm(Un,Ae),Me=je?0:z.getBoundingClientRect().width||6,Be=Ee-(Pe.clientX-he),Ge=km(Be,Re,R,Me,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);yt.element.style.width=`${Ge}px`,yt.element.style.maxWidth="none",jo()},Xe=()=>{O.removeEventListener("pointermove",tt),O.removeEventListener("pointerup",Xe),O.removeEventListener("pointercancel",Xe),no=null;try{z.releasePointerCapture(Z.pointerId)}catch{}};no=Xe,O.addEventListener("pointermove",tt),O.addEventListener("pointerup",Xe),O.addEventListener("pointercancel",Xe);try{z.setPointerCapture(Z.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,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re,je,R;if(!I||!yt||((ue=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||pn(o)&&Mo(o).reveal==="emerge")return;let y=(Z=e.ownerDocument.defaultView)!=null?Z:window,P=(Ee=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Ee:!0,N=(tt=(Ne=o.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?tt:640;if(P&&y.innerWidth<=N||!Am(o,I))return;let V=(it=(at=(Xe=o.launcher)==null?void 0:Xe.width)!=null?at:o.launcherWidth)!=null?it:io,z=(R=(je=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:je.expandedPanelWidth)!=null?R:"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()&&Ue&&(He.peekBanner&&Ue.appendChild(He.peekBanner),Ue.appendChild($e));e.appendChild(ye),Ue&&e.appendChild(Ue);let po=()=>{var Ge,Ce,Lt,st,Xt,cn,Pt,An,dn,Je,lt,Tn,mn,mr,fr,gr,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=(Ge=o.launcher)==null?void 0:Ge.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=Ma(o),No=(br,ka)=>{var Ss;return br==null||br===""?ka:(Ss=Vr(To,br))!=null?Ss:br},Sa="1px solid var(--persona-border)",Aa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ta="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,Sa),ce.style.borderRadius=No(en==null?void 0:en.borderRadius,Ta),ce.style.boxShadow=No(en==null?void 0:en.shadow,Aa),ce.style.overflow="hidden";return}let c=pn(o),f=(Pt=(cn=o.launcher)==null?void 0:cn.sidebarMode)!=null?Pt:!1,h=c||f||((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=Ma(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=(fr=(mr=o.launcher)==null?void 0:mr.mobileFullscreen)!=null?fr:!0,Ae=(Nr=(gr=o.launcher)==null?void 0:gr.mobileBreakpoint)!=null?Nr:640,ue=z.innerWidth<=Ae,Z=O&&ue&&I,he=(qt=(_r=o.launcher)==null?void 0:_r.position)!=null?qt:"bottom-left",Ee=he==="bottom-left"||he==="top-left",Ne=(nr=(hr=o.launcher)==null?void 0:hr.zIndex)!=null?nr:hn,tt=f||Z?"none":"1px solid var(--persona-border)",Xe=Z?"none":f?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&&!Z&&(Xe="none",tt="none");let at=f||Z?"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,Xe),Re=V(P==null?void 0:P.borderRadius,at),je=G.scrollTop;e.style.cssText="",ye.style.cssText="",le.style.cssText="",ce.style.cssText="",G.style.cssText="",$e.style.cssText="";let R=()=>{var jt;if(je<=0)return;((jt=G.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(G.scrollTop===je)return;let Bn=G.scrollHeight-G.clientHeight;Bn<=0||(G.scrollTop=Math.min(je,Bn))})};if(Z){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=`
|
|
30
|
+
`,w.addEventListener("click",()=>{p=x,L.forEach((k,S)=>{let A=S<x;k.classList.toggle("selected",A),k.setAttribute("aria-checked",S===x-1?"true":"false")})}),L.push(w),E.appendChild(w)}f.appendChild(E);let I=null;if(d){let x=document.createElement("div");x.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),x.appendChild(I),f.appendChild(x)}let P=document.createElement("div");P.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{n==null||n(),m.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let x=(I==null?void 0:I.value.trim())||void 0;await t(p,x),m.remove()}catch(x){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),P.appendChild(H),P.appendChild(W),f.appendChild(P),m.appendChild(f),m}function Ym(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:m="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,u=document.createElement("div");u.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,C.appendChild(E),u.appendChild(C);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=m,I.appendChild(P),I.appendChild(H);let W=document.createElement("div");W.className="persona-feedback-numbers";let x=[];for(let N=0;N<=10;N++){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 ${N} out of 10`),$.textContent=String(N),$.dataset.rating=String(N),N<=6?$.classList.add("persona-feedback-detractor"):N<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=N,x.forEach((G,fe)=>{G.classList.toggle("selected",fe===N),G.setAttribute("aria-checked",fe===N?"true":"false")})}),x.push($),W.appendChild($)}L.appendChild(I),L.appendChild(W),u.appendChild(L);let w=null;if(d){let N=document.createElement("div");N.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"),N.appendChild(w),u.appendChild(N)}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(),p.remove()});let A=document.createElement("button");return A.type="button",A.className="persona-feedback-btn persona-feedback-btn-submit",A.textContent=a,A.addEventListener("click",async()=>{if(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}A.disabled=!0,A.textContent="Submitting...";try{let N=(w==null?void 0:w.value.trim())||void 0;await t(f,N),p.remove()}catch(N){A.disabled=!1,A.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),k.appendChild(S),k.appendChild(A),u.appendChild(k),p.appendChild(u),p}var is="persona-chat-history",hx=30*1e3,bx={"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 yx(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=bx[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 Wi(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 vx(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 xx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var zl=e=>!e||typeof e!="object"?{}:{...e},Xm=e=>e.map(t=>({...t,streaming:!1})),Qm=(e,t,n)=>{let o=e!=null&&e.markdown?za(e.markdown):null,r=qa(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,m,p;let a=(l=s.text)!=null?l:"",i=(m=s.message.rawContent)!=null?m: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=Ds(a),r?r(d):d}};function Jm(e){var i,d,l,m;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=(m=e==null?void 0:e.iconStrokeWidth)!=null?m:.5,a=Ee(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 Zm=(e,t,n)=>{var 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,Zc,ed,td,nd,od,rd,sd;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=ru(t),r=_l.getForInstance(o.plugins);o.components&&Pr.registerAll(o.components);let s=Vm(),i=o.persistState===!1?null:(uc=o.storageAdapter)!=null?uc:Um(),d={},l=null,m=!1,p=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&&(m=!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 p(h)});else{let g=c!=null?c:{messages:[],metadata:{}},h=p(g);h.metadata&&(d=zl(h.metadata)),(mc=h.messages)!=null&&mc.length&&(o={...o,initialMessages:h.messages}),(gc=h.artifacts)!=null&&gc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(fc=h.selectedArtifactId)!=null?fc: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:{}});(hc=c.messages)!=null&&hc.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:{},Fr()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[$l],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[aa.message,aa.messageAndClick],E=Ul({parsers:C,handlers:v,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let L=(yc=(bc=o.launcher)==null?void 0:bc.enabled)!=null?yc:!0,I=(xc=(vc=o.launcher)==null?void 0:vc.autoExpand)!=null?xc:!1,P=(wc=o.autoFocusInput)!=null?wc:!1,H=I,W=L,x=(Sc=(Cc=o.layout)==null?void 0:Cc.header)==null?void 0:Sc.layout,w=!1,k=()=>Js(o),S=()=>L||k(),A=k()?!1:L?I:!0,N=!1,$=null,G=()=>{N=!0,$&&clearTimeout($),$=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},fe=Qm(o,E,G),ge=(Tc=(Ac=o.features)==null?void 0:Ac.showReasoning)!=null?Tc:!0,se=(Ec=(kc=o.features)==null?void 0:kc.showToolCalls)!=null?Ec:!0,ke=(Lc=(Mc=o.features)==null?void 0:Mc.showEventStreamToggle)!=null?Lc:!1,be=(Rc=(Ic=o.features)==null?void 0:Ic.scrollToBottom)!=null?Rc:{},xe=`${(Wc=typeof o.persistState=="object"?(Pc=o.persistState)==null?void 0:Pc.keyPrefix:void 0)!=null?Wc:"persona-"}event-stream`,j=ke?new ra(xe):null,de=(Dc=(Hc=(Bc=o.features)==null?void 0:Bc.eventStream)==null?void 0:Hc.maxEvents)!=null?Dc:2e3,K=ke?new oa(de,j):null,ye=ke?new sa:null,le=null,te=!1,Ce=null,Ue=0;j==null||j.open().then(()=>K==null?void 0:K.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ee={onCopy:c=>{var g,h;s.emit("message:copy",c),V!=null&&V.isClientTokenMode()&&V.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),V!=null&&V.isClientTokenMode()&&V.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)}},oe=(Fc=o.statusIndicator)!=null?Fc:{},ae=c=>{var g,h,y,M;return c==="idle"?(g=oe.idleText)!=null?g:xn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:xn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:xn.connected:c==="error"?(M=oe.errorText)!=null?M:xn.error:xn[c]};function rt(c,g,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let M=document.createElement("a");M.href=h.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=g,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=g}let{wrapper:Ae,panel:pe,pillRoot:$e}=am(o),We=im(o,S()),{container:ue,body:X,messagesWrapper:Ne,suggestions:Bt,textarea:he,sendButton:ce,sendButtonWrapper:Rn,composerForm:$t,statusText:mn,introTitle:Dn,introSubtitle:eo,closeButton:ze,iconHolder:_,headerTitle:Me,headerSubtitle:Be,header:He,footer:_e,actionsRow:ut,leftActions:st,rightActions:Rt}=We,qt=We.setSendButtonMode,q=We.micButton,Ut=We.micButtonWrapper,Je=We.attachmentButton,_t=We.attachmentButtonWrapper,re=We.attachmentInput,we=We.attachmentPreviewsContainer;ue.classList.add("persona-relative"),X.classList.add("persona-relative");let Tt=12,jt=()=>{var c;return(c=be.label)!=null?c:""},en=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},Sn=()=>be.enabled!==!1,Pt=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");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let Et=b("span","persona-flex persona-items-center"),xt=b("span","");Pt.append(Et,xt),ue.appendChild(Pt);let Ct=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;Pt.style.bottom=`${g+Tt}px`};Ct();let Kt=()=>{let c=!!jt();Pt.setAttribute("aria-label",jt()||"Jump to latest"),Pt.title=jt(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Et.innerHTML="";let g=Ee(en(),"14px","currentColor",2);g?(Et.appendChild(g),Et.style.display=""):Et.style.display="none",xt.textContent=jt(),xt.style.display=c?"":"none"};Kt();let nt=null,Fn=null,to=r.find(c=>c.renderHeader);if(to!=null&&to.renderHeader){let c=to.renderHeader({config:o,defaultRenderer:()=>{let g=Mr({config:o,showClose:S()});return ea(ue,g,o),g.header},onClose:()=>Ft(!1,"user")});if(c){let g=ue.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),He=c)}}let An=()=>{var g,h,y,M;if(!K)return;if(te=!0,!le&&K&&(le=Rm({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var F;return(F=ye==null?void 0:ye.getMetric())!=null?F:{status:"idle"}}})),le&&(X.style.display="none",(g=_e.parentNode)==null||g.insertBefore(le.element,_e),le.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${In.actionIconColor}`;let F=(M=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:M.toggleButtonActive;F&&F.split(/\s+/).forEach(O=>O&&ht.classList.add(O))}let c=()=>{if(!te)return;let F=Date.now();F-Ue>=200&&(le==null||le.update(),Ue=F),Ce=requestAnimationFrame(c)};Ue=0,Ce=requestAnimationFrame(c),No(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,g,h;if(te){if(te=!1,le&&le.element.remove(),X.style.display="",ht){ht.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(M=>M&&ht.classList.remove(M))}Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),No(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(ke){let c=(Nc=(Oc=o.features)==null?void 0:Oc.eventStream)==null?void 0:Nc.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:"");ht=b("button",g),ht.style.width="28px",ht.style.height="28px",ht.style.color=In.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=Ee("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let y=We.clearChatButtonWrapper,M=We.closeButtonWrapper,F=y||M;F&&F.parentNode===He?He.insertBefore(ht,F):He.appendChild(ht),ht.addEventListener("click",()=>{te?On():An()})}let Eo=c=>{var y,M,F;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 O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(h,O):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=b("input");O.type="file",O.accept=((y=g.allowedTypes)!=null?y:Uo).join(","),O.multiple=((M=g.maxFiles)!=null?M:4)>1,O.style.display="none",O.setAttribute("aria-label",(F=g.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(O)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,g=Nn.renderComposer({config:o,defaultRenderer:()=>Ai({config:o}).footer,onSubmit:h=>{var O;if(!V||V.isStreaming())return;let y=h.trim(),M=(O=nt==null?void 0:nt.hasAttachments())!=null?O:!1;if(!y&&!M)return;ws();let F;M&&(F=[],F.push(...nt.getContentParts()),y&&F.push(fl(y))),V.sendMessage(y,{contentParts:F}),M&&nt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{re==null||re.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((_c=o.voiceRecognition)==null?void 0:_c.enabled)===!0?()=>{Fn==null||Fn()}:void 0});g&&(_e.replaceWith(g),_e=g)}let dr=c=>{let g=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");g&&($t=g),h&&(he=h),y&&(ce=y),M&&(q=M,Ut=M.parentElement),F&&(mn=F);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Bt=O);let z=c.querySelector(".persona-attachment-button");z&&(Je=z,_t=z.parentElement),re=c.querySelector('input[type="file"]'),we=c.querySelector(".persona-attachment-previews");let D=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");D&&(ut=D)};Eo(_e),dr(_e);let Pn=(qc=(Vc=o.layout)==null?void 0:Vc.contentMaxWidth)!=null?qc:k()?(zc=(Uc=($c=o.launcher)==null?void 0:$c.composerBar)==null?void 0:Uc.contentMaxWidth)!=null?zc:"720px":void 0;if(Pn&&(Ne.style.maxWidth=Pn,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%"),Pn&&$t&&!k()&&($t.style.maxWidth=Pn,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Pn&&Bt&&!k()&&(Bt.style.maxWidth=Pn,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Pn&&we&&!k()&&(we.style.maxWidth=Pn,we.style.marginLeft="auto",we.style.marginRight="auto"),(jc=o.attachments)!=null&&jc.enabled&&re&&we){nt=zs.fromConfig(o.attachments),nt.setPreviewsContainer(we),re.addEventListener("change",h=>{let y=h.target;nt==null||nt.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,g=Jm(c);ue.appendChild(g)}(()=>{var y,M;let c=(M=(y=o.layout)==null?void 0:y.slots)!=null?M:{},g=F=>{switch(F){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ne;case"footer-top":return Bt;case"composer":return $t;case"footer-bottom":return mn;default:return null}},h=(F,O)=>{var z;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")He.insertBefore(O,He.firstChild);else if(F==="header-right")He.appendChild(O);else{let D=He.querySelector(".persona-flex-col");D?(z=D.parentNode)==null||z.insertBefore(O,D.nextSibling):He.appendChild(O)}break;case"body-top":{let D=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(O):X.insertBefore(O,X.firstChild);break}case"body-bottom":X.appendChild(O);break;case"footer-top":Bt.replaceWith(O);break;case"footer-bottom":mn.replaceWith(O);break;default:break}};for(let[F,O]of Object.entries(c))if(O)try{let z=O({config:o,defaultContent:()=>g(F)});z&&h(F,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,z)}})();let qo=c=>{var O,z;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")es.has(M)?es.delete(M):es.add(M),dm(M,y);else if(F==="tool")ts.has(M)?ts.delete(M):ts.add(M),pm(M,y,o);else if(F==="approval"){let D=o.approval!==!1?o.approval:void 0,Te=((O=D==null?void 0:D.detailsDisplay)!=null?O:"collapsed")==="expanded",me=(z=Mi.get(M))!=null?z:Te;Mi.set(M,!me),km(M,y,o)}ve.delete(M)};Ne.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),qo(c))}),Ne.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),qo(c))});let Bo=new Map;Ne.addEventListener("click",c=>{var O;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 M=y.getAttribute("data-actions-for");if(!M)return;let F=h.getAttribute("data-action");if(F==="copy"){let D=V.getMessages().find(Te=>Te.id===M);if(D&&ee.onCopy){let Te=D.content||"";navigator.clipboard.writeText(Te).then(()=>{h.classList.add("persona-message-action-success");let me=Ee("check",14,"currentColor",2);me&&(h.innerHTML="",h.appendChild(me)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Ee("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ee.onCopy(D)}}else if(F==="upvote"||F==="downvote"){let D=((O=Bo.get(M))!=null?O:null)===F,Te=F==="upvote"?"thumbs-up":"thumbs-down";if(D){Bo.delete(M),h.classList.remove("persona-message-action-active");let me=Ee(Te,14,"currentColor",2);me&&(h.innerHTML="",h.appendChild(me))}else{let me=F==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${me}"]`);if(Z){Z.classList.remove("persona-message-action-active");let je=Ee(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);je&&(Z.innerHTML="",Z.appendChild(je))}Bo.set(M,F),h.classList.add("persona-message-action-active");let Se=Ee(Te,14,"currentColor",2);Se&&(Se.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Se)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ve=V.getMessages().find(ot=>ot.id===M);Ve&&ee.onFeedback&&ee.onFeedback({type:F,messageId:Ve.id,message:Ve})}}}),Ne.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 M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-approval-action");if(!F)return;let O=F==="approve"?"approved":"denied",D=V.getMessages().find(me=>me.id===M);if(!(D!=null&&D.approval))return;let Te=y.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?V.resolveWebMcpApproval(M,O):V.resolveApproval(D.approval,O)});let St=null,_n=null,Vn={artifacts:[],selectedId:null},Tn=!1,Mt={current:null};Ne.addEventListener("click",c=>{var Z,Se,Le,Ve,ot;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Le=(Se=(Z=o.features)==null?void 0:Z.artifacts)==null?void 0:Se.onArtifactAction)==null?void 0:Le.call(Se,{type:"download",artifactId:y}))===!0)return;let F=V.getArtifactById(y),O=F==null?void 0:F.markdown,z=(F==null?void 0:F.title)||"artifact";if(!O){let je=h.closest("[data-open-artifact]"),mt=je==null?void 0:je.closest("[data-message-id]"),dt=mt==null?void 0:mt.getAttribute("data-message-id");if(dt){let Re=V.getMessages().find(qe=>qe.id===dt);if(Re!=null&&Re.rawContent)try{let qe=JSON.parse(Re.rawContent);O=(Ve=qe==null?void 0:qe.props)==null?void 0:Ve.markdown,z=((ot=qe==null?void 0:qe.props)==null?void 0:ot.title)||z}catch{}}}if(!O)return;let D=new Blob([O],{type:"text/markdown"}),Te=URL.createObjectURL(D),me=document.createElement("a");me.href=Te,me.download=`${z}.md`,me.click(),URL.revokeObjectURL(Te)}),Ne.addEventListener("click",c=>{var F,O,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(O=(F=o.features)==null?void 0:F.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:z.call(O,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Tn=!1,V.selectArtifact(y),zn())}),Ne.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let no=We.composerOverlay,oo=(c,g,h)=>{var z,D,Te,me;let y=g.trim();if(!y||!Mt.current)return;let M=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:y,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?y.split(", "):[y],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),ss(no,M);let O=Mt.current.getMessages().find(Z=>{var Se;return((Se=Z.toolCall)==null?void 0:Se.id)===M});(Te=O==null?void 0:O.agentMetadata)!=null&&Te.awaitingLocalTool?Mt.current.resolveAskUserQuestion(O,(me=h.structured)!=null?me:y):Mt.current.sendMessage(y)},$n=c=>{var M;let g=Mt.current;if(!g)return;let h=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",y=g.getMessages().find(F=>{var O;return((O=F.toolCall)==null?void 0:O.id)===h});y&&g.persistAskUserQuestionProgress(y,{answers:Ti(c,y),currentIndex:fo(c)})},jo=c=>Object.entries(c).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ho=c=>{var M,F,O;if(((F=(M=o.features)==null?void 0:M.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let g=fo(c),h=rs(c);if(g>=h-1)return;let y=(O=Mt.current)==null?void 0:O.getMessages().find(z=>{var D;return((D=z.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});y&&(Ei(c,y,o,g+1),$n(c))};no.addEventListener("click",c=>{var F,O,z,D,Te,me,Z,Se,Le,Ve,ot,je,mt,dt;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 M=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Pe=(F=y.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ss(no,Pe);let Re=(O=Mt.current)==null?void 0:O.getMessages().find(qe=>{var Qe;return((Qe=qe.toolCall)==null?void 0:Qe.id)===Pe});(z=Re==null?void 0:Re.agentMetadata)!=null&&z.awaitingLocalTool&&((D=Mt.current)==null||D.markAskUserQuestionResolved(Re),(Te=Mt.current)==null||Te.resolveAskUserQuestion(Re,"(dismissed)"));return}if(M==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Re=y.getAttribute("data-multi-select")==="true",qe=lr(y);if(qe&&Re){let Qe=Ir(y)[fo(y)],vt=new Set(Array.isArray(Qe)?Qe:[]);vt.has(Pe)?vt.delete(Pe):vt.add(Pe),cr(y,Array.from(vt)),$n(y);return}if(qe){cr(y,Pe),$n(y),Ho(y);return}if(Re){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let vt=y.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=Bl(y).length===0);return}oo(y,Pe,{source:"pick",values:[Pe]});return}if(M==="submit-multi"){let Pe=Bl(y);if(Pe.length===0)return;oo(y,Pe.join(", "),{source:"multi",values:Pe});return}if(M==="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(M==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(M==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Re=(me=Pe==null?void 0:Pe.value)!=null?me:"";if(!Re.trim())return;if(lr(y)){cr(y,Re.trim()),$n(y),Ho(y);return}oo(y,Re,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Mt.current)return;let Pe=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Re=Mt.current.getMessages().find(De=>{var ne;return((ne=De.toolCall)==null?void 0:ne.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(Le=(Se=qe==null?void 0:qe.value)==null?void 0:Se.trim())!=null?Le:"";if(Qe){let De=Ir(y)[fo(y)];(typeof De!="string"||De!==Qe)&&cr(y,Qe)}let vt=M==="next"?1:-1,B=fo(y)+vt;Ei(y,Re,o,B),$n(y);return}if(M==="submit-all"){if(!Mt.current)return;let Pe=(Ve=y.getAttribute("data-tool-call-id"))!=null?Ve:"",Re=Mt.current.getMessages().find(De=>{var ne;return((ne=De.toolCall)==null?void 0:ne.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(je=(ot=qe==null?void 0:qe.value)==null?void 0:ot.trim())!=null?je:"";Qe&&cr(y,Qe);let vt=Ti(y,Re);Mt.current.persistAskUserQuestionProgress(Re,{answers:vt,currentIndex:fo(y)});let B=jo(vt);oo(y,B||"(submitted)",{source:"submit-all",structured:vt});return}if(M==="skip"){if(!Mt.current)return;let Pe=(mt=y.getAttribute("data-tool-call-id"))!=null?mt:"",Re=Mt.current.getMessages().find(ne=>{var et;return((et=ne.toolCall)==null?void 0:et.id)===Pe});if(!Re)return;let qe=lr(y),Qe=fo(y),vt=rs(y),B=Qe>=vt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ss(no,Pe),(dt=Re.agentMetadata)!=null&&dt.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Re),Mt.current.resolveAskUserQuestion(Re,"(dismissed)"));return}cr(y,"");let De=y.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),B){let ne=Ti(y,Re),et=jo(ne);oo(y,et||"(skipped)",{source:"submit-all",structured:ne});return}Ei(y,Re,o,Qe+1),$n(y);return}}),no.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let h=c.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let M=h.value;if(M.trim()){if(lr(y)){cr(y,M.trim()),$n(y),Ho(y);return}oo(y,M,{source:"free-text"})}});let Ko=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=no.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),F=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",Ko);let Un=null,Dt=null,kn=null,ro=null,Go=()=>{};function Do(){ro==null||ro(),ro=null}let Yo=()=>{var O;if(!Un||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Dt.style.removeProperty("position"),Dt.style.removeProperty("left"),Dt.style.removeProperty("top"),Dt.style.removeProperty("bottom"),Dt.style.removeProperty("width"),Dt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Dt)return;let M=10;Dt.style.position="absolute",Dt.style.top="0",Dt.style.bottom="0",Dt.style.width=`${M}px`,Dt.style.zIndex="5";let F=y.offsetWidth-M/2;Dt.style.left=`${Math.max(0,F)}px`},Mo=()=>{},zn=()=>{var h,y,M,F,O;if(!St||!ho(o))return;Ri(e,o),Pi(e,o),Mo();let c=(F=(M=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:M.narrowHostMaxWidth)!=null?F:520,g=pe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),St.update(Vn),Tn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(O=St.backdrop)==null||O.classList.add("persona-hidden")):Vn.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),Go()};if(ho(o)){pe.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(ue),St=Bm(o,{onSelect:h=>{var y;return(y=Mt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Tn=!0,zn()}}),St.element.classList.add("persona-hidden"),Un=g,g.appendChild(c),g.appendChild(St.element),St.backdrop&&pe.appendChild(St.backdrop),pe.appendChild(g),Go=()=>{var y,M,F,O;if(!Un||!St)return;if(!(((F=(M=(y=o.features)==null?void 0:y.artifacts)==null?void 0:M.layout)==null?void 0:F.resizable)===!0)){kn==null||kn(),kn=null,Do(),Dt&&(Dt.remove(),Dt=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Dt){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 D=e.ownerDocument,Te=(O=D.defaultView)!=null?O:window,me=Z=>{var mt,dt;if(!St||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;Z.preventDefault(),Do();let Se=Z.clientX,Le=St.element.getBoundingClientRect().width,Ve=(dt=(mt=o.features)==null?void 0:mt.artifacts)==null?void 0:dt.layout,ot=Pe=>{let Re=Un.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Qe=qe?0:Om(Un,Te),vt=qe?0:z.getBoundingClientRect().width||6,B=Le-(Pe.clientX-Se),De=Nm(B,Re,Qe,vt,Ve==null?void 0:Ve.resizableMinWidth,Ve==null?void 0:Ve.resizableMaxWidth);St.element.style.width=`${De}px`,St.element.style.maxWidth="none",Yo()},je=()=>{D.removeEventListener("pointermove",ot),D.removeEventListener("pointerup",je),D.removeEventListener("pointercancel",je),ro=null;try{z.releasePointerCapture(Z.pointerId)}catch{}};ro=je,D.addEventListener("pointermove",ot),D.addEventListener("pointerup",je),D.addEventListener("pointercancel",je);try{z.setPointerCapture(Z.pointerId)}catch{}};z.addEventListener("pointerdown",me),Dt=z,Un.insertBefore(z,St.element),kn=()=>{z.removeEventListener("pointerdown",me)}}if(Dt){let z=Vn.artifacts.length>0&&!Tn;Dt.classList.toggle("persona-hidden",!z),Yo()}},Mo=()=>{var Te,me,Z,Se,Le,Ve,ot,je,mt,dt,Pe,Re,qe,Qe;if(!L||!St||((me=(Te=o.launcher)==null?void 0:Te.sidebarMode)!=null?me:!1)||hn(o)&&Wo(o).reveal==="emerge")return;let y=(Z=e.ownerDocument.defaultView)!=null?Z:window,M=(Le=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?Le:!0,F=(ot=(Ve=o.launcher)==null?void 0:Ve.mobileBreakpoint)!=null?ot:640;if(M&&y.innerWidth<=F||!Fm(o,L))return;let O=(dt=(mt=(je=o.launcher)==null?void 0:je.width)!=null?mt:o.launcherWidth)!=null?dt:go,z=(Qe=(qe=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:qe.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!Tn?(pe.style.width=z,pe.style.maxWidth=z):(pe.style.width=O,pe.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(pe))}else pe.appendChild(ue),k()&&$e&&(We.peekBanner&&$e.appendChild(We.peekBanner),$e.appendChild(_e));e.appendChild(Ae),$e&&e.appendChild($e);let bo=()=>{var De,ne,et,Nt,Ot,zt,at,ln,Yn,Ke,wt,Xn,on,uo,Qn,hr,zr,qr,Gt,br,rr,sr,$o,yr,tt,yn,gn,cn;if(k()){pe.style.width="100%",pe.style.maxWidth="100%";let gt=(ne=(De=o.launcher)==null?void 0:De.composerBar)!=null?ne:{},it=Ae.dataset.state==="expanded",kt=(et=gt.expandedSize)!=null?et:"anchored";if(!(it&&kt!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Zt=(Ot=(Nt=o.theme)==null?void 0:Nt.components)==null?void 0:Ot.panel,Io=Ia(o),rn=(xr,Ma)=>{var Ls;return xr==null||xr===""?Ma:(Ls=jr(Io,xr))!=null?Ls:xr},Mn="1px solid var(--persona-border)",mo="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",vr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=rn(Zt==null?void 0:Zt.border,Mn),ue.style.borderRadius=rn(Zt==null?void 0:Zt.borderRadius,vr),ue.style.boxShadow=rn(Zt==null?void 0:Zt.shadow,mo),ue.style.overflow="hidden";return}let c=hn(o),g=(at=(zt=o.launcher)==null?void 0:zt.sidebarMode)!=null?at:!1,h=c||g||((Yn=(ln=o.launcher)==null?void 0:ln.fullHeight)!=null?Yn:!1),y=((Ke=o.launcher)==null?void 0:Ke.enabled)===!1,M=(Xn=(wt=o.theme)==null?void 0:wt.components)==null?void 0:Xn.panel,F=Ia(o),O=(gt,it)=>{var kt;return gt==null||gt===""?it:(kt=jr(F,gt))!=null?kt:gt},z=(on=e.ownerDocument.defaultView)!=null?on:window,D=(Qn=(uo=o.launcher)==null?void 0:uo.mobileFullscreen)!=null?Qn:!0,Te=(zr=(hr=o.launcher)==null?void 0:hr.mobileBreakpoint)!=null?zr:640,me=z.innerWidth<=Te,Z=D&&me&&L,Se=(Gt=(qr=o.launcher)==null?void 0:qr.position)!=null?Gt:"bottom-left",Le=Se==="bottom-left"||Se==="top-left",Ve=(rr=(br=o.launcher)==null?void 0:br.zIndex)!=null?rr:wn,ot=g||Z?"none":"1px solid var(--persona-border)",je=Z?"none":g?Le?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(je="none",ot="none");let mt=g||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=O(M==null?void 0:M.border,ot),Pe=O(M==null?void 0:M.shadow,je),Re=O(M==null?void 0:M.borderRadius,mt),qe=X.scrollTop;e.style.cssText="",Ae.style.cssText="",pe.style.cssText="",ue.style.cssText="",X.style.cssText="",_e.style.cssText="";let Qe=()=>{var it;if(qe<=0)return;((it=X.ownerDocument.defaultView)!=null?it:window).requestAnimationFrame(()=>{if(X.scrollTop===qe)return;let kt=X.scrollHeight-X.clientHeight;kt<=0||(X.scrollTop=Math.min(qe,kt))})};if(Z){Ae.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"),Ae.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 Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
37
37
|
padding: 0 !important;
|
|
38
38
|
display: flex !important;
|
|
39
39
|
flex-direction: column !important;
|
|
40
|
-
z-index: ${
|
|
40
|
+
z-index: ${Ve} !important;
|
|
41
41
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
|
-
`,
|
|
42
|
+
`,pe.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 Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
52
52
|
padding: 0 !important;
|
|
53
53
|
box-shadow: none !important;
|
|
54
54
|
border-radius: 0 !important;
|
|
55
|
-
`,
|
|
55
|
+
`,ue.style.cssText=`
|
|
56
56
|
display: flex !important;
|
|
57
57
|
flex-direction: column !important;
|
|
58
58
|
flex: 1 1 0% !important;
|
|
@@ -63,20 +63,20 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
63
63
|
overflow: hidden !important;
|
|
64
64
|
border-radius: 0 !important;
|
|
65
65
|
border: none !important;
|
|
66
|
-
`,
|
|
66
|
+
`,X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0",w=!0,Qe();return}let vt=($o=(sr=o==null?void 0:o.launcher)==null?void 0:sr.width)!=null?$o:o==null?void 0:o.launcherWidth,B=vt!=null?vt:go;if(!g&&!c)y&&h?(pe.style.width="100%",pe.style.maxWidth="100%"):(pe.style.width=B,pe.style.maxWidth=B);else if(c)if(Wo(o).reveal==="emerge"){let it=Wo(o).width;pe.style.width=it,pe.style.maxWidth=it}else pe.style.width="100%",pe.style.maxWidth="100%";if(Mo(),pe.style.boxShadow=Pe,pe.style.borderRadius=Re,ue.style.border=dt,ue.style.borderRadius=Re,c&&!Z&&(M==null?void 0:M.border)===void 0&&(ue.style.border="none",Wo(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.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%"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",y&&(Ae.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.height="100%",pe.style.overflow="hidden",ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0"),Ae.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&&((yr=ko[Se])!=null?yr:ko["bottom-right"]).split(" ").forEach(it=>Ae.classList.add(it)),g){let gt=(yn=(tt=o.launcher)==null?void 0:tt.sidebarWidth)!=null?yn:"420px";Ae.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
70
|
-
width: ${
|
|
70
|
+
width: ${gt} !important;
|
|
71
71
|
height: 100vh !important;
|
|
72
72
|
max-height: 100vh !important;
|
|
73
73
|
margin: 0 !important;
|
|
74
74
|
padding: 0 !important;
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
|
-
z-index: ${
|
|
78
|
-
${
|
|
79
|
-
`,
|
|
77
|
+
z-index: ${Ve} !important;
|
|
78
|
+
${Le?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
|
+
`,pe.style.cssText=`
|
|
80
80
|
position: relative !important;
|
|
81
81
|
display: flex !important;
|
|
82
82
|
flex-direction: column !important;
|
|
@@ -89,7 +89,7 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
89
89
|
padding: 0 !important;
|
|
90
90
|
box-shadow: ${Pe} !important;
|
|
91
91
|
border-radius: ${Re} !important;
|
|
92
|
-
`,
|
|
92
|
+
`,pe.style.setProperty("width","100%","important"),pe.style.setProperty("max-width","100%","important"),ue.style.cssText=`
|
|
93
93
|
display: flex !important;
|
|
94
94
|
flex-direction: column !important;
|
|
95
95
|
flex: 1 1 0% !important;
|
|
@@ -99,12 +99,12 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
99
99
|
max-height: 100% !important;
|
|
100
100
|
overflow: hidden !important;
|
|
101
101
|
border-radius: ${Re} !important;
|
|
102
|
-
border: ${
|
|
103
|
-
|
|
102
|
+
border: ${dt} !important;
|
|
103
|
+
`,_e.style.cssText=`
|
|
104
104
|
flex-shrink: 0 !important;
|
|
105
105
|
border-top: none !important;
|
|
106
106
|
padding: 8px 16px 12px 16px !important;
|
|
107
|
-
`}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",jt=f?"":"padding-top: 1.25em !important;",Bn=f?"":`z-index: ${(Ut=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Ut:hn} !important;`;ye.style.cssText+=Dt+jt+Bn}R()};po(),$r(e,o),Ei(e,o),Mi(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(()=>{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&&ft.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),Se==null||Se.destroy(),Se=null,Y==null||Y.destroy(),Y=null,Q=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=ou(()=>{$r(e,o)}))};Ko(),ft.push(()=>{qn&&(qn(),qn=null)});let oo=(Vc=o.features)==null?void 0:Vc.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=$s(oo.type,oo.plugins);c&&(ml(c,e),ft.push(()=>ju(e)))}let uo=fm(Et),jn=null,E,Kn=!1,mo=_u(),Po=new Map,So=new Map,as=0,fo=ai(),go=0,ho=null,Wo=!1,lr=!1,aa=4,is=24,ia=80,Pr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ls=(Uc=($c=o.voiceRecognition)==null?void 0:$c.autoResume)!=null?Uc:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{p(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},la=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Nl(d.voiceState),f=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-h<nx&&setTimeout(()=>{var N,V;mt.active||(mt.manuallyDeactivated=!1,((V=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:V.type)==="runtype"?E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("restore"),E.isVoiceActive()&&U()}):ur("restore"))},1e3)},ca=()=>E?Fm(E.getMessages()).filter(c=>!c.__skipPersist):[];function Wr(c){if(!(i!=null&&i.save))return;let h={messages:c?Fm(c):E?ca():[],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,da=()=>ye.querySelector("#persona-scroll-container")||G,cr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},cs=()=>{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=Ns(G)>0;Tt.style.display=fo.isFollowing()||!c?"none":""},ds=()=>{fo.pause()&&(cs(),Ho())},Go=()=>{fo.resume(),Ho()},Yo=(c=!1)=>{fo.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!0,ho=requestAnimationFrame(()=>{ho=null,lr=!1,fo.isFollowing()&&pa(da(),c?220:140)})))},pa=(c,f=500)=>{let h=c.scrollTop,y=Ns(c),P=y-h;if(Math.abs(P)<1){go=c.scrollTop;return}if(Math.abs(P)>=ia){cr(),Wo=!0,c.scrollTop=y,go=c.scrollTop,Wo=!1;return}cr();let N=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!fo.isFollowing()){cr();return}let Ae=Ns(c);Ae!==y&&(y=Ae,P=y-h);let ue=O-N,Z=Math.min(ue/f,1),he=V(Z),Ee=h+P*he;c.scrollTop=Ee,go=c.scrollTop,Z<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,go=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},ua=c=>{let f=new Map;c.forEach(h=>{let y=Pr.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Pr.clear(),f.forEach((h,y)=>{Pr.set(y,h)})},dr=(c,f,h)=>{var Xe,at,it,Pe,Re,je;let y=document.createElement("div"),N=(()=>{var Me;let R=r.find(Be=>Be.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Me=o.loadingIndicator)!=null&&Me.render)return o.loadingIndicator.render})(),V=(R,Me)=>Me==null?!1:typeof Me=="string"?(R.textContent=Me,!0):(R.appendChild(Me),!0),z=new Set,O=new Set,Ae=r.some(R=>R.renderAskUserQuestion),ue=[],Z=[],he=o.enableComponentStreaming!==!1;if(f.forEach(R=>{var An,dn,Je,lt,Tn,mn,mr,fr,gr,Nr,_r,qt,hr,nr;z.add(R.id);let Me=Ae&&Tr(R),Be=!Me&&R.role==="assistant"&&!R.variant&&he&&Wm(R);if(!Be&&So.has(R.id)){let ht=c.querySelector(`#wrapper-${R.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),So.delete(R.id)}let Ge=Tr(R)?`:${(An=R.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(dn=R.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ce=Nu(R,as)+Ge,Lt=Me||Be?null:Vu(mo,R.id,Ce);if(Lt){y.appendChild(Lt.cloneNode(!0)),Tr(R)&&((Je=R.toolCall)!=null&&Je.id)&&((lt=R.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((Tn=R.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}let st=null,Xt=r.find(ht=>!!(R.variant==="reasoning"&&ht.renderReasoning||R.variant==="tool"&&ht.renderToolCall||R.variant==="approval"&&ht.renderApproval||!R.variant&&ht.renderMessage)),cn=(mn=o.layout)==null?void 0:mn.messages;if(Tr(R)&&((mr=R.agentMetadata)==null?void 0:mr.askUserQuestionAnswered)===!0){Po.delete(R.id);let ht=c.querySelector(`#wrapper-${R.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(Tr(R)&&((gr=(fr=o.features)==null?void 0:fr.askUserQuestion)==null?void 0:gr.enabled)!==!1){let ht=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&It.current){let Pn=Po.get(R.id),Oo=Pn!==Ce,kn=null;if(Oo){let{payload:Ut,complete:Dt}=Qr(R),jt=R.id,Bn=()=>{var Yn;return(Yn=It.current)==null?void 0:Yn.getMessages().find(en=>en.id===jt)};kn=ht.renderAskUserQuestion({message:R,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=R.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=R.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${R.id}`,Ht.setAttribute("data-wrapper-id",R.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),ue.push({messageId:R.id,fingerprint:Ce,bubble:kn});return}else{((qt=R.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((hr=R.agentMetadata)!=null&&hr.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}}else if(Xt)if(R.variant==="reasoning"&&R.reasoning&&Xt.renderReasoning){if(!se)return;st=Xt.renderReasoning({message:R,defaultRenderer:()=>xl(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&Xt.renderToolCall){if(!fe)return;st=Xt.renderToolCall({message:R,defaultRenderer:()=>wl(R,o),config:o})}else if(R.variant==="approval"&&R.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:R,defaultRenderer:()=>Ll(R,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:R,defaultRenderer:()=>{let ht=vl(R,h,cn,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o});return R.role!=="user"&&Wl(ht,R,o,E),ht},config:o}));if(!st&&Be){let ht=Bm(R);if(ht){let Pn=So.get(R.id),Oo=Pn!==Ce,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Rm(ht,{config:o,message:R,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-${R.id}`,Ut.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.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-${R.id}`,Ut.setAttribute("data-message-id",R.id),Ut.setAttribute("data-persona-component-directive","true"),R.content&&R.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:R.content,message:R,streaming:!!R.streaming,raw:R.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-${R.id}`,Ht.setAttribute("data-wrapper-id",R.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),Z.push({messageId:R.id,fingerprint:Ce,bubble:Wn});return}}}if(!st)if(R.variant==="reasoning"&&R.reasoning){if(!se)return;st=xl(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!fe)return;st=wl(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;st=Ll(R,o)}else{let ht=(nr=o.layout)==null?void 0:nr.messages;ht!=null&&ht.renderUserMessage&&R.role==="user"?st=ht.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):ht!=null&&ht.renderAssistantMessage&&R.role==="assistant"?st=ht.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):st=vl(R,h,ht,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o}),R.role!=="user"&&st&&Wl(st,R,o,E)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${R.id}`,Pt.setAttribute("data-wrapper-id",R.id),R.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,R.id,Ce,Pt),y.appendChild(Pt)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Me=>{let Be=Me.getAttribute("data-persona-ask-sheet-for");Be&&!O.has(Be)&&Zr(He.composerOverlay,Be)}),(at=(Xe=o.features)==null?void 0:Xe.toolCallDisplay)!=null&&at.grouped){let R=[],Me=[];f.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&fe){Me.push(Be);return}Me.length>1&&R.push(Me),Me=[]}),Me.length>1&&R.push(Me),R.forEach((Be,Ge)=>{var dn,Je;let Ce=Be.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-${Ge}-${Be[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Ge}-${Be[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 ${Be.length} tools`,Pt=(Je=(dn=o.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Je.call(dn,{messages:Be,toolCalls:Be.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)})})}Uu(mo,z);let Ee=f.some(R=>R.role==="assistant"&&R.streaming),Ne=f[f.length-1],tt=(Ne==null?void 0:Ne.role)==="assistant"&&!Ne.streaming&&Ne.variant!=="approval";if(Kn&&f.some(R=>R.role==="user")&&!Ee&&!tt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:Ys},Me=r.find(Ge=>Ge.renderLoadingIndicator),Be=null;if(Me!=null&&Me.renderLoadingIndicator&&(Be=Me.renderLoadingIndicator(R)),Be===null&&((it=o.loadingIndicator)!=null&&it.render)&&(Be=o.loadingIndicator.render(R)),Be===null&&(Be=Ys()),Be){let Ge=document.createElement("div"),Ce=((Pe=o.loadingIndicator)==null?void 0:Pe.showBubble)!==!1;Ge.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(" "),Ge.setAttribute("data-typing-indicator","true"),Ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ge.appendChild(Be);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Ge),y.appendChild(Lt)}}if(!Kn&&f.length>0){let R=f[f.length-1],Me={config:o,lastMessage:R,messageCount:f.length},Be=r.find(Ce=>Ce.renderIdleIndicator),Ge=null;if(Be!=null&&Be.renderIdleIndicator&&(Ge=Be.renderIdleIndicator(Me)),Ge===null&&((Re=o.loadingIndicator)!=null&&Re.renderIdle)&&(Ge=o.loadingIndicator.renderIdle(Me)),Ge){let Ce=document.createElement("div"),Lt=((je=o.loadingIndicator)==null?void 0:je.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(Ge);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(ri(c,y),ue.length>0)for(let{messageId:R,fingerprint:Me,bubble:Be}of ue){let Ge=c.querySelector(`#wrapper-${R}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.setAttribute("data-bubble-fp",Me),Po.set(R,Me))}if(Po.size>0)for(let R of Po.keys())z.has(R)||Po.delete(R);if(Z.length>0)for(let{messageId:R,fingerprint:Me,bubble:Be}of Z){let Ge=c.querySelector(`#wrapper-${R}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.setAttribute("data-bubble-fp",Me),So.set(R,Me))}if(So.size>0)for(let R of So.keys())z.has(R)||So.delete(R)},Xo=null,ma=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ye)||Ue&&P.includes(Ue)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ps=()=>{var f;if(!Xo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Xo,!0),Xo=null};ft.push(()=>ps());let Qo=null,fa=()=>{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)},us=()=>{var f;if(!Qo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Qo,!0),Qo=null};ft.push(()=>us());let Jo=!1,ms=new Set,ga=()=>{var f,h,y,P;let c=(y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var at,it,Pe,Re;if(!k())return;let c=He.peekBanner,f=He.peekTextNode;if(!c||!f)return;if(T){c.classList.remove("persona-pill-peek--visible");return}let h=(at=E==null?void 0:E.getMessages())!=null?at:[],y;for(let je=h.length-1;je>=0;je--){let R=h[je];if(R.role==="assistant"&&R.content){y=R;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,N=!!y.streaming,V=ga(),z=ci(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&&!ms.has(O.name)&&(ml(O,e),ms.add(O.name));let Z=ue&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Pe=f.dataset.personaPeekStreamClass)!=null?Pe:null;he&&he!==Z&&(f.classList.remove(he),delete f.dataset.personaPeekStreamClass),Z&&he!==Z&&(f.classList.add(Z),f.dataset.personaPeekStreamClass=Z),ue?(f.style.setProperty("--persona-stream-step",`${z.speed}ms`),f.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ee=ue?di(P,z.buffer,O,y,N):P;if(ue&&z.placeholder==="skeleton"&&N&&(!Ee||!Ee.trim())){let je=document.createElement("div"),R=zs();R.classList.add("persona-pill-peek__skeleton"),je.appendChild(R),ri(f,je)}else{let je=Math.max(0,Ee.length-100),R=Ee.length>100?Ee.slice(-100):Ee,Me=Is(R);if(!ue||!O){let Be=Ee.length>100?`\u2026${R}`:R;f.textContent!==Be&&(f.textContent=Be)}else{let Be=Me;(O.wrap==="char"||O.wrap==="word")&&(Be=Us(Me,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:je}));let Ge=document.createElement("div");if(Ge.innerHTML=Be,O.useCaret&&R.length>0){let Ce=pi(),Lt=Ge.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=Lt[Lt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(Ce,st.nextSibling):Ge.appendChild(Ce)}ri(f,Ge),(Re=O.onAfterRender)==null||Re.call(O,{container:f,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Xe=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Xe)};if(k()){let c=He.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),ft.push(()=>{c.removeEventListener("pointerdown",y)})}let f=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};le.addEventListener("pointerenter",f),le.addEventListener("pointerleave",h),ft.push(()=>{le.removeEventListener("pointerenter",f),le.removeEventListener("pointerleave",h)}),Ue&&(Ue.addEventListener("pointerenter",f),Ue.addEventListener("pointerleave",h),ft.push(()=>{Ue.removeEventListener("pointerenter",f),Ue.removeEventListener("pointerleave",h)}))}let ha=c=>{var he,Ee,Ne,tt,Xe,at,it,Pe;let f=(Ee=(he=o.launcher)==null?void 0:he.composerBar)!=null?Ee:{},h=(Ne=f.expandedSize)!=null?Ne:"anchored",y=(tt=f.bottomOffset)!=null?tt:"16px",P=f.collapsedMaxWidth,N=(Xe=f.expandedMaxWidth)!=null?Xe:"880px",V=(at=f.expandedTopOffset)!=null?at:"5vh",z=(it=f.modalMaxWidth)!=null?it:"880px",O=(Pe=f.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",Z=ye.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Ue){let Re=Ue.style;Re.bottom=y,Re.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=z,Z.maxWidth=Ae,Z.maxHeight=O,Z.height=O;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${ue})`,Z.top=V,Z.width=N,Z.maxWidth=Ae}},Zo=()=>{var O,Ae,ue,Z,he,Ee,Ne,tt;if(!C())return;if(k()){let at=(ue=((Ae=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",it=T?"expanded":"collapsed";ye.dataset.state=it,ye.dataset.expandedSize=at,Ue&&(Ue.dataset.state=it,Ue.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"),ha(T),ce.style.display=T?"flex":"none",po(),T?(ma(),fa()):(ps(),us()),Do();return}let c=pn(o),f=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Ee=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ee:640,y=(tt=(Ne=o.launcher)==null?void 0:Ne.mobileFullscreen)!=null?tt:!0,P=f.innerWidth<=h,N=y&&P&&I,V=Mo(o).reveal;T?(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":Ye&&(Ye.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":"":Ye&&(Ye.style.display=c?"none":""))},Bt=(c,f="user")=>{var N,V;if(!C()||T===c)return;let h=T;T=c,Zo();let y=(()=>{var Ne,tt,Xe,at,it,Pe,Re,je,R,Me;let z=(tt=(Ne=o.launcher)==null?void 0:Ne.sidebarMode)!=null?tt:!1,O=(Xe=e.ownerDocument.defaultView)!=null?Xe: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,Z=O.innerWidth<=ue,he=pn(o)&&Ae&&Z,Ee=k()&&((Me=(R=(je=o.launcher)==null?void 0:je.composerBar)==null?void 0:R.expandedSize)!=null?Me:"fullscreen")==="fullscreen";return z||Ae&&Z&&I||he||Ee})();if(T&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=fl(O,(V=(N=o.launcher)==null?void 0:N.zIndex)!=null?V:hn))}Gt||(Gt=gl(e.ownerDocument))}else T||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);T&&(Rt(),Yo(!0));let P={open:T,source:f,timestamp:Date.now()};T&&!h?s.emit("widget:opened",P):!T&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:T,launcherEnabled:I,voiceActive:mt.active,streaming:E.isStreaming()})},Br=c=>{Vt(c?"stop":"send"),q&&(q.disabled=c),uo.buttons.forEach(f=>{f.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Hr=()=>{mt.active||pe&&pe.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hr(),200)});let fs=()=>{var h,y,P,N,V,z,O,Ae,ue,Z,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=G.querySelector("[data-persona-intro-card]");if(c){let Ee=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ee?"":"none",Ee?(G.classList.remove("persona-gap-3"),G.classList.add("persona-gap-6")):(G.classList.remove("persona-gap-6"),G.classList.add("persona-gap-3"))}!((ue=(Ae=o.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(E!=null&&E.isStreaming())&&(ae.textContent=(he=(Z=o.copy)==null?void 0:Z.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=>{p(f=>({...f,sessionId:c}))}});let Ao=null,ba=()=>{Ao==null&&(Ao=setInterval(()=>{let c=Ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let f=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=ja(f-y))})},100))};if(E=new ni(o,{onMessagesChanged(c){dr(Ve,c,me),ba(),E&&(c.some(P=>P.role==="user")?uo.render([],E,pe,c):uo.render(o.suggestionChips,E,pe,c,o.suggestionChipsConfig)),Yo(!Kn),ua(c);let f=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;f&&f.id!==h&&(mt.lastUserMessageId=f.id,s.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Wr(c),Do()},onStatusChanged(c){var y;let f=(y=o.statusIndicator)!=null?y:{};nt(ln,(P=>{var N,V,z,O;return P==="idle"?(N=f.idleText)!=null?N:gn.idle:P==="connecting"?(V=f.connectingText)!=null?V:gn.connecting:P==="connected"?(z=f.connectedText)!=null?z:gn.connected:P==="error"?(O=f.errorText)!=null?O:gn.error:gn[P]})(c),f,c)},onStreamingChanged(c){Kn=c,Br(c),E&&dr(Ve,E.getMessages(),me),c||Yo(!0),Do()},onVoiceStatusChanged(c){var f,h;if(((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":ee(),B();break;case"speaking":ee(),J();break;default:c==="idle"&&E.isBargeInActive()?(ee(),U(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,ee(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Wr()}}),It.current=E,((qc=(zc=o.voiceRecognition)==null?void 0:zc.provider)==null?void 0:qc.type)==="runtype")try{E.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&E.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Y||o.onSSEEvent)&&E.setSSEEventCallback((c,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,f),xe==null||xe.processEvent(c,f),Y==null||Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,h,y;c&&(c.metadata&&(d=Nl(c.metadata),M.syncFromMetadata()),(f=c.messages)!=null&&f.length&&E.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&E.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 f,h,y;!k()||T||!((y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},hs=c=>{var P;if(c.preventDefault(),E.isStreaming()){E.cancel(),xe==null||xe.reset(),Se==null||Se.update();return}let f=pe.value.trim(),h=(P=et==null?void 0:et.hasAttachments())!=null?P:!1;if(!f&&!h)return;gs();let y;h&&(y=[],y.push(...et.getContentParts()),f&&y.push(cl(f))),pe.value="",pe.style.height="auto",pr(),E.sendMessage(f,{contentParts:y}),h&&et.clearAttachments()},ya=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Dr={...si},Fr=!1,pr=()=>{Dr={...si}},va=()=>E.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),xa=c=>{if(!pe)return;Fr=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Fr=!1;let f=pe.value.length;pe.setSelectionRange(f,f)},bs=()=>{Fr||pr()},ys=c=>{if(pe){if(ya()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=pe.selectionStart===0&&pe.selectionEnd===0,h=Ou({direction:c.key==="ArrowUp"?"up":"down",history:va(),currentValue:pe.value,atStart:f,state:Dr});if(Dr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&xa(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(E.isStreaming()){c.preventDefault();return}pr(),c.preventDefault(),ae.click()}}},vs=c=>{c.key!=="Escape"||c.isComposing||E.isStreaming()&&c.composedPath().includes(ce)&&(E.cancel(),xe==null||xe.reset(),Se==null||Se.update(),pr(),c.preventDefault(),c.stopImmediatePropagation())},xs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let f=rx(c.clipboardData);f.length!==0&&(c.preventDefault(),await et.handleFiles(f))},Cn=null,Gn=!1,Fo=null,rt=null,ws=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ur=(c="user")=>{var N,V,z,O,Ae,ue,Z;if(Gn||E.isStreaming())return;let f=ws();if(!f)return;Cn=new f;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="",Ne="";for(let Xe=0;Xe<he.results.length;Xe++){let at=he.results[Xe],it=at[0].transcript;at.isFinal?Ee+=it+" ":Ne=it}let tt=P+Ee+Ne;pe.value=tt,Fo&&clearTimeout(Fo),(Ee||Ne)&&(Fo=window.setTimeout(()=>{let Xe=pe.value.trim();Xe&&Cn&&Gn&&(bo(),pe.value="",pe.style.height="auto",E.sendMessage(Xe,{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",E.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((Z=(ue=he.iconSize)!=null?ue:(Ae=o.sendButton)==null?void 0:Ae.size)!=null?Z:"40")||24};let Ee=he.recordingBackgroundColor,Ne=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=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let Xe=q.querySelector("svg");Xe&&Xe.setAttribute("stroke",Ne)}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 f=q.querySelector("svg");f&&f.setAttribute("stroke",rt.color||"currentColor"),rt=null}q.setAttribute("aria-label","Start voice recognition")}}},wa=(c,f)=>{var at,it,Pe,Re,je,R,Me,Be;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=f==null?void 0:f.size)!=null?Pe:"40px",Ae=(Re=c==null?void 0:c.iconSize)!=null?Re:O,ue=parseFloat(Ae)||24,Z=(je=c==null?void 0:c.backgroundColor)!=null?je:f==null?void 0:f.backgroundColor,he=(R=c==null?void 0:c.iconColor)!=null?R:f==null?void 0:f.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 Ne=Te(z,ue,he||"currentColor",1.5);Ne?V.appendChild(Ne):V.textContent="\u{1F3A4}",Z?V.style.backgroundColor=Z: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(((Be=c==null?void 0:c.showTooltip)!=null?Be:!1)&&tt){let Ge=b("div","persona-send-button-tooltip");Ge.textContent=tt,N.appendChild(Ge)}return{micButton:V,micButtonWrapper:N}},er=()=>{var f,h,y,P,N;if(!q||rt)return;let c=(f=o.voiceRecognition)!=null?f:{};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}},Ke=(c,f)=>{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,f,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:{},f=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f!=null?f:"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")},B=()=>{var z,O,Ae,ue,Z,he,Ee,Ne;if(!q)return;er();let c=(z=o.voiceRecognition)!=null?z:{},f=E.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=(Z=c.processingBackgroundColor)!=null?Z:rt==null?void 0:rt.backgroundColor)!=null?he:"",N=(Ne=(Ee=c.processingBorderColor)!=null?Ee:rt==null?void 0:rt.borderColor)!=null?Ne:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=P,q.style.borderColor=N;let V=y||"currentColor";q.style.color=V,Ke(h,V),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},J=()=>{var Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re;if(!q)return;er();let c=(Ae=o.voiceRecognition)!=null?Ae:{},f=E.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,P=(Ne=c.speakingIconColor)!=null?Ne:f==="barge-in"?(he=(Z=c.recordingIconColor)!=null?Z:rt==null?void 0:rt.color)!=null?he:"":(Ee=rt==null?void 0:rt.color)!=null?Ee:"",N=(at=c.speakingBackgroundColor)!=null?at:f==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=rt==null?void 0:rt.backgroundColor)!=null?Xe:"",V=(Re=c.speakingBorderColor)!=null?Re:f==="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,Ke(y,z);let O=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",O),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},ee=()=>{var c,f,h;q&&(A(),rt&&(q.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",q.style.color=(f=rt.color)!=null?f:"",q.style.borderColor=(h=rt.borderColor)!=null?h:"",Ke(rt.iconName,rt.color||"currentColor"),rt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},K=()=>{var c,f;if(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let h=E.getVoiceStatus(),y=E.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){E.stopVoicePlayback();return}if(E.isBargeInActive()){E.stopVoicePlayback(),E.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),ee()});return}E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),mt.manuallyDeactivated=!E.isVoiceActive(),Rn(),ro("user"),E.isVoiceActive()?U():ee()});return}if(Gn){let h=pe.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(pe.value="",pe.style.height="auto",E.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),ur("user")};Fn=K,q&&(q.addEventListener("click",K),ft.push(()=>{var c,f;((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(E.isVoiceActive()&&E.toggleVoice(),ee()):bo("system"),q&&q.removeEventListener("click",K)}));let We=s.on("assistant:complete",()=>{ls&&(mt.active||mt.manuallyDeactivated||ls==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("auto"),E.isVoiceActive()&&U()}):ur("auto"))},600))});ft.push(We);let _e=s.on("action:resubmit",()=>{setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)});ft.push(_e);let Ze=()=>{Bt(!T,"user")},Ie=null,Ye=null;if(I&&!k()){let c=r.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:o,defaultRenderer:()=>Ks(o,Ze).element,onToggle:Ze});f&&(Ye=f)}Ye||(Ie=Ks(o,Ze))}Ie?e.appendChild(Ie.element):Ye&&e.appendChild(Ye),Zo(),uo.render(o.suggestionChips,E,pe,void 0,o.suggestionChipsConfig),fs(),Br(E.isStreaming()),Yo(!0),la(),H&&(!I||k()?setTimeout(()=>Hr(),0):T&&setTimeout(()=>Hr(),200));let Rt=()=>{var O,Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re,je,R,Me,Be,Ge,Ce,Lt,st,Xt;if(k()){bt(),Zo();return}let c=pn(o),f=(Ae=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ae:!1,h=c||f||((Z=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?Z:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Ne=(Ee=o.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Ne:!0,N=(Xe=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Xe: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(!f&&!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(),T&&I){let Pt=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((Me=(R=o.launcher)==null?void 0:R.mobileBreakpoint)!=null?Me:640),An=(Ge=(Be=o.launcher)==null?void 0:Be.sidebarMode)!=null?Ge:!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=fl(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=(jc=e.ownerDocument.defaultView)!=null?jc:window;if(nn.addEventListener("resize",Rt),ft.push(()=>nn.removeEventListener("resize",Rt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe($e),ft.push(()=>c.disconnect())}go=G.scrollTop;let Ct=G.scrollHeight,Mt=()=>{let c=G.scrollTop,f=G.scrollHeight,h=f<Ct;Ct=f;let{action:y,nextLastScrollTop:P}=ii({following:fo.isFollowing(),currentScrollTop:c,lastScrollTop:go,nearBottom:_s(G,is),userScrollThreshold:aa,isAutoScrolling:Wo||lr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(go=P,y==="resume"){Go();return}y==="pause"&&ds()};G.addEventListener("scroll",Mt,{passive:!0}),ft.push(()=>G.removeEventListener("scroll",Mt));let on=c=>{let f=li({following:fo.isFollowing(),deltaY:c.deltaY,nearBottom:_s(G,is),resumeWhenNearBottom:!0});f==="pause"?ds():f==="resume"&&Go()};G.addEventListener("wheel",on,{passive:!0}),ft.push(()=>G.removeEventListener("wheel",on)),Tt.addEventListener("click",()=>{G.scrollTop=G.scrollHeight,go=G.scrollTop,Go(),Yo(!0)}),ft.push(()=>Tt.remove()),ft.push(()=>{cs()});let un=()=>{qe&&(jn&&(qe.removeEventListener("click",jn),jn=null),C()?(qe.style.display="",jn=()=>{Bt(!1,"user")},qe.addEventListener("click",jn)):qe.style.display="none")};un(),(()=>{let{clearChatButton:c}=He;c&&c.addEventListener("click",()=>{E.clearMessages(),mo.clear(),Go(),Zr(He.composerOverlay);try{localStorage.removeItem(ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ts}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()})})(),Nt&&Nt.addEventListener("submit",hs),pe==null||pe.addEventListener("keydown",ys),pe==null||pe.addEventListener("input",bs),pe==null||pe.addEventListener("paste",xs);let Yt=(Kc=e.ownerDocument)!=null?Kc:document;Yt.addEventListener("keydown",vs,!0);let so="persona-attachment-drop-active",Cs=0,qi=()=>{Cs=0,ce.classList.remove(so)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},ec=c=>{!Li(c.dataTransfer)||!Or()||(Cs++,Cs===1&&ce.classList.add(so))},tc=c=>{!Li(c.dataTransfer)||!Or()||(Cs--,Cs<=0&&qi())},nc=c=>{!Li(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},oc=c=>{var h;if(!Li(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),qi();let f=Array.from((h=c.dataTransfer.files)!=null?h:[]);f.length!==0&&et.handleFiles(f)},tr=!0;ce.addEventListener("dragenter",ec,tr),ce.addEventListener("dragleave",tc,tr),e.addEventListener("dragover",nc,tr),e.addEventListener("drop",oc,tr);let Ca=e.ownerDocument,rc=c=>{Or()&&c.preventDefault()},sc=c=>{Or()&&c.preventDefault()};Ca.addEventListener("dragover",rc),Ca.addEventListener("drop",sc),ft.push(()=>{Nt&&Nt.removeEventListener("submit",hs),pe==null||pe.removeEventListener("keydown",ys),pe==null||pe.removeEventListener("input",bs),pe==null||pe.removeEventListener("paste",xs),Yt.removeEventListener("keydown",vs,!0)}),ft.push(()=>{ce.removeEventListener("dragenter",ec,tr),ce.removeEventListener("dragleave",tc,tr),e.removeEventListener("dragover",nc,tr),e.removeEventListener("drop",oc,tr),Ca.removeEventListener("dragover",rc),Ca.removeEventListener("drop",sc),qi()}),ft.push(()=>{E.cancel()}),Ie?ft.push(()=>{Ie==null||Ie.destroy()}):Ye&&ft.push(()=>{Ye==null||Ye.remove()});let Zt={update(c){var en,To,No,Sa,Aa,Ta,br,ka,Ss,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,fd,gd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,fp,gp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp;let f=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=(Sa=o.features)==null?void 0:Sa.toolCallDisplay,ue=(Aa=o.features)==null?void 0:Aa.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ei(e,o),Mi(e,o),zn(),o.colorScheme!==P&&Ko();let Z=Hl.getForInstance(o.plugins);r.length=0,r.push(...Z),I=(br=(Ta=o.launcher)==null?void 0:Ta.enabled)!=null?br:!0,L=(Ss=(ka=o.launcher)==null?void 0:ka.autoExpand)!=null?Ss:!1,se=(td=(ed=o.features)==null?void 0:ed.showReasoning)!=null?td:!0,fe=(od=(nd=o.features)==null?void 0:nd.showToolCalls)!=null?od:!0,be=(sd=(rd=o.features)==null?void 0:rd.scrollToBottom)!=null?sd:{},zt(),Ho();let he=ie;if(ie=(id=(ad=o.features)==null?void 0:ad.showEventStreamToggle)!=null?id:!1,ie&&!he){if(Y||(Q=new Js(ve),Y=new Qs(Le,Q),xe=xe!=null?xe:new Zs,Q.open().then(()=>Y==null?void 0:Y.restore()).catch(()=>{}),E.setSSEEventCallback((X,vt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,X,vt),xe==null||xe.processEvent(X,vt),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!ut&&Fe){let X=(cd=(ld=o.features)==null?void 0:ld.eventStream)==null?void 0:cd.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");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=He.clearChatButtonWrapper,kt=He.closeButtonWrapper,rn=ct||kt;rn&&rn.parentNode===Fe?Fe.insertBefore(ut,rn):Fe.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),Y==null||Y.clear(),Q==null||Q.destroy(),Y=null,Q=null,xe==null||xe.reset(),xe=null);if(((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Ie&&(Ie.destroy(),Ie=null),((pd=o.launcher)==null?void 0:pd.enabled)===!1&&Ye&&(Ye.remove(),Ye=null),((ud=o.launcher)==null?void 0:ud.enabled)!==!1&&!Ie&&!Ye){let X=r.find(vt=>vt.renderLauncher);if(X!=null&&X.renderLauncher){let vt=X.renderLauncher({config:o,defaultRenderer:()=>Ks(o,Ze).element,onToggle:Ze});vt&&(Ye=vt,e.appendChild(Ye))}Ye||(Ie=Ks(o,Ze),e.appendChild(Ie.element))}Ie&&Ie.update(o),ke&&((md=o.launcher)==null?void 0:md.title)!==void 0&&(ke.textContent=o.launcher.title),De&&((fd=o.launcher)==null?void 0:fd.subtitle)!==void 0&&(De.textContent=o.launcher.subtitle);let Ee=(gd=o.layout)==null?void 0:gd.header;if((Ee==null?void 0:Ee.layout)!==v&&Fe){let X=Ee?gi(o,Ee,{showClose:C(),onClose:()=>Bt(!1,"user")}):Ar({config:o,showClose:C(),onClose:()=>Bt(!1,"user")});Fe.replaceWith(X.header),Fe=X.header,_=X.iconHolder,ke=X.headerTitle,De=X.headerSubtitle,qe=X.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":""),De&&(De.style.display=Ee.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ee.showCloseButton===!1?"none":""),He.clearChatButtonWrapper)){let X=Ee.showClearChat;if(X!==void 0){He.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:vt}=He;vt&&!vt.classList.contains("persona-absolute")&&(X?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let tt=((hd=o.layout)==null?void 0:hd.showHeader)!==!1;Fe&&(Fe.style.display=tt?"":"none");let Xe=((bd=o.layout)==null?void 0:bd.showFooter)!==!1;$e&&($e.style.display=Xe?"":"none"),bt(),Ho(),I!==W?I?Bt(L,"auto"):(T=!0,Zo()):L!==D&&Bt(L,"auto"),D=L,W=I,Rt(),un();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(f),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((yd=o.layout)==null?void 0:yd.messages)!==JSON.stringify(y),R=((vd=o.loadingIndicator)==null?void 0:vd.render)!==(N==null?void 0:N.render)||((xd=o.loadingIndicator)==null?void 0:xd.renderIdle)!==(N==null?void 0:N.renderIdle)||((wd=o.loadingIndicator)==null?void 0:wd.showBubble)!==(N==null?void 0:N.showBubble),Me=o.iterationDisplay!==V,Be=((Sd=(Cd=o.features)==null?void 0:Cd.showReasoning)!=null?Sd:!0)!==(z!=null?z:!0)||((Td=(Ad=o.features)==null?void 0:Ad.showToolCalls)!=null?Td:!0)!==(O!=null?O:!0)||JSON.stringify((kd=o.features)==null?void 0:kd.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((Ed=o.features)==null?void 0:Ed.reasoningDisplay)!==JSON.stringify(ue);(Pe||Re||je||R||Me||Be)&&E&&(as++,dr(Ve,E.getMessages(),me));let Ce=(Md=o.launcher)!=null?Md:{},Lt=(Ld=Ce.headerIconHidden)!=null?Ld:!1,st=(Rd=(Id=o.layout)==null?void 0:Id.header)==null?void 0:Rd.showIcon,Xt=Lt||st===!1,cn=Ce.headerIconName,Pt=(Pd=Ce.headerIconSize)!=null?Pd:"48px";if(_){let X=ce.querySelector(".persona-border-b-persona-divider"),vt=X==null?void 0:X.querySelector(".persona-flex-col");if(Xt)_.style.display="none",X&&vt&&!X.contains(vt)&&X.insertBefore(vt,X.firstChild);else{if(_.style.display="",_.style.height=Pt,_.style.width=Pt,X&&vt&&(X.contains(_)?_.nextSibling!==vt&&(_.remove(),X.insertBefore(_,vt)):X.insertBefore(_,vt)),cn){let ct=parseFloat(Pt)||24,kt=Te(cn,ct*.6,"#ffffff",2);kt?_.replaceChildren(kt):_.textContent=(Wd=Ce.agentIconText)!=null?Wd:"\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=(Bd=Ce.agentIconText)!=null?Bd:"\u{1F4AC}"}let Ot=_.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Dd=(Hd=o.layout)==null?void 0:Hd.header)==null?void 0:Dd.showTitle,dn=(Od=(Fd=o.layout)==null?void 0:Fd.header)==null?void 0:Od.showSubtitle;if(ke&&(ke.style.display=An===!1?"none":""),De&&(De.style.display=dn===!1?"none":""),qe){((_d=(Nd=o.layout)==null?void 0:Nd.header)==null?void 0:_d.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let vt=(Vd=Ce.closeButtonSize)!=null?Vd:"32px",Ot=($d=Ce.closeButtonPlacement)!=null?$d:"inline";qe.style.height=vt,qe.style.width=vt;let{closeButtonWrapper:ct}=He,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=(zd=(Ud=Ce.clearChat)==null?void 0:Ud.placement)!=null?zd:"inline",sn=(jd=(qd=Ce.clearChat)==null?void 0:qd.enabled)!=null?jd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=ce.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ct)}if(qe.style.color=Ce.closeButtonColor||Mn.actionIconColor,Ce.closeButtonBackgroundColor?(qe.style.backgroundColor=Ce.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let pt=Ce.closeButtonBorderWidth||"0px",sn=Ce.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${sn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(qe.style.borderRadius=Ce.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(qe.style.paddingLeft=Ce.closeButtonPaddingX,qe.style.paddingRight=Ce.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Ce.closeButtonPaddingY?(qe.style.paddingTop=Ce.closeButtonPaddingY,qe.style.paddingBottom=Ce.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let fn=(Kd=Ce.closeButtonIconName)!=null?Kd:"x",yo=(Gd=Ce.closeButtonIconText)!=null?Gd:"\xD7";qe.innerHTML="";let En=Te(fn,"28px","currentColor",1);En?qe.appendChild(En):qe.textContent=yo;let Qt=(Yd=Ce.closeButtonTooltipText)!=null?Yd:"Close chat",Xn=(Xd=Ce.closeButtonShowTooltip)!=null?Xd:!0;if(qe.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!qe)return;let yr=qe.ownerDocument,As=yr.body;if(!As)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let Ts=Eo(yr,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);let vr=qe.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%)",As.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),qe.addEventListener("focus",sn),qe.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",sn),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:lt}=He;if(Je){let X=(Qd=Ce.clearChat)!=null?Qd:{},vt=(Jd=X.enabled)!=null?Jd:!0,Ot=(ep=(Zd=o.layout)==null?void 0:Zd.header)==null?void 0:ep.showClearChat,ct=Ot!==void 0?Ot:vt,kt=(tp=X.placement)!=null?tp:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:rn}=He;!k()&&rn&&!rn.classList.contains("persona-absolute")&&(ct?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let fn=kt==="top-right",yo=lt.classList.contains("persona-absolute");if(!k()&&fn!==yo&&ct){if(lt.remove(),fn)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=He.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(lt,Xn):Qt&&Qt.appendChild(lt)}let En=He.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(fn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ct){if(!k()){let pt=(np=X.size)!=null?np:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(op=X.iconName)!=null?op:"refresh-cw",fn=(rp=X.iconColor)!=null?rp:"";Je.style.color=fn||Mn.actionIconColor,Je.innerHTML="";let yo=k()?"14px":"20px",En=Te(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),X.backgroundColor?(Je.style.backgroundColor=X.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let pt=X.borderWidth||"0px",sn=X.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");X.borderRadius?(Je.style.borderRadius=X.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),X.paddingX?(Je.style.paddingLeft=X.paddingX,Je.style.paddingRight=X.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),X.paddingY?(Je.style.paddingTop=X.paddingY,Je.style.paddingBottom=X.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(sp=X.tooltipText)!=null?sp:"Clear chat",Xn=(ap=X.showTooltip)!=null?ap:!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,As=yr.body;if(!As)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let Ts=Eo(yr,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);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%)",As.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:[Fl],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ea.message,ea.messageAndClick];M=Ol({parsers:Tn,handlers:mn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Om(o,M,j),E.updateConfig(o),dr(Ve,E.getMessages(),me),uo.render(o.suggestionChips,E,pe,void 0,o.suggestionChipsConfig),fs(),Br(E.isStreaming());let mr=((ip=o.voiceRecognition)==null?void 0:ip.enabled)===!0,fr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gr=((cp=(lp=o.voiceRecognition)==null?void 0:lp.provider)==null?void 0:cp.type)==="runtype";if(mr&&(fr||gr))if(!q||!_t){let X=wa(o.voiceRecognition,o.sendButton);X&&(q=X.micButton,_t=X.micButtonWrapper,At.insertBefore(_t,Ln),q.addEventListener("click",K),q.disabled=E.isStreaming())}else{let X=(dp=o.voiceRecognition)!=null?dp:{},vt=(pp=o.sendButton)!=null?pp:{},Ot=(up=X.iconName)!=null?up:"mic",ct=(mp=vt.size)!=null?mp:"40px",kt=(fp=X.iconSize)!=null?fp:ct,rn=parseFloat(kt)||24;q.style.width=kt,q.style.height=kt,q.style.minWidth=kt,q.style.minHeight=kt;let fn=(hp=(gp=X.iconColor)!=null?gp:vt.textColor)!=null?hp:"currentColor";q.innerHTML="";let yo=Te(Ot,rn,fn,2);yo?q.appendChild(yo):q.textContent="\u{1F3A4}";let En=(bp=X.backgroundColor)!=null?bp:vt.backgroundColor;En?q.style.backgroundColor=En:q.style.backgroundColor="",fn?q.style.color=fn:q.style.color="var(--persona-text, #111827)",X.borderWidth?(q.style.borderWidth=X.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),X.borderColor?q.style.borderColor=X.borderColor:q.style.borderColor="",X.paddingX?(q.style.paddingLeft=X.paddingX,q.style.paddingRight=X.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),X.paddingY?(q.style.paddingTop=X.paddingY,q.style.paddingBottom=X.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Qt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Xn=(yp=X.tooltipText)!=null?yp:"Start voice recognition";if(((vp=X.showTooltip)!=null?vp:!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=E.isStreaming()}else q&&_t&&(_t.style.display="none",((wp=(xp=o.voiceRecognition)==null?void 0:xp.provider)==null?void 0:wp.type)==="runtype"?E.isVoiceActive()&&E.toggleVoice():Gn&&bo());if(((Cp=o.attachments)==null?void 0:Cp.enabled)===!0)if(!Ft||!Qe){let X=(Sp=o.attachments)!=null?Sp:{},Ot=(Tp=((Ap=o.sendButton)!=null?Ap:{}).size)!=null?Tp:"40px";ge||(ge=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",Nt.insertBefore(ge,pe)),oe||(oe=document.createElement("input"),oe.type="file",oe.accept=((kp=X.allowedTypes)!=null?kp:_o).join(","),oe.multiple=((Ep=X.maxFiles)!=null?Ep: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",(Mp=X.buttonTooltipText)!=null?Mp:"Attach file");let ct=(Lp=X.buttonIconName)!=null?Lp:"paperclip",kt=Ot,rn=parseFloat(kt)||40,fn=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,fn,"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=(Ip=X.buttonTooltipText)!=null?Ip:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,Ft.appendChild(Qt),ot.append(Ft),!et&&oe&&ge&&(et=Os.fromConfig(X),et.setPreviewsContainer(ge),oe.addEventListener("change",async()=>{et&&(oe!=null&&oe.files)&&(await et.handleFileSelect(oe.files),oe.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Nm(X.dropOverlay))}else{Ft.style.display="";let X=(Rp=o.attachments)!=null?Rp:{};oe&&(oe.accept=((Pp=X.allowedTypes)!=null?Pp:_o).join(","),oe.multiple=((Wp=X.maxFiles)!=null?Wp:4)>1),et&&et.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Ft&&(Ft.style.display="none"),et&&et.clearAttachments(),(Bp=ce.querySelector(".persona-attachment-drop-overlay"))==null||Bp.remove();let qt=(Hp=o.sendButton)!=null?Hp:{},hr=(Dp=qt.useIcon)!=null?Dp:!1,nr=(Fp=qt.iconText)!=null?Fp:"\u2191",ht=qt.iconName,Pn=(Op=qt.tooltipText)!=null?Op:"Send message",Oo=(Np=qt.showTooltip)!=null?Np:!1,kn=(_p=qt.size)!=null?_p:"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 X=parseFloat(kn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Te(ht,X,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=($p=(Vp=o.copy)==null?void 0:Vp.sendButtonLabel)!=null?$p:"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 X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Pn,Ln==null||Ln.insertBefore(X,ae)}else Ut&&(Ut.style.display="none");let Dt=(Kp=(Up=o.layout)==null?void 0:Up.contentMaxWidth)!=null?Kp:k()?(jp=(qp=(zp=o.launcher)==null?void 0:zp.composerBar)==null?void 0:qp.contentMaxWidth)!=null?jp:"720px":void 0;Dt?(Ve.style.maxWidth=Dt,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.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")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let jt=(Gp=o.statusIndicator)!=null?Gp:{},Bn=(Yp=jt.visible)!=null?Yp:!0;if(ln.style.display=Bn?"":"none",E){let X=E.getStatus();nt(ln,(Ot=>{var ct,kt,rn,fn;return Ot==="idle"?(ct=jt.idleText)!=null?ct:gn.idle:Ot==="connecting"?(kt=jt.connectingText)!=null?kt:gn.connecting:Ot==="connected"?(rn=jt.connectedText)!=null?rn:gn.connected:Ot==="error"?(fn=jt.errorText)!=null?fn:gn.error:gn[Ot]})(X),jt,X)}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(){C()&&Bt(!0,"api")},close(){C()&&Bt(!1,"api")},toggle(){C()&&Bt(!T,"api")},clearChat(){xn=!1,E.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ts}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()},setMessage(c){return!pe||E.isStreaming()?!1:(!T&&C()&&Bt(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(E.isStreaming())return!1;let f=(c==null?void 0:c.trim())||pe.value.trim();return f?(!T&&C()&&Bt(!0,"system"),pe.value="",pe.style.height="auto",E.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return E.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(E.isVoiceActive()||(!T&&C()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("user"),E.isVoiceActive()&&U()})),!0):Gn?!0:ws()?(!T&&C()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),ur("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?E.isVoiceActive()?(E.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),ee()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectMessage(c)},injectAssistantMessage(c){!T&&C()&&Bt(!0,"system");let f=E.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)),f},injectUserMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectUserMessage(c)},injectSystemMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectSystemMessage(c)},injectMessageBatch(c){return!T&&C()&&Bt(!0,"system"),E.injectMessageBatch(c)},injectComponentDirective(c){return!T&&C()&&Bt(!0,"system"),E.injectComponentDirective(c)},injectTestMessage(c){!T&&C()&&Bt(!0,"system"),E.injectTestEvent(c)},async connectStream(c,f){return E.connectStream(c,f)},__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,E.upsertArtifact(c)):null},selectArtifact(c){co(o)&&E.selectArtifact(c)},clearArtifacts(){co(o)&&E.clearArtifacts()},getArtifacts(){var c;return(c=E==null?void 0:E.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=E==null?void 0:E.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!T&&!k()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,f){let y=E.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"){E.resolveWebMcpApproval(y.id,f);return}return E.resolveApproval(y.approval,f)},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){p(c)},on(c,f){return s.on(c,f)},off(c,f){s.off(c,f)},isOpen(){return C()&&T},isVoiceActive(){return mt.active},getState(){return{open:C()&&T,launcherEnabled:I,voiceActive:mt.active,streaming:E.isStreaming()}},showCSATFeedback(c){!T&&C()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Hm({onSubmit:async(y,P)=>{var N;E.isClientTokenMode()&&await E.submitCSATFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!T&&C()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Dm({onSubmit:async(y,P)=>{var N;E.isClientTokenMode()&&await E.submitNPSFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return E.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return E.submitNPSFeedback(c,f)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),ft.forEach(c=>c()),ye.remove(),Ue==null||Ue.remove(),Ie==null||Ie.destroy(),Ye==null||Ye.remove(),jn&&qe.removeEventListener("click",jn)}};if((((Gc=n==null?void 0:n.debugTools)!=null?Gc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={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=f,ft.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",f),ft.push(()=>{window.removeEventListener("persona:focusInput",f)}),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),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)&&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),ft.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=sx(o.persistState);if(ao&&C()){let c=ax(ao.storage),f=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Yc=ao.persist)==null?void 0:Yc.openState)&&c.getItem(f)==="true",N=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(h)==="true",V=((Qc=ao.persist)==null?void 0:Qc.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),(Jc=ao.persist)!=null&&Jc.openState&&(s.on("widget:opened",()=>{c.setItem(f,"true")}),s.on("widget:closed",()=>{c.setItem(f,"false")})),(Zc=ao.persist)!=null&&Zc.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(f),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),ft.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return m&&C()&&setTimeout(()=>{Zt.open()},0),Do(),Zt};var ix=(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},Vm=(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"},Ul=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="",Ul(e)},_l=e=>{e.style.transition=""},Vl=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"},Ii=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lx=(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))},cx=(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)},Um=(e,t,n,o,r,s,a)=>{var w,S,M,I,L,H;let i=Mo(s),d=i.reveal==="push";lx(e,t,n,o,d),cx(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,m=(S=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?S:!0,u=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,g=l!=null?l.innerWidth<=u:!1;if(m&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Vl(t),_l(o),$m(o),$l(n),Ii(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: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",Vl(t),_l(o),$l(n),Ii(r,o);let D=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":W;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=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",_l(o),Ul(o),Ii(r,o);let D=ix(i.width,e.clientWidth),W=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=`${W+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=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.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="",Vl(t),Ul(o),$l(n),Ii(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=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 ${W}`,o.style.width=W,o.style.maxWidth=W,o.style.minWidth=W,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")}},dx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Vm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Vm(n,o)},destroy(){n.remove()}}},px=(e,t)=>{var L,H,D,W;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"),m=n.createElement("div"),u=(H=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||H?(W=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",m.dataset.personaDockRole="host",l.appendChild(m),o.insertBefore(a,e),d.appendChild(e);let g=null,p=()=>{g==null||g.disconnect(),g=null},w=()=>{p(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Um(a,i,d,l,m,t,u)}),g.observe(a))},S=()=>{Um(a,i,d,l,m,t,u),w()},M=a.ownerDocument.defaultView,I=()=>{S()};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)),S(),{mode:"docked",host:m,shell:a,syncWidgetState(v){let x=v.launcherEnabled?v.open:!0;u!==x&&(u=x,S())},updateConfig(v){var x,k;t=v,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(u=!0),S()},destroy(){M==null||M.removeEventListener("resize",I),p(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},zm=(e,t)=>pn(t)?px(e,t):dx(e,t);var ns={desktop:{w:1280,h:800},mobile:{w:390,h:844}},zl=.15,ql=1.5,Ri="persona-preview-shell-theme",qm={load:()=>null,save:()=>{},clear:()=>{}},jm=["How do I get started?","Pricing & plans","Talk to support"];function Pi(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Km(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 jl(e){let t=Km(e);return`* { box-sizing: border-box; }
|
|
107
|
+
`}if(!y&&!c){let gt="max-height: -moz-available !important; max-height: stretch !important;",it=g?"":"padding-top: 1.25em !important;",kt=g?"":`z-index: ${(cn=(gn=o.launcher)==null?void 0:gn.zIndex)!=null?cn:wn} !important;`;Ae.style.cssText+=gt+it+kt}Qe()};bo(),Kr(e,o),Ri(e,o),Pi(e,o);let yt=[];yt.push(()=>{document.removeEventListener("keydown",Ko)});let Yt=null,Xt=null;yt.push(()=>{Yt==null||Yt(),Yt=null,Xt==null||Xt(),Xt=null}),_n&&yt.push(()=>{_n==null||_n.disconnect(),_n=null}),yt.push(()=>{kn==null||kn(),kn=null,Do(),Dt&&(Dt.remove(),Dt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),ke&&yt.push(()=>{Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),le==null||le.destroy(),le=null,K==null||K.destroy(),K=null,j=null});let qn=null,Xo=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=cu(()=>{Kr(e,o)}))};Xo(),yt.push(()=>{qn&&(qn(),qn=null)});let so=(Kc=o.features)==null?void 0:Kc.streamAnimation;if(so!=null&&so.type&&so.type!=="none"){let c=Gs(so.type,so.plugins);c&&(vl(c,e),yt.push(()=>tm(e)))}let yo=Em(Bt),jn=null,V,ao=!1,ve=Yu(),Kn=new Map,io=new Map,vo=new Map,us=0,xo=li(),wo=0,Co=null,Fo=!1,pr=!1,ua=4,ms=24,ma=80,Dr=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},gs=(Yc=(Gc=o.voiceRecognition)==null?void 0:Gc.autoResume)!=null?Yc:!1,lo=c=>{s.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Wn=()=>{u(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},ga=()=>{var y,M;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=zl(d.voiceState),g=!!c.active,h=Number((M=c.timestamp)!=null?M:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-h<hx&&setTimeout(()=>{var F,O;bt.active||(bt.manuallyDeactivated=!1,((O=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:O.type)==="runtype"?V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),lo("restore"),V.isVoiceActive()&&R()}):fr("restore"))},1e3)},fa=()=>V?Xm(V.getMessages()).filter(c=>!c.__skipPersist):[];function Fr(c){if(!(i!=null&&i.save))return;let h={messages:c?Xm(c):V?fa():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Oo=null,ha=()=>Ae.querySelector("#persona-scroll-container")||X,ur=()=>{Oo!==null&&(cancelAnimationFrame(Oo),Oo=null),Fo=!1},fs=()=>{Co!==null&&(cancelAnimationFrame(Co),Co=null),pr=!1,ur()},No=()=>{if(!Sn()||te){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==ue&&ue.appendChild(Pt),Ct();let c=qs(X)>0;Pt.style.display=xo.isFollowing()||!c?"none":""},hs=()=>{xo.pause()&&(fs(),No())},Qo=()=>{xo.resume(),No()},Jo=(c=!1)=>{xo.isFollowing()&&(!c&&!ao||(Co!==null&&(cancelAnimationFrame(Co),Co=null),pr=!0,Co=requestAnimationFrame(()=>{Co=null,pr=!1,xo.isFollowing()&&ba(ha(),c?220:140)})))},ba=(c,g=500)=>{let h=c.scrollTop,y=qs(c),M=y-h;if(Math.abs(M)<1){wo=c.scrollTop;return}if(Math.abs(M)>=ma){ur(),Fo=!0,c.scrollTop=y,wo=c.scrollTop,Fo=!1;return}ur();let F=performance.now();Fo=!0;let O=D=>1-Math.pow(1-D,3),z=D=>{if(!xo.isFollowing()){ur();return}let Te=qs(c);Te!==y&&(y=Te,M=y-h);let me=D-F,Z=Math.min(me/g,1),Se=O(Z),Le=h+M*Se;c.scrollTop=Le,wo=c.scrollTop,Z<1?Oo=requestAnimationFrame(z):(c.scrollTop=y,wo=c.scrollTop,Oo=null,Fo=!1)};Oo=requestAnimationFrame(z)},ya=c=>{let g=new Map;c.forEach(h=>{let y=Dr.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}))}),Dr.clear(),g.forEach((h,y)=>{Dr.set(y,h)})},mr=(c,g,h)=>{var dt,Pe,Re,qe,Qe,vt;let y=document.createElement("div"),F=(()=>{var De;let B=r.find(ne=>ne.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((De=o.loadingIndicator)!=null&&De.render)return o.loadingIndicator.render})(),O=(B,De)=>De==null?!1:typeof De=="string"?(B.textContent=De,!0):(B.appendChild(De),!0),z=new Set,D=new Set,Te=r.some(B=>B.renderAskUserQuestion),me=[],Z=[],Se=o.enableComponentStreaming!==!1,Le=r.some(B=>B.renderApproval)&&o.approval!==!1,Ve=[];if(g.forEach(B=>{var wt,Xn,on,uo,Qn,hr,zr,qr,Gt,br,rr,sr,$o,yr;z.add(B.id);let De=Te&&Lr(B),ne=Le&&B.variant==="approval"&&!!B.approval,et=!De&&B.role==="assistant"&&!B.variant&&Se&&jm(B);if(!ne&&vo.has(B.id)){let tt=c.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),vo.delete(B.id)}if(!et&&io.has(B.id)){let tt=c.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),io.delete(B.id)}let Nt=Lr(B)?`:${(wt=B.agentMetadata)!=null&&wt.askUserQuestionAnswered?"a":"u"}:${(Xn=B.agentMetadata)!=null&&Xn.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Gu(B,us)+Nt,zt=De||ne||et?null:Xu(ve,B.id,Ot);if(zt){y.appendChild(zt.cloneNode(!0)),Lr(B)&&((on=B.toolCall)!=null&&on.id)&&((uo=B.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((Qn=B.agentMetadata)!=null&&Qn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),ki(B,o,We.composerOverlay));return}let at=null,ln=r.find(tt=>!!(B.variant==="reasoning"&&tt.renderReasoning||B.variant==="tool"&&tt.renderToolCall||!B.variant&&tt.renderMessage)),Yn=(hr=o.layout)==null?void 0:hr.messages;if(Lr(B)&&((zr=B.agentMetadata)==null?void 0:zr.askUserQuestionAnswered)===!0){Kn.delete(B.id);let tt=c.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime");return}if(Lr(B)&&((Gt=(qr=o.features)==null?void 0:qr.askUserQuestion)==null?void 0:Gt.enabled)!==!1){let tt=r.find(yn=>typeof yn.renderAskUserQuestion=="function");if(tt&&Mt.current){let yn=Kn.get(B.id),gn=yn!==Ot,cn=null;if(gn){let{payload:kt,complete:Bn}=os(B),Zt=B.id,Io=()=>{var rn;return(rn=Mt.current)==null?void 0:rn.getMessages().find(Mn=>Mn.id===Zt)};cn=tt.renderAskUserQuestion({message:B,payload:kt,complete:Bn,resolve:rn=>{var mo;let Mn=Io();Mn&&((mo=Mt.current)==null||mo.resolveAskUserQuestion(Mn,rn))},dismiss:()=>{var Mn,mo,vr;let rn=Io();(Mn=rn==null?void 0:rn.agentMetadata)!=null&&Mn.awaitingLocalTool&&((mo=Mt.current)==null||mo.markAskUserQuestionResolved(rn),(vr=Mt.current)==null||vr.resolveAskUserQuestion(rn,"(dismissed)"))},config:o})}let gt=yn!=null;if(gn&&cn===null&&!gt){((br=B.agentMetadata)==null?void 0:br.awaitingLocalTool)===!0&&!((rr=B.agentMetadata)!=null&&rr.askUserQuestionAnswered)&&(D.add(B.toolCall.id),ki(B,o,We.composerOverlay));return}let it=document.createElement("div");it.className="persona-flex",it.id=`wrapper-${B.id}`,it.setAttribute("data-wrapper-id",B.id),it.setAttribute("data-ask-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),y.appendChild(it),me.push({messageId:B.id,fingerprint:Ot,bubble:cn});return}else{((sr=B.agentMetadata)==null?void 0:sr.awaitingLocalTool)===!0&&!(($o=B.agentMetadata)!=null&&$o.askUserQuestionAnswered)&&(D.add(B.toolCall.id),ki(B,o,We.composerOverlay));return}}else if(ne){let tt=r.find(gt=>typeof gt.renderApproval=="function"),gn=vo.get(B.id)!==Ot,cn=null;if(gn&&(tt!=null&&tt.renderApproval)){let gt=B.id,it=(kt,Bn)=>{var Io,rn,Mn;let Zt=(Io=Mt.current)==null?void 0:Io.getMessages().find(mo=>mo.id===gt);Zt!=null&&Zt.approval&&(Zt.approval.toolType==="webmcp"?(rn=Mt.current)==null||rn.resolveWebMcpApproval(Zt.id,kt):(Mn=Mt.current)==null||Mn.resolveApproval(Zt.approval,kt,Bn))};cn=tt.renderApproval({message:B,defaultRenderer:()=>Li(B,o),config:o,approve:kt=>it("approved",kt),deny:kt=>it("denied",kt)})}if(gn&&cn===null){let gt=c.querySelector(`#wrapper-${B.id}`);gt==null||gt.removeAttribute("data-preserve-runtime"),vo.delete(B.id),at=Li(B,o)}else{let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${B.id}`,gt.setAttribute("data-wrapper-id",B.id),gt.setAttribute("data-approval-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),y.appendChild(gt),Ve.push({messageId:B.id,fingerprint:Ot,bubble:cn});return}}else if(ln)if(B.variant==="reasoning"&&B.reasoning&&ln.renderReasoning){if(!ge)return;at=ln.renderReasoning({message:B,defaultRenderer:()=>kl(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&ln.renderToolCall){if(!se)return;at=ln.renderToolCall({message:B,defaultRenderer:()=>El(B,o),config:o})}else ln.renderMessage&&(at=ln.renderMessage({message:B,defaultRenderer:()=>{let tt=Tl(B,h,Yn,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&Ol(tt,B,o,V),tt},config:o}));if(!at&&et){let tt=Km(B);if(tt){let yn=io.get(B.id),gn=yn!==Ot,cn=o.wrapComponentDirectiveInBubble!==!1,gt=null;if(gn){let it=zm(tt,{config:o,message:B,transform:h});if(it)if(cn){let kt=document.createElement("div");if(kt.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(" "),kt.id=`bubble-${B.id}`,kt.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Bn=document.createElement("div");Bn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Bn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),kt.appendChild(Bn)}kt.appendChild(it),gt=kt}else{let kt=document.createElement("div");if(kt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",kt.id=`bubble-${B.id}`,kt.setAttribute("data-message-id",B.id),kt.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Bn=document.createElement("div");Bn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Bn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),kt.appendChild(Bn)}kt.appendChild(it),gt=kt}}if(gt||yn!=null){let it=document.createElement("div");it.className="persona-flex",it.id=`wrapper-${B.id}`,it.setAttribute("data-wrapper-id",B.id),it.setAttribute("data-component-directive-stub","true"),it.setAttribute("data-preserve-runtime","true"),cn||it.classList.add("persona-w-full"),y.appendChild(it),Z.push({messageId:B.id,fingerprint:Ot,bubble:gt});return}}}if(!at)if(B.variant==="reasoning"&&B.reasoning){if(!ge)return;at=kl(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!se)return;at=El(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;at=Li(B,o)}else{let tt=(yr=o.layout)==null?void 0:yr.messages;tt!=null&&tt.renderUserMessage&&B.role==="user"?at=tt.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):tt!=null&&tt.renderAssistantMessage&&B.role==="assistant"?at=tt.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):at=Tl(B,h,tt,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&at&&Ol(at,B,o,V)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${B.id}`,Ke.setAttribute("data-wrapper-id",B.id),B.role==="user"&&Ke.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(at),Qu(ve,B.id,Ot,Ke),y.appendChild(Ke)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let ne=De.getAttribute("data-persona-ask-sheet-for");ne&&!D.has(ne)&&ss(We.composerOverlay,ne)}),(Pe=(dt=o.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let B=[],De=[];g.forEach(ne=>{if(ne.variant==="tool"&&ne.toolCall&&se){De.push(ne);return}De.length>1&&B.push(De),De=[]}),De.length>1&&B.push(De),B.forEach((ne,et)=>{var wt,Xn;let Nt=ne.map(on=>Array.from(y.children).find(uo=>uo instanceof HTMLElement&&uo.getAttribute("data-wrapper-id")===on.id)).filter(on=>!!on);if(Nt.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${et}-${ne[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${et}-${ne[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.setAttribute("data-persona-tool-group","true");let at=document.createElement("div");at.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ln=`Called ${ne.length} tools`,Yn=(Xn=(wt=o.toolCall)==null?void 0:wt.renderGroupedSummary)==null?void 0:Xn.call(wt,{messages:ne,toolCalls:ne.map(on=>on.toolCall).filter(on=>!!on),defaultSummary:ln,config:o});O(at,Yn)||(at.textContent=ln);let Ke=document.createElement("div");Ke.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(at,Ke),Ot.appendChild(zt),Nt[0].before(Ot),Nt.forEach((on,uo)=>{let Qn=document.createElement("div");Qn.className="persona-tool-group-item persona-relative",Qn.setAttribute("data-persona-tool-group-item","true"),uo<Nt.length-1&&Qn.setAttribute("data-persona-tool-group-connector","true"),Qn.appendChild(on),Ke.appendChild(Qn)})})}Ju(ve,z);let ot=g.some(B=>B.role==="assistant"&&B.streaming),je=g[g.length-1],mt=(je==null?void 0:je.role)==="assistant"&&!je.streaming&&je.variant!=="approval";if(ao&&g.some(B=>B.role==="user")&&!ot&&!mt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ta},De=r.find(et=>et.renderLoadingIndicator),ne=null;if(De!=null&&De.renderLoadingIndicator&&(ne=De.renderLoadingIndicator(B)),ne===null&&((Re=o.loadingIndicator)!=null&&Re.render)&&(ne=o.loadingIndicator.render(B)),ne===null&&(ne=ta()),ne){let et=document.createElement("div"),Nt=((qe=o.loadingIndicator)==null?void 0:qe.showBubble)!==!1;et.className=Nt?["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(" "),et.setAttribute("data-typing-indicator","true"),et.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",et.appendChild(ne);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(et),y.appendChild(Ot)}}if(!ao&&g.length>0){let B=g[g.length-1],De={config:o,lastMessage:B,messageCount:g.length},ne=r.find(Nt=>Nt.renderIdleIndicator),et=null;if(ne!=null&&ne.renderIdleIndicator&&(et=ne.renderIdleIndicator(De)),et===null&&((Qe=o.loadingIndicator)!=null&&Qe.renderIdle)&&(et=o.loadingIndicator.renderIdle(De)),et){let Nt=document.createElement("div"),Ot=((vt=o.loadingIndicator)==null?void 0:vt.showBubble)!==!1;Nt.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(et);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Nt),y.appendChild(zt)}}if(ai(c,y),me.length>0)for(let{messageId:B,fingerprint:De,bubble:ne}of me){let et=c.querySelector(`#wrapper-${B}`);et&&ne!==null&&(et.replaceChildren(ne),et.setAttribute("data-bubble-fp",De),Kn.set(B,De))}if(Kn.size>0)for(let B of Kn.keys())z.has(B)||Kn.delete(B);if(Z.length>0)for(let{messageId:B,fingerprint:De,bubble:ne}of Z){let et=c.querySelector(`#wrapper-${B}`);et&&ne!==null&&(et.replaceChildren(ne),et.setAttribute("data-bubble-fp",De),io.set(B,De))}if(io.size>0)for(let B of io.keys())z.has(B)||io.delete(B);if(Ve.length>0)for(let{messageId:B,fingerprint:De,bubble:ne}of Ve){let et=c.querySelector(`#wrapper-${B}`);et&&ne!==null&&(et.replaceChildren(ne),et.setAttribute("data-bubble-fp",De),vo.set(B,De))}if(vo.size>0)for(let B of vo.keys())z.has(B)||vo.delete(B)},Zo=null,va=()=>{var h;if(Zo)return;let c=y=>{let M=y.composedPath();M.includes(Ae)||$e&&M.includes($e)||Ft(!1,"user")};Zo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},bs=()=>{var g;if(!Zo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Zo,!0),Zo=null};yt.push(()=>bs());let er=null,xa=()=>{var h;if(er)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ft(!1,"user"))};er=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ys=()=>{var g;if(!er)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",er,!0),er=null};yt.push(()=>ys());let tr=!1,vs=new Set,wa=()=>{var g,h,y,M;let c=(y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((M=o.features)==null?void 0:M.streamAnimation)},_o=()=>{var mt,dt,Pe,Re;if(!k())return;let c=We.peekBanner,g=We.peekTextNode;if(!c||!g)return;if(A){c.classList.remove("persona-pill-peek--visible");return}let h=(mt=V==null?void 0:V.getMessages())!=null?mt:[],y;for(let qe=h.length-1;qe>=0;qe--){let Qe=h[qe];if(Qe.role==="assistant"&&Qe.content){y=Qe;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let M=y.content,F=!!y.streaming,O=wa(),z=pi(O),D=z.type!=="none"?Gs(z.type,O==null?void 0:O.plugins):null,Te=((dt=D==null?void 0:D.isAnimating)==null?void 0:dt.call(D,y))===!0,me=D!==null&&(F||Te);me&&D&&!vs.has(D.name)&&(vl(D,e),vs.add(D.name));let Z=me&&(D!=null&&D.containerClass)?D.containerClass:null,Se=(Pe=g.dataset.personaPeekStreamClass)!=null?Pe:null;Se&&Se!==Z&&(g.classList.remove(Se),delete g.dataset.personaPeekStreamClass),Z&&Se!==Z&&(g.classList.add(Z),g.dataset.personaPeekStreamClass=Z),me?(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 Le=me?ui(M,z.buffer,D,y,F):M;if(me&&z.placeholder==="skeleton"&&F&&(!Le||!Le.trim())){let qe=document.createElement("div"),Qe=Xs();Qe.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Qe),ai(g,qe)}else{let qe=Math.max(0,Le.length-100),Qe=Le.length>100?Le.slice(-100):Le,vt=Ds(Qe);if(!me||!D){let B=Le.length>100?`\u2026${Qe}`:Qe;g.textContent!==B&&(g.textContent=B)}else{let B=vt;(D.wrap==="char"||D.wrap==="word")&&(B=Ys(vt,D.wrap,`peek-${y.id}`,{skipTags:D.skipTags,startIndex:qe}));let De=document.createElement("div");if(De.innerHTML=B,D.useCaret&&Qe.length>0){let ne=mi(),et=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=et[et.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(ne,Nt.nextSibling):De.appendChild(ne)}ai(g,De),(Re=D.onAfterRender)==null||Re.call(D,{container:g,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let je=ao||tr;c.classList.toggle("persona-pill-peek--visible",je)};if(k()){let c=We.peekBanner;if(c){let y=M=>{M.preventDefault(),M.stopPropagation(),Ft(!0,"user")};c.addEventListener("pointerdown",y),yt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{tr||(tr=!0,_o())},h=()=>{tr&&(tr=!1,_o())};pe.addEventListener("pointerenter",g),pe.addEventListener("pointerleave",h),yt.push(()=>{pe.removeEventListener("pointerenter",g),pe.removeEventListener("pointerleave",h)}),$e&&($e.addEventListener("pointerenter",g),$e.addEventListener("pointerleave",h),yt.push(()=>{$e.removeEventListener("pointerenter",g),$e.removeEventListener("pointerleave",h)}))}let Ca=c=>{var Se,Le,Ve,ot,je,mt,dt,Pe;let g=(Le=(Se=o.launcher)==null?void 0:Se.composerBar)!=null?Le:{},h=(Ve=g.expandedSize)!=null?Ve:"anchored",y=(ot=g.bottomOffset)!=null?ot:"16px",M=g.collapsedMaxWidth,F=(je=g.expandedMaxWidth)!=null?je:"880px",O=(mt=g.expandedTopOffset)!=null?mt:"5vh",z=(dt=g.modalMaxWidth)!=null?dt:"880px",D=(Pe=g.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Te="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",Z=Ae.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",$e){let Re=$e.style;Re.bottom=y,Re.width=M!=null?M:""}if(c&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=z,Z.maxWidth=Te,Z.maxHeight=D,Z.height=D;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${me})`,Z.top=O,Z.width=F,Z.maxWidth=Te}},nr=()=>{var D,Te,me,Z,Se,Le,Ve,ot;if(!S())return;if(k()){let mt=(me=((Te=(D=o.launcher)==null?void 0:D.composerBar)!=null?Te:{}).expandedSize)!=null?me:"anchored",dt=A?"expanded":"collapsed";Ae.dataset.state=dt,Ae.dataset.expandedSize=mt,$e&&($e.dataset.state=dt,$e.dataset.expandedSize=mt),Ae.style.removeProperty("display"),Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ca(A),ue.style.display=A?"flex":"none",bo(),A?(va(),xa()):(bs(),ys()),_o();return}let c=hn(o),g=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Le=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?Le:640,y=(ot=(Ve=o.launcher)==null?void 0:Ve.mobileFullscreen)!=null?ot:!0,M=g.innerWidth<=h,F=y&&M&&L,O=Wo(o).reveal;A?(Ae.style.removeProperty("display"),Ae.style.display=c?"flex":"",Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),Xe?Xe.element.style.display="none":Ze&&(Ze.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!F?(Ae.style.removeProperty("display"),Ae.style.display="flex",Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ae.style.setProperty("display","none","important"),Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ae.style.display="",Ae.classList.add("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),Xe?Xe.element.style.display=c?"none":"":Ze&&(Ze.style.display=c?"none":""))},Ft=(c,g="user")=>{var F,O;if(!S()||A===c)return;let h=A;A=c,nr();let y=(()=>{var Ve,ot,je,mt,dt,Pe,Re,qe,Qe,vt;let z=(ot=(Ve=o.launcher)==null?void 0:Ve.sidebarMode)!=null?ot:!1,D=(je=e.ownerDocument.defaultView)!=null?je:window,Te=(dt=(mt=o.launcher)==null?void 0:mt.mobileFullscreen)!=null?dt:!0,me=(Re=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,Z=D.innerWidth<=me,Se=hn(o)&&Te&&Z,Le=k()&&((vt=(Qe=(qe=o.launcher)==null?void 0:qe.composerBar)==null?void 0:Qe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return z||Te&&Z&&L||Se||Le})();if(A&&y){if(!Yt){let z=e.getRootNode(),D=z instanceof ShadowRoot?z.host:e.closest(".persona-host");D&&(Yt=xl(D,(O=(F=o.launcher)==null?void 0:F.zIndex)!=null?O:wn))}Xt||(Xt=wl(e.ownerDocument))}else A||(Yt==null||Yt(),Yt=null,Xt==null||Xt(),Xt=null);A&&(Qt(),Jo(!0));let M={open:A,source:g,timestamp:Date.now()};A&&!h?s.emit("widget:opened",M):!A&&h&&s.emit("widget:closed",M),s.emit("widget:state",{open:A,launcherEnabled:L,voiceActive:bt.active,streaming:V.isStreaming()})},Or=c=>{qt(c?"stop":"send"),q&&(q.disabled=c),yo.buttons.forEach(g=>{g.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Nr=()=>{bt.active||he&&he.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Nr(),200)});let xs=()=>{var h,y,M,F,O,z,D,Te,me,Z,Se;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",eo.textContent=(F=(M=o.copy)==null?void 0:M.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",he.placeholder=(z=(O=o.copy)==null?void 0:O.inputPlaceholder)!=null?z:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let Le=((D=o.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Le?"":"none",Le?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((me=(Te=o.sendButton)==null?void 0:Te.useIcon)!=null&&me)&&!(V!=null&&V.isStreaming())&&(ce.textContent=(Se=(Z=o.copy)==null?void 0:Z.sendButtonLabel)!=null?Se:"Send"),he.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',he.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(g=>({...g,sessionId:c}))}});let Lo=null,Sa=()=>{Lo==null&&(Lo=setInterval(()=>{let c=Ne.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Lo),Lo=null;return}let g=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ga(g-y))})},100))};if(V=new ri(o,{onMessagesChanged(c){mr(Ne,c,fe),Sa(),V&&(c.some(M=>M.role==="user")?yo.render([],V,he,c):yo.render(o.suggestionChips,V,he,c,o.suggestionChipsConfig)),Jo(!ao),ya(c);let g=[...c].reverse().find(y=>y.role==="user"),h=bt.lastUserMessageId;g&&g.id!==h&&(bt.lastUserMessageId=g.id,s.emit("user:message",g)),bt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Fr(c),_o()},onStatusChanged(c){var y;let g=(y=o.statusIndicator)!=null?y:{};rt(mn,(M=>{var F,O,z,D;return M==="idle"?(F=g.idleText)!=null?F:xn.idle:M==="connecting"?(O=g.connectingText)!=null?O:xn.connecting:M==="connected"?(z=g.connectedText)!=null?z:xn.connected:M==="error"?(D=g.errorText)!=null?D:xn.error:xn[M]})(c),g,c)},onStreamingChanged(c){ao=c,Or(c),V&&mr(Ne,V.getMessages(),fe),c||Jo(!0),_o()},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":Y(),J();break;case"speaking":Y(),ie();break;default:c==="idle"&&V.isBargeInActive()?(Y(),R(),q==null||q.setAttribute("aria-label","End voice session")):(bt.active=!1,Y(),lo("system"),Wn());break}},onArtifactsState(c){Vn=c,zn(),Fr()}}),Mt.current=V,((Qc=(Xc=o.voiceRecognition)==null?void 0:Xc.provider)==null?void 0:Qc.type)==="runtype")try{V.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&V.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||o.onSSEEvent)&&V.setSSEEventCallback((c,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,g),ye==null||ye.processEvent(c,g),K==null||K.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=zl(c.metadata),E.syncFromMetadata()),(g=c.messages)!=null&&g.length&&V.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&V.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ws=()=>{var g,h,y;!k()||A||!((y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ft(!0,"auto")},Cs=c=>{var M;if(c.preventDefault(),V.isStreaming()){V.cancel(),ye==null||ye.reset(),le==null||le.update();return}let g=he.value.trim(),h=(M=nt==null?void 0:nt.hasAttachments())!=null?M:!1;if(!g&&!h)return;ws();let y;h&&(y=[],y.push(...nt.getContentParts()),g&&y.push(fl(g))),he.value="",he.style.height="auto",gr(),V.sendMessage(g,{contentParts:y}),h&&nt.clearAttachments()},Aa=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},_r={...ii},Vr=!1,gr=()=>{_r={...ii}},Ta=()=>V.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ka=c=>{if(!he)return;Vr=!0,he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),Vr=!1;let g=he.value.length;he.setSelectionRange(g,g)},Ss=()=>{Vr||gr()},As=c=>{if(he){if(Aa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=he.selectionStart===0&&he.selectionEnd===0,h=Ku({direction:c.key==="ArrowUp"?"up":"down",history:Ta(),currentValue:he.value,atStart:g,state:_r});if(_r=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ka(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(V.isStreaming()){c.preventDefault();return}gr(),c.preventDefault(),ce.click()}}},Ts=c=>{c.key!=="Escape"||c.isComposing||V.isStreaming()&&c.composedPath().includes(ue)&&(V.cancel(),ye==null||ye.reset(),le==null||le.update(),gr(),c.preventDefault(),c.stopImmediatePropagation())},ks=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!nt)return;let g=yx(c.clipboardData);g.length!==0&&(c.preventDefault(),await nt.handleFiles(g))},En=null,Gn=!1,Vo=null,lt=null,Es=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fr=(c="user")=>{var F,O,z,D,Te,me,Z;if(Gn||V.isStreaming())return;let g=Es();if(!g)return;En=new g;let y=(O=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?O:2e3;En.continuous=!0,En.interimResults=!0,En.lang="en-US";let M=he.value;En.onresult=Se=>{let Le="",Ve="";for(let je=0;je<Se.results.length;je++){let mt=Se.results[je],dt=mt[0].transcript;mt.isFinal?Le+=dt+" ":Ve=dt}let ot=M+Le+Ve;he.value=ot,Vo&&clearTimeout(Vo),(Le||Ve)&&(Vo=window.setTimeout(()=>{let je=he.value.trim();je&&En&&Gn&&(So(),he.value="",he.style.height="auto",V.sendMessage(je,{viaVoice:!0}))},y))},En.onerror=Se=>{Se.error!=="no-speech"&&So()},En.onend=()=>{if(Gn){let Se=he.value.trim();Se&&Se!==M.trim()&&(he.value="",he.style.height="auto",V.sendMessage(Se,{viaVoice:!0})),So()}};try{if(En.start(),Gn=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),lo(c),Wn(),q){let Se=(z=o.voiceRecognition)!=null?z:{};lt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(D=Se.iconName)!=null?D:"mic",iconSize:parseFloat((Z=(me=Se.iconSize)!=null?me:(Te=o.sendButton)==null?void 0:Te.size)!=null?Z:"40")||24};let Le=Se.recordingBackgroundColor,Ve=Se.recordingIconColor,ot=Se.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Le!=null?Le:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Ve!=null?Ve:"var(--persona-voice-recording-indicator, #ffffff)",Ve){let je=q.querySelector("svg");je&&je.setAttribute("stroke",Ve)}ot&&(q.style.borderColor=ot),q.setAttribute("aria-label","Stop voice recognition")}}catch{So("system")}},So=(c="user")=>{if(Gn){if(Gn=!1,Vo&&(clearTimeout(Vo),Vo=null),En){try{En.stop()}catch{}En=null}if(bt.active=!1,lo(c),Wn(),q){if(q.classList.remove("persona-voice-recording"),lt){q.style.backgroundColor=lt.backgroundColor,q.style.color=lt.color,q.style.borderColor=lt.borderColor;let g=q.querySelector("svg");g&&g.setAttribute("stroke",lt.color||"currentColor"),lt=null}q.setAttribute("aria-label","Start voice recognition")}}},$r=(c,g)=>{var mt,dt,Pe,Re,qe,Qe,vt,B;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((mt=c==null?void 0:c.provider)==null?void 0:mt.type)==="runtype";if(!(h||y))return null;let F=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let z=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",D=(Pe=g==null?void 0:g.size)!=null?Pe:"40px",Te=(Re=c==null?void 0:c.iconSize)!=null?Re:D,me=parseFloat(Te)||24,Z=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,Se=(Qe=c==null?void 0:c.iconColor)!=null?Qe:g==null?void 0:g.textColor;O.style.width=Te,O.style.height=Te,O.style.minWidth=Te,O.style.minHeight=Te,O.style.fontSize="18px",O.style.lineHeight="1",Se?O.style.color=Se:O.style.color="var(--persona-text, #111827)";let Ve=Ee(z,me,Se||"currentColor",1.5);Ve?O.appendChild(Ve):O.textContent="\u{1F3A4}",Z?O.style.backgroundColor=Z:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),F.appendChild(O);let ot=(vt=c==null?void 0:c.tooltipText)!=null?vt:"Start voice recognition";if(((B=c==null?void 0:c.showTooltip)!=null?B:!1)&&ot){let De=b("div","persona-send-button-tooltip");De.textContent=ot,F.appendChild(De)}return{micButton:O,micButtonWrapper:F}},Ge=()=>{var g,h,y,M,F;if(!q||lt)return;let c=(g=o.voiceRecognition)!=null?g:{};lt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((F=(M=c.iconSize)!=null?M:(y=o.sendButton)==null?void 0:y.size)!=null?F:"40")||24}},T=(c,g)=>{var F,O,z,D,Te;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(Te=lt==null?void 0:lt.iconSize)!=null?Te:parseFloat((D=(z=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?z:(O=o.sendButton)==null?void 0:O.size)!=null?D:"40")||24,M=Ee(c,y,g,1.5);M&&q.appendChild(M)},U=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},R=()=>{var M;if(!q)return;Ge();let c=(M=o.voiceRecognition)!=null?M:{},g=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(U(),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 F=q.querySelector("svg");F&&F.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},J=()=>{var z,D,Te,me,Z,Se,Le,Ve;if(!q)return;Ge();let c=(z=o.voiceRecognition)!=null?z:{},g=V.getVoiceInterruptionMode(),h=(D=c.processingIconName)!=null?D:"loader",y=(me=(Te=c.processingIconColor)!=null?Te:lt==null?void 0:lt.color)!=null?me:"",M=(Se=(Z=c.processingBackgroundColor)!=null?Z:lt==null?void 0:lt.backgroundColor)!=null?Se:"",F=(Ve=(Le=c.processingBorderColor)!=null?Le:lt==null?void 0:lt.borderColor)!=null?Ve:"";U(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=M,q.style.borderColor=F;let O=y||"currentColor";q.style.color=O,T(h,O),q.setAttribute("aria-label","Processing voice input"),g==="none"&&(q.style.cursor="default")},ie=()=>{var Te,me,Z,Se,Le,Ve,ot,je,mt,dt,Pe,Re;if(!q)return;Ge();let c=(Te=o.voiceRecognition)!=null?Te:{},g=V.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(me=c.speakingIconName)!=null?me:h,M=(Ve=c.speakingIconColor)!=null?Ve:g==="barge-in"?(Se=(Z=c.recordingIconColor)!=null?Z:lt==null?void 0:lt.color)!=null?Se:"":(Le=lt==null?void 0:lt.color)!=null?Le:"",F=(mt=c.speakingBackgroundColor)!=null?mt:g==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(je=lt==null?void 0:lt.backgroundColor)!=null?je:"",O=(Re=c.speakingBorderColor)!=null?Re:g==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=lt==null?void 0:lt.borderColor)!=null?Pe:"";U(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=F,q.style.borderColor=O;let z=M||"currentColor";q.style.color=z,T(y,z);let D=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",D),g==="none"&&(q.style.cursor="default"),g==="barge-in"&&q.classList.add("persona-voice-recording")},Y=()=>{var c,g,h;q&&(U(),lt&&(q.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",q.style.color=(g=lt.color)!=null?g:"",q.style.borderColor=(h=lt.borderColor)!=null?h:"",T(lt.iconName,lt.color||"currentColor"),lt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},Ie=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let h=V.getVoiceStatus(),y=V.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Wn(),lo("user"),Y()});return}V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),bt.manuallyDeactivated=!V.isVoiceActive(),Wn(),lo("user"),V.isVoiceActive()?R():Y()});return}if(Gn){let h=he.value.trim();bt.manuallyDeactivated=!0,Wn(),So("user"),h&&(he.value="",he.style.height="auto",V.sendMessage(h))}else bt.manuallyDeactivated=!1,Wn(),fr("user")};Fn=Ie,q&&(q.addEventListener("click",Ie),yt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),Y()):So("system"),q&&q.removeEventListener("click",Ie)}));let Oe=s.on("assistant:complete",()=>{gs&&(bt.active||bt.manuallyDeactivated||gs==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!bt.active&&!bt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),lo("auto"),V.isVoiceActive()&&R()}):fr("auto"))},600))});yt.push(Oe);let ct=s.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});yt.push(ct);let Ye=()=>{Ft(!A,"user")},Xe=null,Ze=null;if(L&&!k()){let c=r.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>Zs(o,Ye).element,onToggle:Ye});g&&(Ze=g)}Ze||(Xe=Zs(o,Ye))}Xe?e.appendChild(Xe.element):Ze&&e.appendChild(Ze),nr(),yo.render(o.suggestionChips,V,he,void 0,o.suggestionChipsConfig),xs(),Or(V.isStreaming()),Jo(!0),ga(),P&&(!L||k()?setTimeout(()=>Nr(),0):A&&setTimeout(()=>Nr(),200));let Qt=()=>{var D,Te,me,Z,Se,Le,Ve,ot,je,mt,dt,Pe,Re,qe,Qe,vt,B,De,ne,et,Nt,Ot;if(k()){Ct(),nr();return}let c=hn(o),g=(Te=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?Te:!1,h=c||g||((Z=(me=o.launcher)==null?void 0:me.fullHeight)!=null?Z:!1),y=(Se=e.ownerDocument.defaultView)!=null?Se:window,M=(Ve=(Le=o.launcher)==null?void 0:Le.mobileFullscreen)!=null?Ve:!0,F=(je=(ot=o.launcher)==null?void 0:ot.mobileBreakpoint)!=null?je:640,O=y.innerWidth<=F,z=M&&O&&L;try{if(z){bo(),Kr(e,o);return}if(w&&(w=!1,bo(),Kr(e,o)),!L&&!c){pe.style.height="",pe.style.width="";return}if(!g&&!c){let zt=(dt=(mt=o==null?void 0:o.launcher)==null?void 0:mt.width)!=null?dt:o==null?void 0:o.launcherWidth,at=zt!=null?zt:go;pe.style.width=at,pe.style.maxWidth=at}if(Mo(),!h){let zt=y.innerHeight,at=64,ln=(Re=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Re:0,Yn=Math.max(200,zt-at),Ke=Math.min(640,Yn),wt=Math.max(200,Ke-ln);pe.style.height=`${wt}px`}}finally{if(Ct(),nr(),A&&L){let at=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((vt=(Qe=o.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?vt:640),ln=(De=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?De:!1,Yn=(et=(ne=o.launcher)==null?void 0:ne.mobileFullscreen)!=null?et:!0,Ke=hn(o)&&Yn&&at,wt=ln||Yn&&at&&L||Ke;if(wt&&!Xt){let Xn=e.getRootNode(),on=Xn instanceof ShadowRoot?Xn.host:e.closest(".persona-host");on&&!Yt&&(Yt=xl(on,(Ot=(Nt=o.launcher)==null?void 0:Nt.zIndex)!=null?Ot:wn)),Xt=wl(e.ownerDocument)}else wt||(Yt==null||Yt(),Yt=null,Xt==null||Xt(),Xt=null)}}};Qt();let Lt=(Jc=e.ownerDocument.defaultView)!=null?Jc:window;if(Lt.addEventListener("resize",Qt),yt.push(()=>Lt.removeEventListener("resize",Qt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ct()});c.observe(_e),yt.push(()=>c.disconnect())}wo=X.scrollTop;let Ht=X.scrollHeight,an=()=>{let c=X.scrollTop,g=X.scrollHeight,h=g<Ht;Ht=g;let{action:y,nextLastScrollTop:M}=ci({following:xo.isFollowing(),currentScrollTop:c,lastScrollTop:wo,nearBottom:js(X,ms),userScrollThreshold:ua,isAutoScrolling:Fo||pr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(wo=M,y==="resume"){Qo();return}y==="pause"&&hs()};X.addEventListener("scroll",an,{passive:!0}),yt.push(()=>X.removeEventListener("scroll",an));let bn=c=>{let g=di({following:xo.isFollowing(),deltaY:c.deltaY,nearBottom:js(X,ms),resumeWhenNearBottom:!0});g==="pause"?hs():g==="resume"&&Qo()};X.addEventListener("wheel",bn,{passive:!0}),yt.push(()=>X.removeEventListener("wheel",bn)),Pt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,wo=X.scrollTop,Qo(),Jo(!0)}),yt.push(()=>Pt.remove()),yt.push(()=>{fs()});let fn=()=>{ze&&(jn&&(ze.removeEventListener("click",jn),jn=null),S()?(ze.style.display="",jn=()=>{Ft(!1,"user")},ze.addEventListener("click",jn)):ze.style.display="none")};fn(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{V.clearMessages(),ve.clear(),Qo(),ss(We.composerOverlay);try{localStorage.removeItem(is),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==is)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={},E.syncFromMetadata(),K==null||K.clear(),ye==null||ye.reset(),le==null||le.update()})})(),$t&&$t.addEventListener("submit",Cs),he==null||he.addEventListener("keydown",As),he==null||he.addEventListener("input",Ss),he==null||he.addEventListener("paste",ks);let co=(Zc=e.ownerDocument)!=null?Zc:document;co.addEventListener("keydown",Ts,!0);let sc="persona-attachment-drop-active",Ms=0,Yi=()=>{Ms=0,ue.classList.remove(sc)},Ur=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&nt!==null},ac=c=>{!Wi(c.dataTransfer)||!Ur()||(Ms++,Ms===1&&ue.classList.add(sc))},ic=c=>{!Wi(c.dataTransfer)||!Ur()||(Ms--,Ms<=0&&Yi())},lc=c=>{!Wi(c.dataTransfer)||!Ur()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},cc=c=>{var h;if(!Wi(c.dataTransfer)||!Ur())return;c.preventDefault(),c.stopPropagation(),Yi();let g=Array.from((h=c.dataTransfer.files)!=null?h:[]);g.length!==0&&nt.handleFiles(g)},or=!0;ue.addEventListener("dragenter",ac,or),ue.addEventListener("dragleave",ic,or),e.addEventListener("dragover",lc,or),e.addEventListener("drop",cc,or);let Ea=e.ownerDocument,dc=c=>{Ur()&&c.preventDefault()},pc=c=>{Ur()&&c.preventDefault()};Ea.addEventListener("dragover",dc),Ea.addEventListener("drop",pc),yt.push(()=>{$t&&$t.removeEventListener("submit",Cs),he==null||he.removeEventListener("keydown",As),he==null||he.removeEventListener("input",Ss),he==null||he.removeEventListener("paste",ks),co.removeEventListener("keydown",Ts,!0)}),yt.push(()=>{ue.removeEventListener("dragenter",ac,or),ue.removeEventListener("dragleave",ic,or),e.removeEventListener("dragover",lc,or),e.removeEventListener("drop",cc,or),Ea.removeEventListener("dragover",dc),Ea.removeEventListener("drop",pc),Yi()}),yt.push(()=>{V.cancel()}),Xe?yt.push(()=>{Xe==null||Xe.destroy()}):Ze&&yt.push(()=>{Ze==null||Ze.remove()});let nn={update(c){var Zt,Io,rn,Mn,mo,vr,xr,Ma,Ls,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,Yp,Xp,Qp,Jp,Zp,eu,tu;let g=o.toolCall,h=o.messageActions,y=(Zt=o.layout)==null?void 0:Zt.messages,M=o.colorScheme,F=o.loadingIndicator,O=o.iterationDisplay,z=(Io=o.features)==null?void 0:Io.showReasoning,D=(rn=o.features)==null?void 0:rn.showToolCalls,Te=(Mn=o.features)==null?void 0:Mn.toolCallDisplay,me=(mo=o.features)==null?void 0:mo.reasoningDisplay;o={...o,...c},bo(),Kr(e,o),Ri(e,o),Pi(e,o),zn(),o.colorScheme!==M&&Xo();let Z=_l.getForInstance(o.plugins);r.length=0,r.push(...Z),L=(xr=(vr=o.launcher)==null?void 0:vr.enabled)!=null?xr:!0,I=(Ls=(Ma=o.launcher)==null?void 0:Ma.autoExpand)!=null?Ls:!1,ge=(id=(ad=o.features)==null?void 0:ad.showReasoning)!=null?id:!0,se=(cd=(ld=o.features)==null?void 0:ld.showToolCalls)!=null?cd:!0,be=(pd=(dd=o.features)==null?void 0:dd.scrollToBottom)!=null?pd:{},Kt(),No();let Se=ke;if(ke=(md=(ud=o.features)==null?void 0:ud.showEventStreamToggle)!=null?md:!1,ke&&!Se){if(K||(j=new ra(xe),K=new oa(de,j),ye=ye!=null?ye:new sa,j.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),V.setSSEEventCallback((Q,At)=>{var Vt;(Vt=o.onSSEEvent)==null||Vt.call(o,Q,At),ye==null||ye.processEvent(Q,At),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(At)})})),!ht&&He){let Q=(fd=(gd=o.features)==null?void 0:gd.eventStream)==null?void 0:fd.classNames,At="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:"");ht=b("button",At),ht.style.width="28px",ht.style.height="28px",ht.style.color=In.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let Vt=Ee("activity","18px","currentColor",1.5);Vt&&ht.appendChild(Vt);let pt=We.clearChatButtonWrapper,Wt=We.closeButtonWrapper,dn=pt||Wt;dn&&dn.parentNode===He?He.insertBefore(ht,dn):He.appendChild(ht),ht.addEventListener("click",()=>{te?On():An()})}}else!ke&&Se&&(On(),ht&&(ht.remove(),ht=null),K==null||K.clear(),j==null||j.destroy(),K=null,j=null,ye==null||ye.reset(),ye=null);if(((hd=o.launcher)==null?void 0:hd.enabled)===!1&&Xe&&(Xe.destroy(),Xe=null),((bd=o.launcher)==null?void 0:bd.enabled)===!1&&Ze&&(Ze.remove(),Ze=null),((yd=o.launcher)==null?void 0:yd.enabled)!==!1&&!Xe&&!Ze){let Q=r.find(At=>At.renderLauncher);if(Q!=null&&Q.renderLauncher){let At=Q.renderLauncher({config:o,defaultRenderer:()=>Zs(o,Ye).element,onToggle:Ye});At&&(Ze=At,e.appendChild(Ze))}Ze||(Xe=Zs(o,Ye),e.appendChild(Xe.element))}Xe&&Xe.update(o),Me&&((vd=o.launcher)==null?void 0:vd.title)!==void 0&&(Me.textContent=o.launcher.title),Be&&((xd=o.launcher)==null?void 0:xd.subtitle)!==void 0&&(Be.textContent=o.launcher.subtitle);let Le=(wd=o.layout)==null?void 0:wd.header;if((Le==null?void 0:Le.layout)!==x&&He){let Q=Le?bi(o,Le,{showClose:S(),onClose:()=>Ft(!1,"user")}):Mr({config:o,showClose:S(),onClose:()=>Ft(!1,"user")});He.replaceWith(Q.header),He=Q.header,_=Q.iconHolder,Me=Q.headerTitle,Be=Q.headerSubtitle,ze=Q.closeButton,x=Le==null?void 0:Le.layout}else if(Le&&(_&&(_.style.display=Le.showIcon===!1?"none":""),Me&&(Me.style.display=Le.showTitle===!1?"none":""),Be&&(Be.style.display=Le.showSubtitle===!1?"none":""),ze&&(ze.style.display=Le.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let Q=Le.showClearChat;if(Q!==void 0){We.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:At}=We;At&&!At.classList.contains("persona-absolute")&&(Q?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let ot=((Cd=o.layout)==null?void 0:Cd.showHeader)!==!1;He&&(He.style.display=ot?"":"none");let je=((Sd=o.layout)==null?void 0:Sd.showFooter)!==!1;_e&&(_e.style.display=je?"":"none"),Ct(),No(),L!==W?L?Ft(I,"auto"):(A=!0,nr()):I!==H&&Ft(I,"auto"),H=I,W=L,Qt(),fn();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),qe=JSON.stringify((Ad=o.layout)==null?void 0:Ad.messages)!==JSON.stringify(y),Qe=((Td=o.loadingIndicator)==null?void 0:Td.render)!==(F==null?void 0:F.render)||((kd=o.loadingIndicator)==null?void 0:kd.renderIdle)!==(F==null?void 0:F.renderIdle)||((Ed=o.loadingIndicator)==null?void 0:Ed.showBubble)!==(F==null?void 0:F.showBubble),vt=o.iterationDisplay!==O,B=((Ld=(Md=o.features)==null?void 0:Md.showReasoning)!=null?Ld:!0)!==(z!=null?z:!0)||((Rd=(Id=o.features)==null?void 0:Id.showToolCalls)!=null?Rd:!0)!==(D!=null?D:!0)||JSON.stringify((Pd=o.features)==null?void 0:Pd.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((Wd=o.features)==null?void 0:Wd.reasoningDisplay)!==JSON.stringify(me);(Pe||Re||qe||Qe||vt||B)&&V&&(us++,mr(Ne,V.getMessages(),fe));let ne=(Bd=o.launcher)!=null?Bd:{},et=(Hd=ne.headerIconHidden)!=null?Hd:!1,Nt=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showIcon,Ot=et||Nt===!1,zt=ne.headerIconName,at=(Od=ne.headerIconSize)!=null?Od:"48px";if(_){let Q=ue.querySelector(".persona-border-b-persona-divider"),At=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Ot)_.style.display="none",Q&&At&&!Q.contains(At)&&Q.insertBefore(At,Q.firstChild);else{if(_.style.display="",_.style.height=at,_.style.width=at,Q&&At&&(Q.contains(_)?_.nextSibling!==At&&(_.remove(),Q.insertBefore(_,At)):Q.insertBefore(_,At)),zt){let pt=parseFloat(at)||24,Wt=Ee(zt,pt*.6,"#ffffff",2);Wt?_.replaceChildren(Wt):_.textContent=(Nd=ne.agentIconText)!=null?Nd:"\u{1F4AC}"}else if(ne.iconUrl){let pt=_.querySelector("img");if(pt)pt.src=ne.iconUrl,pt.style.height=at,pt.style.width=at;else{let Wt=document.createElement("img");Wt.src=ne.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=at,Wt.style.width=at,_.replaceChildren(Wt)}}else{let pt=_.querySelector("svg"),Wt=_.querySelector("img");(pt||Wt)&&_.replaceChildren(),_.textContent=(_d=ne.agentIconText)!=null?_d:"\u{1F4AC}"}let Vt=_.querySelector("img");Vt&&(Vt.style.height=at,Vt.style.width=at)}}let ln=($d=(Vd=o.layout)==null?void 0:Vd.header)==null?void 0:$d.showTitle,Yn=(zd=(Ud=o.layout)==null?void 0:Ud.header)==null?void 0:zd.showSubtitle;if(Me&&(Me.style.display=ln===!1?"none":""),Be&&(Be.style.display=Yn===!1?"none":""),ze){((jd=(qd=o.layout)==null?void 0:qd.header)==null?void 0:jd.showCloseButton)===!1?ze.style.display="none":ze.style.display="";let At=(Kd=ne.closeButtonSize)!=null?Kd:"32px",Vt=(Gd=ne.closeButtonPlacement)!=null?Gd:"inline";ze.style.height=At,ze.style.width=At;let{closeButtonWrapper:pt}=We,Wt=Vt==="top-right",dn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&Wt!==dn)if(pt.remove(),Wt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(pt);else{let ft=(Xd=(Yd=ne.clearChat)==null?void 0:Yd.placement)!=null?Xd:"inline",pn=(Jd=(Qd=ne.clearChat)==null?void 0:Qd.enabled)!=null?Jd:!0;pt.className=pn&&ft==="inline"?"":"persona-ml-auto";let Hn=ue.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(pt)}if(ze.style.color=ne.closeButtonColor||In.actionIconColor,ne.closeButtonBackgroundColor?(ze.style.backgroundColor=ne.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let ft=ne.closeButtonBorderWidth||"0px",pn=ne.closeButtonBorderColor||"transparent";ze.style.border=`${ft} solid ${pn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");ne.closeButtonBorderRadius?(ze.style.borderRadius=ne.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),ne.closeButtonPaddingX?(ze.style.paddingLeft=ne.closeButtonPaddingX,ze.style.paddingRight=ne.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),ne.closeButtonPaddingY?(ze.style.paddingTop=ne.closeButtonPaddingY,ze.style.paddingBottom=ne.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let vn=(Zd=ne.closeButtonIconName)!=null?Zd:"x",Ao=(ep=ne.closeButtonIconText)!=null?ep:"\xD7";ze.innerHTML="";let Ln=Ee(vn,"28px","currentColor",1);Ln?ze.appendChild(Ln):ze.textContent=Ao;let Jt=(tp=ne.closeButtonTooltipText)!=null?tp:"Close chat",Jn=(np=ne.closeButtonShowTooltip)!=null?np:!0;if(ze.setAttribute("aria-label",Jt),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),Jn&&Jt)){let ft=null,pn=()=>{if(ft||!ze)return;let wr=ze.ownerDocument,Is=wr.body;if(!Is)return;ft=Po(wr,"div","persona-clear-chat-tooltip"),ft.textContent=Jt;let Rs=Po(wr,"div");Rs.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Rs);let Cr=ze.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(ar),ft.style.left=`${Cr.left+Cr.width/2}px`,ft.style.top=`${Cr.top-8}px`,ft.style.transform="translate(-50%, -100%)",Is.appendChild(ft)},Hn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};pt.addEventListener("mouseenter",pn),pt.addEventListener("mouseleave",Hn),ze.addEventListener("focus",pn),ze.addEventListener("blur",Hn),pt._cleanupTooltip=()=>{Hn(),pt&&(pt.removeEventListener("mouseenter",pn),pt.removeEventListener("mouseleave",Hn)),ze&&(ze.removeEventListener("focus",pn),ze.removeEventListener("blur",Hn))}}}let{clearChatButton:Ke,clearChatButtonWrapper:wt}=We;if(Ke){let Q=(op=ne.clearChat)!=null?op:{},At=(rp=Q.enabled)!=null?rp:!0,Vt=(ap=(sp=o.layout)==null?void 0:sp.header)==null?void 0:ap.showClearChat,pt=Vt!==void 0?Vt:At,Wt=(ip=Q.placement)!=null?ip:"inline";if(wt){wt.style.display=pt?"":"none";let{closeButtonWrapper:dn}=We;!k()&&dn&&!dn.classList.contains("persona-absolute")&&(pt?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let vn=Wt==="top-right",Ao=wt.classList.contains("persona-absolute");if(!k()&&vn!==Ao&&pt){if(wt.remove(),vn)wt.className="persona-absolute persona-top-4 persona-z-50",wt.style.right="48px",ue.style.position="relative",ue.appendChild(wt);else{wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wt.style.right="";let Jt=ue.querySelector(".persona-border-b-persona-divider"),Jn=We.closeButtonWrapper;Jt&&Jn&&Jn.parentElement===Jt?Jt.insertBefore(wt,Jn):Jt&&Jt.appendChild(wt)}let Ln=We.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(vn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(pt){if(!k()){let ft=(lp=Q.size)!=null?lp:"32px";Ke.style.height=ft,Ke.style.width=ft}let dn=(cp=Q.iconName)!=null?cp:"refresh-cw",vn=(dp=Q.iconColor)!=null?dp:"";Ke.style.color=vn||In.actionIconColor,Ke.innerHTML="";let Ao=k()?"14px":"20px",Ln=Ee(dn,Ao,"currentColor",2);if(Ln&&Ke.appendChild(Ln),Q.backgroundColor?(Ke.style.backgroundColor=Q.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ft=Q.borderWidth||"0px",pn=Q.borderColor||"transparent";Ke.style.border=`${ft} solid ${pn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");Q.borderRadius?(Ke.style.borderRadius=Q.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),Q.paddingX?(Ke.style.paddingLeft=Q.paddingX,Ke.style.paddingRight=Q.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),Q.paddingY?(Ke.style.paddingTop=Q.paddingY,Ke.style.paddingBottom=Q.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Jt=(pp=Q.tooltipText)!=null?pp:"Clear chat",Jn=(up=Q.showTooltip)!=null?up:!0;if(Ke.setAttribute("aria-label",Jt),wt&&(wt._cleanupTooltip&&(wt._cleanupTooltip(),delete wt._cleanupTooltip),Jn&&Jt)){let ft=null,pn=()=>{if(ft||!Ke)return;let wr=Ke.ownerDocument,Is=wr.body;if(!Is)return;ft=Po(wr,"div","persona-clear-chat-tooltip"),ft.textContent=Jt;let Rs=Po(wr,"div");Rs.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Rs);let Cr=Ke.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(ar),ft.style.left=`${Cr.left+Cr.width/2}px`,ft.style.top=`${Cr.top-8}px`,ft.style.transform="translate(-50%, -100%)",Is.appendChild(ft)},Hn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};wt.addEventListener("mouseenter",pn),wt.addEventListener("mouseleave",Hn),Ke.addEventListener("focus",pn),Ke.addEventListener("blur",Hn),wt._cleanupTooltip=()=>{Hn(),wt&&(wt.removeEventListener("mouseenter",pn),wt.removeEventListener("mouseleave",Hn)),Ke&&(Ke.removeEventListener("focus",pn),Ke.removeEventListener("blur",Hn))}}}}let Xn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[$l],on=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[aa.message,aa.messageAndClick];E=Ul({parsers:Xn,handlers:on,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),fe=Qm(o,E,G),V.updateConfig(o),mr(Ne,V.getMessages(),fe),yo.render(o.suggestionChips,V,he,void 0,o.suggestionChipsConfig),xs(),Or(V.isStreaming());let uo=((mp=o.voiceRecognition)==null?void 0:mp.enabled)===!0,Qn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),hr=((fp=(gp=o.voiceRecognition)==null?void 0:gp.provider)==null?void 0:fp.type)==="runtype";if(uo&&(Qn||hr))if(!q||!Ut){let Q=$r(o.voiceRecognition,o.sendButton);Q&&(q=Q.micButton,Ut=Q.micButtonWrapper,Rt.insertBefore(Ut,Rn),q.addEventListener("click",Ie),q.disabled=V.isStreaming())}else{let Q=(hp=o.voiceRecognition)!=null?hp:{},At=(bp=o.sendButton)!=null?bp:{},Vt=(yp=Q.iconName)!=null?yp:"mic",pt=(vp=At.size)!=null?vp:"40px",Wt=(xp=Q.iconSize)!=null?xp:pt,dn=parseFloat(Wt)||24;q.style.width=Wt,q.style.height=Wt,q.style.minWidth=Wt,q.style.minHeight=Wt;let vn=(Cp=(wp=Q.iconColor)!=null?wp:At.textColor)!=null?Cp:"currentColor";q.innerHTML="";let Ao=Ee(Vt,dn,vn,2);Ao?q.appendChild(Ao):q.textContent="\u{1F3A4}";let Ln=(Sp=Q.backgroundColor)!=null?Sp:At.backgroundColor;Ln?q.style.backgroundColor=Ln:q.style.backgroundColor="",vn?q.style.color=vn: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 Jt=Ut==null?void 0:Ut.querySelector(".persona-send-button-tooltip"),Jn=(Ap=Q.tooltipText)!=null?Ap:"Start voice recognition";if(((Tp=Q.showTooltip)!=null?Tp:!1)&&Jn)if(Jt)Jt.textContent=Jn,Jt.style.display="";else{let pn=document.createElement("div");pn.className="persona-send-button-tooltip",pn.textContent=Jn,Ut==null||Ut.insertBefore(pn,q)}else Jt&&(Jt.style.display="none");Ut.style.display="",q.disabled=V.isStreaming()}else q&&Ut&&(Ut.style.display="none",((Ep=(kp=o.voiceRecognition)==null?void 0:kp.provider)==null?void 0:Ep.type)==="runtype"?V.isVoiceActive()&&V.toggleVoice():Gn&&So());if(((Mp=o.attachments)==null?void 0:Mp.enabled)===!0)if(!_t||!Je){let Q=(Lp=o.attachments)!=null?Lp:{},Vt=(Rp=((Ip=o.sendButton)!=null?Ip:{}).size)!=null?Rp:"40px";we||(we=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),we.style.display="none",$t.insertBefore(we,he)),re||(re=document.createElement("input"),re.type="file",re.accept=((Pp=Q.allowedTypes)!=null?Pp:Uo).join(","),re.multiple=((Wp=Q.maxFiles)!=null?Wp:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),$t.insertBefore(re,he)),_t=b("div","persona-send-button-wrapper"),Je=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Je.type="button",Je.setAttribute("aria-label",(Bp=Q.buttonTooltipText)!=null?Bp:"Attach file");let pt=(Hp=Q.buttonIconName)!=null?Hp:"paperclip",Wt=Vt,dn=parseFloat(Wt)||40,vn=Math.round(dn*.6);Je.style.width=Wt,Je.style.height=Wt,Je.style.minWidth=Wt,Je.style.minHeight=Wt,Je.style.fontSize="18px",Je.style.lineHeight="1",Je.style.backgroundColor="transparent",Je.style.color="var(--persona-primary, #111827)",Je.style.border="none",Je.style.borderRadius="6px",Je.style.transition="background-color 0.15s ease",Je.addEventListener("mouseenter",()=>{Je.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Je.addEventListener("mouseleave",()=>{Je.style.backgroundColor="transparent"});let Ao=Ee(pt,vn,"currentColor",1.5);Ao?Je.appendChild(Ao):Je.textContent="\u{1F4CE}",Je.addEventListener("click",Jn=>{Jn.preventDefault(),re==null||re.click()}),_t.appendChild(Je);let Ln=(Dp=Q.buttonTooltipText)!=null?Dp:"Attach file",Jt=b("div","persona-send-button-tooltip");Jt.textContent=Ln,_t.appendChild(Jt),st.append(_t),!nt&&re&&we&&(nt=zs.fromConfig(Q),nt.setPreviewsContainer(we),re.addEventListener("change",async()=>{nt&&(re!=null&&re.files)&&(await nt.handleFileSelect(re.files),re.value="")})),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(Jm(Q.dropOverlay))}else{_t.style.display="";let Q=(Fp=o.attachments)!=null?Fp:{};re&&(re.accept=((Op=Q.allowedTypes)!=null?Op:Uo).join(","),re.multiple=((Np=Q.maxFiles)!=null?Np:4)>1),nt&&nt.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else _t&&(_t.style.display="none"),nt&&nt.clearAttachments(),(_p=ue.querySelector(".persona-attachment-drop-overlay"))==null||_p.remove();let Gt=(Vp=o.sendButton)!=null?Vp:{},br=($p=Gt.useIcon)!=null?$p:!1,rr=(Up=Gt.iconText)!=null?Up:"\u2191",sr=Gt.iconName,$o=(zp=Gt.tooltipText)!=null?zp:"Send message",yr=(qp=Gt.showTooltip)!=null?qp:!1,tt=(jp=Gt.size)!=null?jp:"40px",yn=Gt.backgroundColor,gn=Gt.textColor;if(br){if(ce.style.width=tt,ce.style.height=tt,ce.style.minWidth=tt,ce.style.minHeight=tt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.innerHTML="",gn?ce.style.color=gn:ce.style.color="var(--persona-button-primary-fg, #ffffff)",sr){let Q=parseFloat(tt)||24,At=(gn==null?void 0:gn.trim())||"currentColor",Vt=Ee(sr,Q,At,2);Vt?ce.appendChild(Vt):ce.textContent=rr}else ce.textContent=rr;ce.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",yn?(ce.style.backgroundColor=yn,ce.classList.remove("persona-bg-persona-primary")):(ce.style.backgroundColor="",ce.classList.add("persona-bg-persona-primary"))}else ce.textContent=(Gp=(Kp=o.copy)==null?void 0:Kp.sendButtonLabel)!=null?Gp:"Send",ce.style.width="",ce.style.height="",ce.style.minWidth="",ce.style.minHeight="",ce.style.fontSize="",ce.style.lineHeight="",ce.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",yn?(ce.style.backgroundColor=yn,ce.classList.remove("persona-bg-persona-accent")):ce.classList.add("persona-bg-persona-accent"),gn?ce.style.color=gn:ce.classList.add("persona-text-white");Gt.borderWidth?(ce.style.borderWidth=Gt.borderWidth,ce.style.borderStyle="solid"):(ce.style.borderWidth="",ce.style.borderStyle=""),Gt.borderColor?ce.style.borderColor=Gt.borderColor:ce.style.borderColor="",Gt.paddingX?(ce.style.paddingLeft=Gt.paddingX,ce.style.paddingRight=Gt.paddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),Gt.paddingY?(ce.style.paddingTop=Gt.paddingY,ce.style.paddingBottom=Gt.paddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let cn=Rn==null?void 0:Rn.querySelector(".persona-send-button-tooltip");if(yr&&$o)if(cn)cn.textContent=$o,cn.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=$o,Rn==null||Rn.insertBefore(Q,ce)}else cn&&(cn.style.display="none");let gt=(Zp=(Yp=o.layout)==null?void 0:Yp.contentMaxWidth)!=null?Zp:k()?(Jp=(Qp=(Xp=o.launcher)==null?void 0:Xp.composerBar)==null?void 0:Qp.contentMaxWidth)!=null?Jp:"720px":void 0;gt?(Ne.style.maxWidth=gt,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%",$t&&($t.style.maxWidth=gt,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Bt&&(Bt.style.maxWidth=gt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto")):(Ne.style.maxWidth="",Ne.style.marginLeft="",Ne.style.marginRight="",Ne.style.width="",$t&&($t.style.maxWidth="",$t.style.marginLeft="",$t.style.marginRight=""),Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""));let it=(eu=o.statusIndicator)!=null?eu:{},kt=(tu=it.visible)!=null?tu:!0;if(mn.style.display=kt?"":"none",V){let Q=V.getStatus();rt(mn,(Vt=>{var pt,Wt,dn,vn;return Vt==="idle"?(pt=it.idleText)!=null?pt:xn.idle:Vt==="connecting"?(Wt=it.connectingText)!=null?Wt:xn.connecting:Vt==="connected"?(dn=it.connectedText)!=null?dn:xn.connected:Vt==="error"?(vn=it.errorText)!=null?vn:xn.error:xn[Vt]})(Q),it,Q)}mn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Bn=it.align==="left"?"persona-text-left":it.align==="center"?"persona-text-center":"persona-text-right";mn.classList.add(Bn)},open(){S()&&Ft(!0,"api")},close(){S()&&Ft(!1,"api")},toggle(){S()&&Ft(!A,"api")},clearChat(){Tn=!1,V.clearMessages(),ve.clear(),Qo();try{localStorage.removeItem(is),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==is)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={},E.syncFromMetadata(),K==null||K.clear(),ye==null||ye.reset(),le==null||le.update()},setMessage(c){return!he||V.isStreaming()?!1:(!A&&S()&&Ft(!0,"system"),he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(V.isStreaming())return!1;let g=(c==null?void 0:c.trim())||he.value.trim();return g?(!A&&S()&&Ft(!0,"system"),he.value="",he.style.height="auto",V.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return V.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?(V.isVoiceActive()||(!A&&S()&&Ft(!0,"system"),bt.manuallyDeactivated=!1,Wn(),V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),lo("user"),V.isVoiceActive()&&R()})),!0):Gn?!0:Es()?(!A&&S()&&Ft(!0,"system"),bt.manuallyDeactivated=!1,Wn(),fr("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Wn(),lo("user"),Y()}),!0):!1:Gn?(bt.manuallyDeactivated=!0,Wn(),So("user"),!0):!1},injectMessage(c){return!A&&S()&&Ft(!0,"system"),V.injectMessage(c)},injectAssistantMessage(c){!A&&S()&&Ft(!0,"system");let g=V.injectAssistantMessage(c);return N&&(N=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),g},injectUserMessage(c){return!A&&S()&&Ft(!0,"system"),V.injectUserMessage(c)},injectSystemMessage(c){return!A&&S()&&Ft(!0,"system"),V.injectSystemMessage(c)},injectMessageBatch(c){return!A&&S()&&Ft(!0,"system"),V.injectMessageBatch(c)},injectComponentDirective(c){return!A&&S()&&Ft(!0,"system"),V.injectComponentDirective(c)},injectTestMessage(c){!A&&S()&&Ft(!0,"system"),V.injectTestEvent(c)},async connectStream(c,g){return V.connectStream(c,g)},__pushEventStreamEvent(c){K&&(ye==null||ye.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ke||!K||An()},hideEventStream(){te&&On()},isEventStreamVisible(){return te},showArtifacts(){ho(o)&&(Tn=!1,zn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){ho(o)&&(Tn=!0,zn())},upsertArtifact(c){return ho(o)?(Tn=!1,V.upsertArtifact(c)):null},selectArtifact(c){ho(o)&&V.selectArtifact(c)},clearArtifacts(){ho(o)&&V.clearArtifacts()},getArtifacts(){var c;return(c=V==null?void 0:V.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=V==null?void 0:V.getSelectedArtifactId())!=null?c:null},focusInput(){return L&&!A&&!k()||!he?!1:(he.focus(),!0)},async resolveApproval(c,g,h){let M=V.getMessages().find(F=>{var O;return F.variant==="approval"&&((O=F.approval)==null?void 0:O.id)===c});if(!(M!=null&&M.approval))throw new Error(`Approval not found: ${c}`);if(M.approval.toolType==="webmcp"){V.resolveWebMcpApproval(M.id,g);return}return V.resolveApproval(M.approval,g,h)},getMessages(){return V.getMessages()},getStatus(){return V.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()&&A},isVoiceActive(){return bt.active},getState(){return{open:S()&&A,launcherEnabled:L,voiceActive:bt.active,streaming:V.isStreaming()}},showCSATFeedback(c){!A&&S()&&Ft(!0,"system");let g=Ne.querySelector(".persona-feedback-container");g&&g.remove();let h=Gm({onSubmit:async(y,M)=>{var F;V.isClientTokenMode()&&await V.submitCSATFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});Ne.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!A&&S()&&Ft(!0,"system");let g=Ne.querySelector(".persona-feedback-container");g&&g.remove();let h=Ym({onSubmit:async(y,M)=>{var F;V.isClientTokenMode()&&await V.submitNPSFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});Ne.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return V.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return V.submitNPSFeedback(c,g)},destroy(){Lo!=null&&(clearInterval(Lo),Lo=null),yt.forEach(c=>c()),Ae.remove(),$e==null||$e.remove(),Xe==null||Xe.destroy(),Ze==null||Ze.remove(),jn&&ze.removeEventListener("click",jn)}};if((((ed=n==null?void 0:n.debugTools)!=null?ed:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:nn,getMessages:nn.getMessages,getStatus:nn.getStatus,getMetadata:nn.getPersistentMetadata,updateMetadata:nn.updatePersistentMetadata,clearHistory:()=>nn.clearChat(),setVoiceActive:h=>h?nn.startVoiceRecognition():nn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,yt.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 D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",g),yt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ke){let z=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&nn.showEventStream()},D=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",D),yt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",D)})}let h=z=>{let D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.showArtifacts()},y=z=>{let D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.hideArtifacts()},M=z=>{let D=z.detail;D!=null&&D.instanceId&&D.instanceId!==c||D!=null&&D.artifact&&nn.upsertArtifact(D.artifact)},F=z=>{let D=z.detail;D!=null&&D.instanceId&&D.instanceId!==c||typeof(D==null?void 0:D.id)=="string"&&nn.selectArtifact(D.id)},O=z=>{let D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",O),yt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",O)})}let po=vx(o.persistState);if(po&&S()){let c=xx(po.storage),g=`${po.keyPrefix}widget-open`,h=`${po.keyPrefix}widget-voice`,y=`${po.keyPrefix}widget-voice-mode`;if(c){let M=((td=po.persist)==null?void 0:td.openState)&&c.getItem(g)==="true",F=((nd=po.persist)==null?void 0:nd.voiceState)&&c.getItem(h)==="true",O=((od=po.persist)==null?void 0:od.voiceState)&&c.getItem(y)==="true";if(M&&setTimeout(()=>{nn.open(),setTimeout(()=>{var z;if(F||O)nn.startVoiceRecognition();else if((z=po.persist)!=null&&z.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(rd=po.persist)!=null&&rd.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(sd=po.persist)!=null&&sd.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")})),po.clearOnChatClear){let z=()=>{c.removeItem(g),c.removeItem(h),c.removeItem(y)},D=()=>z();window.addEventListener("persona:clear-chat",D),yt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return m&&S()&&setTimeout(()=>{nn.open()},0),_o(),nn};var wx=(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},eg=(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"},Gl=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=""},tg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Gl(e)},ql=e=>{e.style.transition=""},jl=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=""},Kl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Bi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Cx=(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))},Sx=(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)},ng=(e,t,n,o,r,s,a)=>{var C,v,E,L,I,P;let i=Wo(s),d=i.reveal==="push";Cx(e,t,n,o,d),Sx(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,m=(v=(C=s==null?void 0:s.launcher)==null?void 0:C.mobileFullscreen)!=null?v:!0,p=(L=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?L:640,f=l!=null?l.innerWidth<=p:!1;if(m&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),jl(t),ql(o),tg(o),Kl(n),Bi(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((P=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?P:wn),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"),tg(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",jl(t),ql(o),Kl(n),Bi(r,o);let H=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",x=a?"translateX(0)":W;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=x,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",ql(o),Gl(o),Bi(r,o);let H=wx(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),x=i.animate?"transform 180ms ease":"none",w=i.side==="right"?a?`translateX(-${H}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${H}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${W+H}px`,t.style.transition=x,t.style.transform=w,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,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="",jl(t),Gl(o),Kl(n),Bi(r,o);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",x=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 ${W}`,o.style.width=W,o.style.maxWidth=W,o.style.minWidth=W,o.style.minHeight="0",o.style.position="relative",o.style.overflow=H||w?"hidden":"visible",o.style.transition=x,H&&(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")}},Ax=(e,t)=>{let n=e.ownerDocument.createElement("div");return eg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){eg(n,o)},destroy(){n.remove()}}},Tx=(e,t)=>{var I,P,H,W;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"),m=n.createElement("div"),p=(P=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||P?(W=(H=t==null?void 0:t.launcher)==null?void 0:H.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",m.dataset.personaDockRole="host",l.appendChild(m),o.insertBefore(a,e),d.appendChild(e);let f=null,u=()=>{f==null||f.disconnect(),f=null},C=()=>{u(),Wo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{ng(a,i,d,l,m,t,p)}),f.observe(a))},v=()=>{ng(a,i,d,l,m,t,p),C()},E=a.ownerDocument.defaultView,L=()=>{v()};return E==null||E.addEventListener("resize",L),Wo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:m,shell:a,syncWidgetState(x){let w=x.launcherEnabled?x.open:!0;p!==w&&(p=w,v())},updateConfig(x){var w,k;t=x,((k=(w=t==null?void 0:t.launcher)==null?void 0:w.enabled)!=null?k:!0)===!1&&(p=!0),v()},destroy(){E==null||E.removeEventListener("resize",L),u(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},og=(e,t)=>hn(t)?Tx(e,t):Ax(e,t);var ls={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Yl=.15,Xl=1.5,Hi="persona-preview-shell-theme",rg={load:()=>null,save:()=>{},clear:()=>{}},sg=["How do I get started?","Pricing & plans","Talk to support"];function Di(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ag(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=ag(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 Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
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
|
|
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(Hi);o||(o=n.createElement("style"),o.id=Hi,n.head.appendChild(o)),o.textContent=Ql(t)}var ig=`
|
|
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>
|
|
@@ -147,7 +147,7 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
147
147
|
<div class="preview-iframe-line body"></div>
|
|
148
148
|
<div class="preview-iframe-line body"></div>
|
|
149
149
|
</div>
|
|
150
|
-
</div>`,
|
|
150
|
+
</div>`,lg=`
|
|
151
151
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
152
152
|
<div class="preview-iframe-line hero"></div>
|
|
153
153
|
<div class="preview-iframe-line body"></div>
|
|
@@ -160,8 +160,8 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
160
160
|
<div class="preview-workspace-card short"></div>
|
|
161
161
|
<div class="preview-workspace-card short"></div>
|
|
162
162
|
</div>
|
|
163
|
-
</div>`;function
|
|
164
|
-
${
|
|
163
|
+
</div>`;function Zl(e,t,n,o){let r=`
|
|
164
|
+
${ig}
|
|
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">
|
|
167
167
|
<div class="preview-workspace-topbar">
|
|
@@ -173,7 +173,7 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
173
173
|
</div>
|
|
174
174
|
<div class="preview-workspace-body">
|
|
175
175
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
176
|
-
${
|
|
176
|
+
${lg}
|
|
177
177
|
</div>
|
|
178
178
|
</div>
|
|
179
179
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
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="${
|
|
185
|
-
<style id="${
|
|
184
|
+
<link rel="stylesheet" href="${Di(o)}">
|
|
185
|
+
<style id="${Hi}">${Ql(t)}</style>
|
|
186
186
|
</head>
|
|
187
187
|
<body>
|
|
188
188
|
${n?s:r}
|
|
189
189
|
</body>
|
|
190
|
-
</html>`}var
|
|
190
|
+
</html>`}var kx={"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)","approval-request":"Approval request"};function Ex(e){return kx[e]}function ec(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:","","","","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
|
|
194
|
-
${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${
|
|
195
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
196
|
-
</div>`,
|
|
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"approval-request":{let r=`preview-approval-${o}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${o}`,toolName:"add_to_cart",description:"Add the selected item to the shopping cart. Approve to let the assistant continue.",parameters:{items:[{productEntityId:129,quantity:1}]}}}}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 Mx(e,t){return[...e,ec(t,e.length)]}function cg(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function Lx(e,t,n){var d,l;let o=ec(e,t);if(!cg(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 m=r;m<a.length;m+=r)i.push({message:{...o,content:a.slice(0,m),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var Ix=()=>[{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()}],Rx=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 dg(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"&&Rx(t)?[...Ix(),...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 tc(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:sg:e.suggestionChips,initialMessages:dg(t,e,n),storageAdapter:rg};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Wr(e,t){var s,a,i,d;let n=e.theme?sn(e.theme,{validate:!1}):sn(),o=(s=e.scene)!=null?s:"conversation",r={...It,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return tc(r,o,(d=e.appendedMessages)!=null?d:[])}function Px(e,t,n){var a,i,d;let o=e.theme?sn(e.theme,{validate:!1}):sn(),r=(a=e.scene)!=null?a:"conversation",s={...It,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return tc(s,r,t)}function pg(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:Wr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Wr(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:Wr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Wr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Wr(e,n),shellMode:n}]}function Wx(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function m(){var I;return(I=n.device)!=null?I:"desktop"}function p(){var I;return(I=n.zoom)!=null?I:i}function f(){var A,N;let I=getComputedStyle(e),P=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),H=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),W=40,x=((A=n.compareMode)!=null?A:"off")!=="off",w=(e.clientWidth-P-W)/(x?2:1),k=e.clientHeight-H-W;if(w<=0||k<=0)return 1;let S=(N=ls[m()])!=null?N:ls.desktop;return Math.min(w/S.w,k/S.h,1)}function u(){var H,W,x;i=f();let I=Math.max(Yl,Math.min(Xl,p()));d=I;let P=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let w of P){let k=(H=w.dataset.device)!=null?H:"desktop",S=(W=ls[k])!=null?W:ls.desktop;w.style.width=`${S.w*I}px`,w.style.height=`${S.h*I}px`,k==="mobile"&&(w.style.borderRadius=`${32*I}px`);let A=w.querySelector("iframe");A&&(A.style.width=`${S.w}px`,A.style.height=`${S.h}px`,A.style.transformOrigin="top left",A.style.transition="none",A.style.transform=`scale(${I})`)}(x=n.onScaleChange)==null||x.call(n,I)}function C(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let P of o)P.destroy();for(let P of r)P();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function E(){var se,ke,be,Fe;if(a)return;C();let I=++l,P=pg(n),H=m(),W=((se=n.compareMode)!=null?se:"off")!=="off",x=((ke=n.scene)!=null?ke:"conversation")==="minimized",w=(be=n.widgetCssPath)!=null?be:"/widget-dist/widget.css",k=(Fe=n.buildSrcdoc)!=null?Fe:Zl,S=H==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",A=xe=>`<div class="${S}" data-mount-id="${xe.mountId}" data-device="${H}" data-shell-mode="${xe.shellMode}">
|
|
194
|
+
${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${Di(xe.label)}</span></div>`:""}
|
|
195
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${xe.mountId}"></iframe>
|
|
196
|
+
</div>`,N=W?`<div class="preview-compare-grid">${P.map(xe=>`<div class="preview-compare-cell">${A(xe)}</div>`).join("")}</div>`:`<div class="preview-single">${A(P[0])}</div>`;n.morphContainer?n.morphContainer(e,N):e.innerHTML=N,u();let $=v(),G=0,fe=$.length,ge=()=>{var j,de,K,ye,le;if(a||I!==l)return;for(let te of $){let Ce=te.dataset.mountId;if(!Ce||!te.contentDocument)continue;let Ue=P.find(Ae=>Ae.mountId===Ce);if(!Ue)continue;let ee=()=>{},oe=hn(Ue.config),ae=oe?(()=>{var X;let Ae=(X=te.contentDocument)==null?void 0:X.getElementById(`preview-content-${Ce}`);if(!Ae)return null;let pe=og(Ae,Ue.config),$e=te.contentDocument.createElement("div");$e.id=Ce,$e.style.height="100%",$e.style.display="flex",$e.style.flexDirection="column",$e.style.flex="1",$e.style.minHeight="0",pe.host.appendChild($e);let We=()=>pe.syncWidgetState(rt.getState()),ue=ee;return ee=()=>{pe.destroy(),ue()},$e.__syncDock=We,$e.__hostLayout=pe,$e})():te.contentDocument.getElementById(Ce);if(!ae)continue;let rt=Zm(ae,Ue.config);if(o.push(rt),oe&&ae.__syncDock){let Ae=ae.__syncDock,pe=rt.on("widget:opened",Ae),$e=rt.on("widget:closed",Ae),We=ee;ee=()=>{pe(),$e(),We()},Ae()}r.push(ee),x&&rt.close()}if(((j=n.scene)!=null?j:"conversation")==="artifact"||(ye=(K=(de=n.config)==null?void 0:de.features)==null?void 0:K.artifacts)!=null&&ye.enabled)for(let te of o)te.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`});(Se=n.onAfterMount)==null||Se.call(n,{iframes:$,controllers:[...o]})};for(let ve of $){let Q=ve.dataset.mountId;if(!Q)continue;let Le=H.find(Y=>Y.mountId===Q);Le&&(ve.addEventListener("load",()=>{j++,j>=me&&se()},{once:!0}),ve.srcdoc=k(Q,Le.shellMode,pn(Le.config),x))}me===0&&se()}function I(){var D;if(a)return;let L=Jm(n);if(o.length!==L.length){M();return}if(L.some(W=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!v||v.dataset.shellMode!==W.shellMode})){M();return}o.forEach((W,v)=>{var x;W.update(L[v].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&W.close()});for(let W of L){let v=e.querySelector(`iframe[data-mount-id="${W.mountId}"]`);v&&Kl(v,W.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:S(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||p()}),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():I()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},p())},getIframes(){return S()},getScale(){return d},setZoom(L){a||(n={...n,zoom:L},p())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Bi={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"},xx=/^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 wx(e){return xx.test(e)}function os(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=Bi[t];if(n)return n;let o=Es(t);if(Qi(o)||o==="transparent"||wx(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(Bi).slice(0,6).join(", ")}).`)}var Hi=Ia.map(e=>e==="gray"?"neutral":e),Cx={...Object.fromEntries(Hi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Di(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Cx[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 Fi(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 Oi(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 Sx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ni(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Sx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function _i(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=Yi(t);return Xi(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Vi(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 Zm=Vi("typo-font-family"),ta=Vi("typo-font-size"),na=Vi("typo-font-weight"),Wi=Vi("typo-line-height"),ef={...Zm,monospace:Zm.mono},tf={...ta,small:ta.sm,md:ta.base,medium:ta.base,large:ta.lg},nf={...na,400:na.normal,500:na.medium,600:na.semibold,700:na.bold},of={...Wi,"1.25":Wi.tight,"1.5":Wi.normal,"1.625":Wi.relaxed};function rf(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 sf="theme.palette.radius.";function Ax(){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(sf)&&typeof i=="string"&&(s[a.slice(sf.length)]=i);e[r[1]]=s}return e}var ra=Ax(),af=["sm","md","lg","xl","full"];function Ui(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Ui(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Ui(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 rs(e){return e.replace(/^role-/,"")}function Tx(e){for(let[t,n]of Object.entries(ra))if(af.every(o=>e[o]===n[o]))return t;return"custom"}function Ir(e){var o,r;let t={};for(let s of af)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of wr)n[rs(s.roleId)]=tl(a=>e.get(`theme.${a}`),s);return{brand:{primary:Ql(e.get("theme.palette.colors.primary.500")),secondary:Ql(e.get("theme.palette.colors.secondary.500")),accent:Ql(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:Tx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Ql(e){return typeof e=="string"&&e!==""?e:null}var oa=[{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 lf(e){let t=new Set(e.targets.map(n=>n.path));return oa.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var kx={AA:4.5,AAA:7};function Ex(e){return Math.round(e*100)/100}function Mx(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,m=1/0;return Ur.forEach((u,g)=>{let p=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof p!="string"||!(p.startsWith("#")||p.startsWith("rgb")))&&La(p,n)>=o){let w=d>=0?Math.abs(g-d):g;w<m&&(m=w,l=`palette.colors.${i}.${u}`)}}),l}function sa(e,t="AA",n="both",o){let r=kx[t],s=n==="both"?["light","dark"]:[n],a=o?oa.filter(d=>o.includes(d.key)):oa,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let u=Ui(e,m.fg,l),g=Ui(e,m.bg,l);if(!u||!g)continue;let p=Ex(La(u,g)),w=p>=r,S={pair:m.key,label:m.label,variant:d,fg:u,bg:g,ratio:p,threshold:r,passes:w};if(!w){let M=Mx(e,m.fg,g,r,l);M&&(S.suggestion=M)}i.push(S)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function ss(e,t,n="light",o="AA"){return t.length===0?[]:sa(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=rs(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 Lx(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=wr.map(r=>rs(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function cf(){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 ol)t(n.sections);for(let n of Va)t(n.sections);return e}var Ix={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Rx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Jl=["bottom-right","bottom-left","top-right","top-left"],Zl=["bubble","flat","minimal"],Px={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function df(e,t){var W;let n=(W=t==null?void 0:t.editTarget)!=null?W:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,x,k=n)=>{let C={};return(k==="light"||k==="both")&&(C[`theme.${v}`]=x),(k==="dark"||k==="both")&&(C[`darkTheme.${v}`]=x),C},a=v=>{if(n==="both")return v;let x={};for(let[k,C]of Object.entries(v))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=C);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(C=>({role:rs(C.roleId),helper:C.helper})),availableFamilies:Hi,presets:Ls.map(C=>{var T;return{id:C.id,name:C.name,description:C.description,tags:(T=C.tags)!=null?T:[]}}),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=cf()),k.fieldIndex=Array.from(o.values()).map(C=>{var T;return{id:C.id,path:C.path,type:C.type,label:C.label,options:(T=C.options)==null?void 0:T.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"],C={},T={};for(let $ of k){if(x[$]===void 0)continue;let j=os(x[$]);T[$]=j;let me=Zi(j);for(let se of Ur){let fe=me[se];fe!==void 0&&Object.assign(C,s(`palette.colors.${$}.${se}`,fe))}}if(Object.keys(T).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(C);let F=ss(e,["primary-button","user-message"],i());return d(T,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:Hi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let x=r(v),k=Lx(x.role),C=Di(x.family,!0),T=Fi(x.intensity),F=a(_a(C,T,k)),$=Object.keys(F).length;e.setBatch(F);let j=ss(e,lf(k),i());return d({role:rs(k.roleId),family:C,intensity:T,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={},C={},T=(F,$)=>{var me;if(x[F]===void 0)return;let j=rf(x[F],$,F);C[F]=(me=j.split(".").pop())!=null?me:j,Object.assign(k,s(`semantic.typography.${F}`,j))};if(T("fontFamily",ef),T("fontSize",tf),T("fontWeight",nf),T("lineHeight",of),Object.keys(C).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(C)}},{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={},C={};if(x.style!==void 0){let T=Ni(x.style);C.style=T;for(let[F,$]of Object.entries(ra[T]))Object.assign(k,s(`palette.radius.${F}`,$))}if(x.radius!==void 0){let T=r(x.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(T[$]===void 0)continue;let j=_i(T[$]);F[$]=j,Object.assign(k,s(`palette.radius.${$}`,j))}C.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(C)}},{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 C=Oi(x.scheme);e.set("colorScheme",C),k.scheme=C}if(x.editTarget!==void 0){let C=String(x.editTarget).trim().toLowerCase();if(C!=="light"&&C!=="dark"&&C!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=C,k.editTarget=C}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=rl(String(x!=null?x:""));if(!k){let $=Ls.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${$}.`)}let C=tn(k.theme,{validate:!1}),T={...e.getConfig()};k.darkTheme&&(T.darkTheme=tn(k.darkTheme,{validate:!1})),k.toolCall&&(T.toolCall=k.toolCall),e.setFullConfig(T,C);let F=ss(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:Jl},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:Zl}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,j,me;let x=r(v),k={},C={};if(x.launcherPosition!==void 0){let se=String(x.launcherPosition);if(!Jl.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Jl.join(", ")}.`);k["launcher.position"]=se,C.launcherPosition=se}let T=r(x.features);for(let[se,fe]of Object.entries(Ix))T[se]!==void 0&&(k[fe]=!!T[se],($=C.features)!=null||(C.features={}),C.features[se]=!!T[se]);let F=r(x.layout);for(let[se,fe]of Object.entries(Rx))if(F[se]!==void 0)if(se==="messageStyle"){let ie=String(F[se]);if(!Zl.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Zl.join(", ")}.`);k[fe]=ie,(j=C.layout)!=null||(C.layout={}),C.layout[se]=ie}else k[fe]=!!F[se],(me=C.layout)!=null||(C.layout={}),C.layout[se]=!!F[se];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(C)}},{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={},C={};for(let[T,F]of Object.entries(Px))x[T]!==void 0&&(k[F]=String(x[T]),C[T]=String(x[T]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let T=x.suggestions.filter(F=>typeof F=="string");k.suggestionChips=T,C.suggestions=T}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(C)}},{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=cf());let k={},C=[];for(let $ of x){let j=r($),me=String((F=j.field)!=null?F:"");try{let se=o.get(me),fe=se?se.path:me;if(!se&&!/^(theme|darkTheme)\.|\./.test(fe))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Wx(se,j.value);if(se&&fe.startsWith("theme.")){let be=s(fe.slice(6),ie);Object.assign(k,be),C.push({field:me,resolvedPath:Object.keys(be),ok:!0})}else k[fe]=ie,C.push({field:me,resolvedPath:fe,ok:!0})}catch(se){C.push({field:me,ok:!1,error:se.message})}}let T=C.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),Vo({ok:T.length>0,summary:Ir(e),warnings:[],applied:{updates:C}})}},{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",C=x.variant==="light"||x.variant==="dark"?x.variant:"both",T=sa(e,k,C);return Vo({level:T.level,passing:T.checks.length-T.failures.length,total:T.checks.length,checks:T.checks,failures:T.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 Wx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(os(t)):os(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{yu as ADVANCED_TOKENS_SECTION,wr as ALL_ROLES,ol as ALL_TABS,fu as BRAND_PALETTE_SECTION,xu as BUILT_IN_PRESETS,Vf as COLORS_SECTIONS,el as COLOR_FAMILIES,pu as COMPONENTS_SECTIONS,du as COMPONENT_COLOR_SECTIONS,cu as COMPONENT_SHAPE_SECTIONS,uu as CONFIGURE_SECTIONS,Va as CONFIGURE_SUB_GROUPS,oa as CONTRAST_PAIRS,Bi as CSS_NAMED_COLORS,ns as DEVICE_DIMENSIONS,jm as HOME_SUGGESTION_CHIPS,hu as INTERFACE_ROLES_SECTION,Gm as MOCK_BROWSER_CONTENT,Ym as MOCK_WORKSPACE_CONTENT,Nf as PALETTE_SECTION,qm as PREVIEW_STORAGE_ADAPTER,ra as RADIUS_PRESETS,Ba as ROLE_ASSISTANT_MESSAGES,Na as ROLE_BORDERS,Ia as ROLE_FAMILIES,kf as ROLE_FAMILY_LABELS,Pa as ROLE_HEADER,Fa as ROLE_INPUT,ko as ROLE_INTENSITIES,Oa as ROLE_LINKS_FOCUS,Ha as ROLE_PRIMARY_ACTIONS,Da as ROLE_SCROLL_TO_BOTTOM,Ra as ROLE_SURFACES,Wa as ROLE_USER_MESSAGES,_f as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Ri as SHELL_STYLE_ID,bu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,Sg as STYLE_SECTIONS_V2,Ls as THEME_EDITOR_PRESETS,mu as THEME_SECTION,Gi as ThemeEditorState,ql as ZOOM_MAX,zl as ZOOM_MIN,fx as appendPreviewTranscriptEntry,Xl as applySceneConfig,Kl as applyShellTheme,Lr as buildPreviewConfig,yx as buildPreviewConfigWithMessages,jl as buildShellCss,Gl as buildSrcdoc,Ir as buildSummary,gx as buildTranscriptStreamFrames,os as coerceColor,Di as coerceFamily,Fi as coerceIntensity,_i as coerceRadius,Ni as coerceRoundnessStyle,Oi as coerceScheme,Sf as convertFromPx,Cf as convertToPx,Qm as createPreviewMessages,Yl as createPreviewTranscriptEntry,df as createThemeEditorTools,vx as createThemePreview,tl as detectRoleAssignment,Pi as escapeHtml,Tg as findSection,Xi as formatCssValue,Zi as generateColorScale,mx as getPreviewTranscriptPresetLabel,Km as getShellPalette,rl as getThemeEditorPreset,ru as hexToHsl,su as hslToHex,Qi as isValidHex,Es as normalizeColorValue,Af as paletteColorPath,Yi as parseCssValue,Xm as presetStreamsText,ss as quickContrastWarnings,_a as resolveRoleAssignment,au as resolveThemeColorPath,Ji as rgbToHex,sa as runContrastChecks,kg as scopeSection,Tf as tokenRefDisplayName,Vo as toolResult,La as wcagContrastRatio};
|
|
204
|
+
- Resizable panes`});(le=n.onAfterMount)==null||le.call(n,{iframes:$,controllers:[...o]})};for(let xe of $){let j=xe.dataset.mountId;if(!j)continue;let de=P.find(K=>K.mountId===j);de&&(xe.addEventListener("load",()=>{G++,G>=fe&&ge()},{once:!0}),xe.srcdoc=k(j,de.shellMode,hn(de.config),w))}fe===0&&ge()}function L(){var H;if(a)return;let I=pg(n);if(o.length!==I.length){E();return}if(I.some(W=>{let x=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!x||x.dataset.shellMode!==W.shellMode})){E();return}o.forEach((W,x)=>{var w;W.update(I[x].config),((w=n.scene)!=null?w:"conversation")==="minimized"&&W.close()});for(let W of I){let x=e.querySelector(`iframe[data-mount-id="${W.mountId}"]`);x&&Jl(x,W.shellMode)}(H=n.onAfterUpdate)==null||H.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(e)),E(),{update(I){if(a)return;let P=I.device!==void 0&&I.device!==n.device||I.scene!==void 0&&I.scene!==n.scene||I.compareMode!==void 0&&I.compareMode!==n.compareMode||I.widgetCssPath!==void 0&&I.widgetCssPath!==n.widgetCssPath;n={...n,...I},P?E():L()},destroy(){a||(a=!0,C(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},u())},getIframes(){return v()},getScale(){return d},setZoom(I){a||(n={...n,zoom:I},u())}}}function zo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Oi={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"},Bx=/^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 Hx(e){return Bx.test(e)}function cs(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=Oi[t];if(n)return n;let o=Ws(t);if(tl(o)||o==="transparent"||Hx(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(Oi).slice(0,6).join(", ")}).`)}var Ni=Pa.map(e=>e==="gray"?"neutral":e),Dx={...Object.fromEntries(Ni.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function _i(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Dx[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 Vi(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 $i(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 Fx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ui(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Fx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function zi(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=Zi(t);return el(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function qi(e){for(let t of Xr){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 ug=qi("typo-font-family"),ia=qi("typo-font-size"),la=qi("typo-font-weight"),Fi=qi("typo-line-height"),mg={...ug,monospace:ug.mono},gg={...ia,small:ia.sm,md:ia.base,medium:ia.base,large:ia.lg},fg={...la,400:la.normal,500:la.medium,600:la.semibold,700:la.bold},hg={...Fi,"1.25":Fi.tight,"1.5":Fi.normal,"1.625":Fi.relaxed};function bg(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 yg="theme.palette.radius.";function Ox(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Xr)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(yg)&&typeof i=="string"&&(s[a.slice(yg.length)]=i);e[r[1]]=s}return e}var da=Ox(),vg=["sm","md","lg","xl","full"];function Ki(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Ki(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Ki(e,r,n,o+1):null}function ji(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 ds(e){return e.replace(/^role-/,"")}function Nx(e){for(let[t,n]of Object.entries(da))if(vg.every(o=>e[o]===n[o]))return t;return"custom"}function Br(e){var o,r;let t={};for(let s of vg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of Ar)n[ds(s.roleId)]=sl(a=>e.get(`theme.${a}`),s);return{brand:{primary:nc(e.get("theme.palette.colors.primary.500")),secondary:nc(e.get("theme.palette.colors.secondary.500")),accent:nc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:ji(e,"theme.semantic.typography.fontFamily"),fontSize:ji(e,"theme.semantic.typography.fontSize"),fontWeight:ji(e,"theme.semantic.typography.fontWeight"),lineHeight:ji(e,"theme.semantic.typography.lineHeight")},roundness:{style:Nx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function nc(e){return typeof e=="string"&&e!==""?e:null}var ca=[{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 xg(e){let t=new Set(e.targets.map(n=>n.path));return ca.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var _x={AA:4.5,AAA:7};function Vx(e){return Math.round(e*100)/100}function $x(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=Gr.indexOf(a[2]),l=null,m=1/0;return Gr.forEach((p,f)=>{let u=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof u!="string"||!(u.startsWith("#")||u.startsWith("rgb")))&&Ra(u,n)>=o){let C=d>=0?Math.abs(f-d):f;C<m&&(m=C,l=`palette.colors.${i}.${p}`)}}),l}function pa(e,t="AA",n="both",o){let r=_x[t],s=n==="both"?["light","dark"]:[n],a=o?ca.filter(d=>o.includes(d.key)):ca,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let p=Ki(e,m.fg,l),f=Ki(e,m.bg,l);if(!p||!f)continue;let u=Vx(Ra(p,f)),C=u>=r,v={pair:m.key,label:m.label,variant:d,fg:p,bg:f,ratio:u,threshold:r,passes:C};if(!C){let E=$x(e,m.fg,f,r,l);E&&(v.suggestion=E)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function ps(e,t,n="light",o="AA"){return t.length===0?[]:pa(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 un={};for(let e of Ar){let t=ds(e.roleId);un[t]=e,un[e.roleId]=e}Object.assign(un,{surface:un.surfaces,background:un.surfaces,backgrounds:un.surfaces,user:un["user-messages"],"user-message":un["user-messages"],assistant:un["assistant-messages"],"assistant-message":un["assistant-messages"],actions:un["primary-actions"],buttons:un["primary-actions"],composer:un.input,links:un["links-focus"],focus:un["links-focus"],border:un.borders,dividers:un.borders,scroll:un["scroll-to-bottom"]});function Ux(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=un[t];if(!n){let o=Ar.map(r=>ds(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function wg(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of ll)t(n.sections);for(let n of Ua)t(n.sections);return e}var zx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},qx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},oc=["bottom-right","bottom-left","top-right","top-left"],rc=["bubble","flat","minimal"],jx={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Cg(e,t){var W;let n=(W=t==null?void 0:t.editTarget)!=null?W:"both",o=null,r=x=>x&&typeof x=="object"?x:{},s=(x,w,k=n)=>{let S={};return(k==="light"||k==="both")&&(S[`theme.${x}`]=w),(k==="dark"||k==="both")&&(S[`darkTheme.${x}`]=w),S},a=x=>{if(n==="both")return x;let w={};for(let[k,S]of Object.entries(x))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(w[k]=S);return w},i=()=>n==="dark"?"dark":"light",d=(x,w=[])=>zo({ok:!0,summary:Br(e),warnings:w,applied:x});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(x){let{verbosity:w}=r(x),k={summary:Br(e),availableRoles:Ar.map(S=>({role:ds(S.roleId),helper:S.helper})),availableFamilies:Ni,presets:Hs.map(S=>{var A;return{id:S.id,name:S.name,description:S.description,tags:(A=S.tags)!=null?A:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return w==="full"&&(o!=null||(o=wg()),k.fieldIndex=Array.from(o.values()).map(S=>{var A;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(A=S.options)==null?void 0:A.map(N=>N.value)}})),zo(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(x){let w=r(x),k=["primary","secondary","accent"],S={},A={};for(let $ of k){if(w[$]===void 0)continue;let G=cs(w[$]);A[$]=G;let fe=ol(G);for(let ge of Gr){let se=fe[ge];se!==void 0&&Object.assign(S,s(`palette.colors.${$}.${ge}`,se))}}if(Object.keys(A).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let N=ps(e,["primary-button","user-message"],i());return d(A,N)}},{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:Ni},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(x){let w=r(x),k=Ux(w.role),S=_i(w.family,!0),A=Vi(w.intensity),N=a($a(S,A,k)),$=Object.keys(N).length;e.setBatch(N);let G=ps(e,xg(k),i());return d({role:ds(k.roleId),family:S,intensity:A,tokensWritten:$},G)}},{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(x){let w=r(x),k={},S={},A=(N,$)=>{var fe;if(w[N]===void 0)return;let G=bg(w[N],$,N);S[N]=(fe=G.split(".").pop())!=null?fe:G,Object.assign(k,s(`semantic.typography.${N}`,G))};if(A("fontFamily",mg),A("fontSize",gg),A("fontWeight",fg),A("lineHeight",hg),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(x){let w=r(x),k={},S={};if(w.style!==void 0){let A=Ui(w.style);S.style=A;for(let[N,$]of Object.entries(da[A]))Object.assign(k,s(`palette.radius.${N}`,$))}if(w.radius!==void 0){let A=r(w.radius),N={};for(let $ of["sm","md","lg","xl","full"]){if(A[$]===void 0)continue;let G=zi(A[$]);N[$]=G,Object.assign(k,s(`palette.radius.${$}`,G))}S.radius=N}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(x){let w=r(x),k={};if(w.scheme!==void 0){let S=$i(w.scheme);e.set("colorScheme",S),k.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,k.editTarget=S}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return zo({ok:!0,summary:Br(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(x){let{presetId:w}=r(x),k=cl(String(w!=null?w:""));if(!k){let $=Hs.map(G=>G.id).join(", ");throw new Error(`Unknown preset "${w}". Valid presets: ${$}.`)}let S=sn(k.theme,{validate:!1}),A={...e.getConfig()};k.darkTheme&&(A.darkTheme=sn(k.darkTheme,{validate:!1})),k.toolCall&&(A.toolCall=k.toolCall),e.setFullConfig(A,S);let N=ps(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},N)}},{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:oc},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:rc}},additionalProperties:!1}},additionalProperties:!1},execute(x){var $,G,fe;let w=r(x),k={},S={};if(w.launcherPosition!==void 0){let ge=String(w.launcherPosition);if(!oc.includes(ge))throw new Error(`Unknown launcherPosition "${ge}". Valid: ${oc.join(", ")}.`);k["launcher.position"]=ge,S.launcherPosition=ge}let A=r(w.features);for(let[ge,se]of Object.entries(zx))A[ge]!==void 0&&(k[se]=!!A[ge],($=S.features)!=null||(S.features={}),S.features[ge]=!!A[ge]);let N=r(w.layout);for(let[ge,se]of Object.entries(qx))if(N[ge]!==void 0)if(ge==="messageStyle"){let ke=String(N[ge]);if(!rc.includes(ke))throw new Error(`Unknown messageStyle "${ke}". Valid: ${rc.join(", ")}.`);k[se]=ke,(G=S.layout)!=null||(S.layout={}),S.layout[ge]=ke}else k[se]=!!N[ge],(fe=S.layout)!=null||(S.layout={}),S.layout[ge]=!!N[ge];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(x){let w=r(x),k={},S={};for(let[A,N]of Object.entries(jx))w[A]!==void 0&&(k[N]=String(w[A]),S[A]=String(w[A]));if(w.suggestions!==void 0){if(!Array.isArray(w.suggestions))throw new Error("`suggestions` must be an array of strings.");let A=w.suggestions.filter(N=>typeof N=="string");k.suggestionChips=A,S.suggestions=A}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(x){var N;let{updates:w}=r(x);if(!Array.isArray(w)||w.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=wg());let k={},S=[];for(let $ of w){let G=r($),fe=String((N=G.field)!=null?N:"");try{let ge=o.get(fe),se=ge?ge.path:fe;if(!ge&&!/^(theme|darkTheme)\.|\./.test(se))throw new Error(`Unknown field "${fe}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ke=Kx(ge,G.value);if(ge&&se.startsWith("theme.")){let be=s(se.slice(6),ke);Object.assign(k,be),S.push({field:fe,resolvedPath:Object.keys(be),ok:!0})}else k[se]=ke,S.push({field:fe,resolvedPath:se,ok:!0})}catch(ge){S.push({field:fe,ok:!1,error:ge.message})}}let A=S.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),zo({ok:A.length>0,summary:Br(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(x){let w=r(x),k=w.level==="AAA"?"AAA":"AA",S=w.variant==="light"||w.variant==="dark"?w.variant:"both",A=pa(e,k,S);return zo({level:A.level,passing:A.checks.length-A.failures.length,total:A.checks.length,checks:A.checks,failures:A.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(x){let{action:w}=r(x);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 zo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${w}". Valid: undo, redo, reset, export.`)}}}]}function Kx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(cs(t)):cs(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{Tu as ADVANCED_TOKENS_SECTION,Ar as ALL_ROLES,ll as ALL_TABS,wu as BRAND_PALETTE_SECTION,Eu as BUILT_IN_PRESETS,Zg as COLORS_SECTIONS,rl as COLOR_FAMILIES,yu as COMPONENTS_SECTIONS,bu as COMPONENT_COLOR_SECTIONS,hu as COMPONENT_SHAPE_SECTIONS,vu as CONFIGURE_SECTIONS,Ua as CONFIGURE_SUB_GROUPS,ca as CONTRAST_PAIRS,Oi as CSS_NAMED_COLORS,ls as DEVICE_DIMENSIONS,sg as HOME_SUGGESTION_CHIPS,Su as INTERFACE_ROLES_SECTION,ig as MOCK_BROWSER_CONTENT,lg as MOCK_WORKSPACE_CONTENT,Qg as PALETTE_SECTION,rg as PREVIEW_STORAGE_ADAPTER,da as RADIUS_PRESETS,Da as ROLE_ASSISTANT_MESSAGES,Va as ROLE_BORDERS,Pa as ROLE_FAMILIES,Og as ROLE_FAMILY_LABELS,Ba as ROLE_HEADER,Na as ROLE_INPUT,Ro as ROLE_INTENSITIES,_a as ROLE_LINKS_FOCUS,Fa as ROLE_PRIMARY_ACTIONS,Oa as ROLE_SCROLL_TO_BOTTOM,Wa as ROLE_SURFACES,Ha as ROLE_USER_MESSAGES,Jg as SEMANTIC_COLORS_SECTION,Gr as SHADE_KEYS,Hi as SHELL_STYLE_ID,Au as STATUS_COLORS_SECTION,Cu as STATUS_PALETTE_SECTION,Xr as STYLE_SECTIONS,Ff as STYLE_SECTIONS_V2,Hs as THEME_EDITOR_PRESETS,xu as THEME_SECTION,Ji as ThemeEditorState,Xl as ZOOM_MAX,Yl as ZOOM_MIN,Mx as appendPreviewTranscriptEntry,tc as applySceneConfig,Jl as applyShellTheme,Wr as buildPreviewConfig,Px as buildPreviewConfigWithMessages,Ql as buildShellCss,Zl as buildSrcdoc,Br as buildSummary,Lx as buildTranscriptStreamFrames,cs as coerceColor,_i as coerceFamily,Vi as coerceIntensity,zi as coerceRadius,Ui as coerceRoundnessStyle,$i as coerceScheme,Hg as convertFromPx,Bg as convertToPx,dg as createPreviewMessages,ec as createPreviewTranscriptEntry,Cg as createThemeEditorTools,Wx as createThemePreview,sl as detectRoleAssignment,Di as escapeHtml,Nf as findSection,el as formatCssValue,ol as generateColorScale,Ex as getPreviewTranscriptPresetLabel,ag as getShellPalette,cl as getThemeEditorPreset,du as hexToHsl,pu as hslToHex,tl as isValidHex,Ws as normalizeColorValue,Dg as paletteColorPath,Zi as parseCssValue,cg as presetStreamsText,ps as quickContrastWarnings,$a as resolveRoleAssignment,uu as resolveThemeColorPath,nl as rgbToHex,pa as runContrastChecks,_f as scopeSection,Fg as tokenRefDisplayName,zo as toolResult,Ra as wcagContrastRatio};
|