@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.
Files changed (53) hide show
  1. package/README.md +55 -0
  2. package/dist/codegen.cjs +6 -6
  3. package/dist/codegen.js +4 -4
  4. package/dist/index.cjs +47 -47
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +112 -7
  7. package/dist/index.d.ts +112 -7
  8. package/dist/index.global.js +59 -59
  9. package/dist/index.global.js.map +1 -1
  10. package/dist/index.js +47 -47
  11. package/dist/index.js.map +1 -1
  12. package/dist/launcher.global.js +2 -2
  13. package/dist/launcher.global.js.map +1 -1
  14. package/dist/plugin-kit.cjs +1 -0
  15. package/dist/plugin-kit.d.cts +98 -0
  16. package/dist/plugin-kit.d.ts +98 -0
  17. package/dist/plugin-kit.js +1 -0
  18. package/dist/smart-dom-reader.d.cts +107 -4
  19. package/dist/smart-dom-reader.d.ts +107 -4
  20. package/dist/theme-editor.cjs +38 -38
  21. package/dist/theme-editor.d.cts +111 -6
  22. package/dist/theme-editor.d.ts +111 -6
  23. package/dist/theme-editor.js +38 -38
  24. package/dist/theme-reference.cjs +1 -1
  25. package/dist/theme-reference.d.cts +2 -0
  26. package/dist/theme-reference.d.ts +2 -0
  27. package/dist/theme-reference.js +1 -1
  28. package/package.json +8 -2
  29. package/src/components/approval-bubble.test.ts +268 -0
  30. package/src/components/approval-bubble.ts +170 -20
  31. package/src/components/launcher.ts +6 -3
  32. package/src/components/tool-bubble.test.ts +39 -0
  33. package/src/components/tool-bubble.ts +4 -0
  34. package/src/index-core.ts +1 -0
  35. package/src/plugin-kit.test.ts +230 -0
  36. package/src/plugin-kit.ts +294 -0
  37. package/src/plugins/types.ts +49 -2
  38. package/src/session.test.ts +99 -0
  39. package/src/session.ts +14 -3
  40. package/src/theme-editor/preview-utils.test.ts +10 -0
  41. package/src/theme-editor/preview-utils.ts +29 -1
  42. package/src/theme-editor/sections.test.ts +17 -0
  43. package/src/theme-editor/sections.ts +31 -0
  44. package/src/theme-reference.ts +1 -1
  45. package/src/types/theme.ts +2 -0
  46. package/src/types.ts +59 -2
  47. package/src/ui.approval-plugin.test.ts +204 -0
  48. package/src/ui.ts +149 -16
  49. package/src/utils/theme.test.ts +6 -2
  50. package/src/utils/theme.ts +0 -8
  51. package/src/utils/tokens.ts +6 -1
  52. package/src/webmcp-bridge.test.ts +66 -0
  53. package/src/webmcp-bridge.ts +49 -0
@@ -1,18 +1,18 @@
1
- "use strict";var Ff=Object.create;var Qa=Object.defineProperty;var Of=Object.getOwnPropertyDescriptor;var Nf=Object.getOwnPropertyNames;var _f=Object.getPrototypeOf,Vf=Object.prototype.hasOwnProperty;var $f=(e,t)=>{for(var n in t)Qa(e,n,{get:t[n],enumerable:!0})},Su=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Nf(t))!Vf.call(e,r)&&r!==n&&Qa(e,r,{get:()=>t[r],enumerable:!(o=Of(t,r))||o.enumerable});return e};var Au=(e,t,n)=>(n=e!=null?Ff(_f(e)):{},Su(t||!e||!e.__esModule?Qa(n,"default",{value:e,enumerable:!0}):n,e)),Uf=e=>Su(Qa({},"__esModule",{value:!0}),e);var Dy={};$f(Dy,{ADVANCED_TOKENS_SECTION:()=>Ml,ALL_ROLES:()=>rr,ALL_TABS:()=>li,BRAND_PALETTE_SECTION:()=>Al,BUILT_IN_PRESETS:()=>Ll,COLORS_SECTIONS:()=>$u,COLOR_FAMILIES:()=>ai,COMPONENTS_SECTIONS:()=>xl,COMPONENT_COLOR_SECTIONS:()=>vl,COMPONENT_SHAPE_SECTIONS:()=>yl,CONFIGURE_SECTIONS:()=>Cl,CONFIGURE_SUB_GROUPS:()=>Gs,CONTRAST_PAIRS:()=>ds,CSS_NAMED_COLORS:()=>Aa,DEVICE_DIMENSIONS:()=>Hr,HOME_SUGGESTION_CHIPS:()=>bc,INTERFACE_ROLES_SECTION:()=>kl,MOCK_BROWSER_CONTENT:()=>vc,MOCK_WORKSPACE_CONTENT:()=>xc,PALETTE_SECTION:()=>_u,PREVIEW_STORAGE_ADAPTER:()=>hc,RADIUS_PRESETS:()=>ps,ROLE_ASSISTANT_MESSAGES:()=>_s,ROLE_BORDERS:()=>qs,ROLE_FAMILIES:()=>Ds,ROLE_FAMILY_LABELS:()=>Fu,ROLE_HEADER:()=>Os,ROLE_INPUT:()=>Us,ROLE_INTENSITIES:()=>xo,ROLE_LINKS_FOCUS:()=>zs,ROLE_PRIMARY_ACTIONS:()=>Vs,ROLE_SCROLL_TO_BOTTOM:()=>$s,ROLE_SURFACES:()=>Fs,ROLE_USER_MESSAGES:()=>Ns,SEMANTIC_COLORS_SECTION:()=>Vu,SHADE_KEYS:()=>kr,SHELL_STYLE_ID:()=>xa,STATUS_COLORS_SECTION:()=>El,STATUS_PALETTE_SECTION:()=>Tl,STYLE_SECTIONS:()=>Er,STYLE_SECTIONS_V2:()=>Uu,THEME_EDITOR_PRESETS:()=>Qr,THEME_SECTION:()=>Sl,ThemeEditorState:()=>ei,ZOOM_MAX:()=>el,ZOOM_MIN:()=>Zi,appendPreviewTranscriptEntry:()=>Cf,applySceneConfig:()=>sl,applyShellTheme:()=>nl,buildPreviewConfig:()=>dr,buildPreviewConfigWithMessages:()=>Af,buildShellCss:()=>tl,buildSrcdoc:()=>ol,buildSummary:()=>pr,buildTranscriptStreamFrames:()=>Sf,coerceColor:()=>Dr,coerceFamily:()=>Ta,coerceIntensity:()=>ka,coerceRadius:()=>La,coerceRoundnessStyle:()=>Ma,coerceScheme:()=>Ea,convertFromPx:()=>Bu,convertToPx:()=>Wu,createPreviewMessages:()=>Cc,createPreviewTranscriptEntry:()=>rl,createThemeEditorTools:()=>kc,createThemePreview:()=>kf,detectRoleAssignment:()=>ii,escapeHtml:()=>wa,findSection:()=>qu,formatCssValue:()=>ni,generateColorScale:()=>si,getPreviewTranscriptPresetLabel:()=>wf,getShellPalette:()=>yc,getThemeEditorPreset:()=>ci,hexToHsl:()=>gl,hslToHex:()=>hl,isValidHex:()=>oi,normalizeColorValue:()=>Xr,paletteColorPath:()=>Hu,parseCssValue:()=>ti,presetStreamsText:()=>wc,quickContrastWarnings:()=>Fr,resolveRoleAssignment:()=>js,resolveThemeColorPath:()=>bl,rgbToHex:()=>ri,runContrastChecks:()=>ms,scopeSection:()=>ju,tokenRefDisplayName:()=>Du,toolResult:()=>Io,wcagContrastRatio:()=>Hs});module.exports=Uf(Dy);var Tu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Bs(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];Tu(s)&&Tu(r)?n[o]=Bs(s,r):n[o]=r}return n}var lo="min(440px, calc(100vw - 24px))",Ja="440px",At={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:lo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ku(e,t){if(!(!e&&!t))return e?t?Bs(e,t):e:t}function Eu(e){var t,n,o,r,s,a,i,d,l,m,u,g,p,w,S,L,R,I,D,F,B;return e?{...At,...e,theme:ku(At.theme,e.theme),darkTheme:ku(At.darkTheme,e.darkTheme),launcher:{...At.launcher,...e.launcher,dock:{...(t=At.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=At.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...At.copy,...e.copy},sendButton:{...At.sendButton,...e.sendButton},statusIndicator:{...At.statusIndicator,...e.statusIndicator},voiceRecognition:{...At.voiceRecognition,...e.voiceRecognition},features:(()=>{var ye,Ne,xe,J,Ie,X,we,Ae;let v=(ye=At.features)==null?void 0:ye.artifacts,x=(Ne=e.features)==null?void 0:Ne.artifacts,E=(xe=At.features)==null?void 0:xe.scrollToBottom,C=(J=e.features)==null?void 0:J.scrollToBottom,k=(Ie=At.features)==null?void 0:Ie.streamAnimation,O=(X=e.features)==null?void 0:X.streamAnimation,U=(we=At.features)==null?void 0:we.askUserQuestion,K=(Ae=e.features)==null?void 0:Ae.askUserQuestion,fe=v===void 0&&x===void 0?void 0:{...v,...x,layout:{...v==null?void 0:v.layout,...x==null?void 0:x.layout}},ae=E===void 0&&C===void 0?void 0:{...E,...C},ge=k===void 0&&O===void 0?void 0:{...k,...O},le=U===void 0&&K===void 0?void 0:{...U,...K,styles:{...U==null?void 0:U.styles,...K==null?void 0:K.styles}};return{...At.features,...e.features,...ae!==void 0?{scrollToBottom:ae}:{},...fe!==void 0?{artifacts:fe}:{},...ge!==void 0?{streamAnimation:ge}:{},...le!==void 0?{askUserQuestion:le}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:At.suggestionChips,suggestionChipsConfig:{...At.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...At.layout,...e.layout,header:{...(a=At.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=At.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(m=At.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=At.layout)==null?void 0:w.messages)==null?void 0:S.timestamp,...(R=(L=e.layout)==null?void 0:L.messages)==null?void 0:R.timestamp}},slots:{...(I=At.layout)==null?void 0:I.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{...At.markdown,...e.markdown,options:{...(F=At.markdown)==null?void 0:F.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...At.messageActions,...e.messageActions}}:At}var zf={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"}},qf={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"}},jf={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:lo,maxWidth:Ja,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Gr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gr(e,o):o}function Mu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Gr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Kf(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 Lu(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]=Lu(s,r):n[o]=r}return n}function Gf(e,t){return t?Lu(e,t):e}function nn(e,t={}){var r,s,a,i,d,l,m,u,g,p,w,S,L;let n={palette:zf,semantic:qf,components:jf},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,...(L=e==null?void 0:e.semantic)==null?void 0:L.typography}},components:Gf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let R=Kf(o);if(!R.valid)throw new Error(`Theme validation failed: ${R.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let R of t.plugins)o=R.transform(o);return o}function Iu(e){var S,L,R,I,D,F,B,v,x,E,C,k,O,U,K,fe,ae,ge,le,ye,Ne,xe,J,Ie,X,we,Ae,pe,Ce,qe,ne,oe,se,ot,ve,ce,ze,De,de,Y,$e,Mt,ue,ie,In,_t,cn,Fn,Zn,je,V,Ee,Fe,Oe,Ue,pt,rt,Tt,$t,j,Vt,Je,Ot,re,he,wt,Ut,Zt,vn,kt,Ct,ht,yt,qt,tt,On,eo,xn,Nn,mt,So,_n,ur,Rn,Or,Uo,Ro,vt,Vn,$n,wn,Rt,to,no,Un,zo,Po,qo,zn,Bt,Cn,oo,jo,Wo,Ko,Ao,qn,uo,gt,Gt,Yt,jn,Go,ro,mo,Kn;let t=Mu(e),n={};for(let[M,Gn]of Object.entries(t)){let fo=M.replace(/\./g,"-");n[`--persona-${fo}`]=Gn.value}n["--persona-primary"]=(S=n["--persona-semantic-colors-primary"])!=null?S:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(L=n["--persona-semantic-colors-secondary"])!=null?L:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(R=n["--persona-semantic-colors-accent"])!=null?R:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(D=n["--persona-semantic-colors-background"])!=null?D:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(F=n["--persona-semantic-colors-container"])!=null?F:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(B=n["--persona-semantic-colors-text"])!=null?B:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(E=n["--persona-semantic-colors-border"])!=null?E: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"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(U=n["--persona-components-voice-processing-icon"])!=null?U:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(K=n["--persona-components-voice-speaking-icon"])!=null?K: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"]=(ae=n["--persona-components-approval-requested-border"])!=null?ae:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ge=n["--persona-components-approval-requested-text"])!=null?ge:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(le=n["--persona-components-approval-approve-background"])!=null?le:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ye=n["--persona-components-approval-deny-background"])!=null?ye:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Ne=n["--persona-components-attachment-image-background"])!=null?Ne:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(xe=n["--persona-components-attachment-image-border"])!=null?xe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(J=n["--persona-semantic-typography-fontFamily"])!=null?J:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Ie=n["--persona-semantic-typography-fontSize"])!=null?Ie:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(X=n["--persona-semantic-typography-fontWeight"])!=null?X:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(we=n["--persona-semantic-typography-lineHeight"])!=null?we: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"]=(Ae=n["--persona-palette-radius-sm"])!=null?Ae:"0.125rem",n["--persona-radius-md"]=(pe=n["--persona-palette-radius-md"])!=null?pe:"0.375rem",n["--persona-radius-lg"]=(Ce=n["--persona-palette-radius-lg"])!=null?Ce:"0.5rem",n["--persona-radius-xl"]=(qe=n["--persona-palette-radius-xl"])!=null?qe:"0.75rem",n["--persona-radius-full"]=(ne=n["--persona-palette-radius-full"])!=null?ne:"9999px",n["--persona-launcher-radius"]=(se=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?se:"9999px",n["--persona-launcher-bg"]=(ot=n["--persona-components-launcher-background"])!=null?ot:n["--persona-primary"],n["--persona-launcher-fg"]=(ve=n["--persona-components-launcher-foreground"])!=null?ve:n["--persona-text-inverse"],n["--persona-launcher-border"]=(ce=n["--persona-components-launcher-border"])!=null?ce:n["--persona-border"],n["--persona-button-primary-bg"]=(ze=n["--persona-components-button-primary-background"])!=null?ze:n["--persona-primary"],n["--persona-button-primary-fg"]=(De=n["--persona-components-button-primary-foreground"])!=null?De:n["--persona-text-inverse"],n["--persona-button-radius"]=(Y=(de=n["--persona-components-button-primary-borderRadius"])!=null?de:n["--persona-palette-radius-full"])!=null?Y:"9999px",n["--persona-panel-radius"]=(Mt=($e=n["--persona-components-panel-borderRadius"])!=null?$e:n["--persona-radius-xl"])!=null?Mt:"0.75rem",n["--persona-panel-border"]=(ue=n["--persona-components-panel-border"])!=null?ue:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(In=(ie=n["--persona-components-panel-shadow"])!=null?ie:n["--persona-palette-shadows-xl"])!=null?In:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(cn=(_t=n["--persona-components-input-borderRadius"])!=null?_t:n["--persona-radius-lg"])!=null?cn:"0.5rem",n["--persona-message-user-radius"]=(Zn=(Fn=n["--persona-components-message-user-borderRadius"])!=null?Fn:n["--persona-radius-lg"])!=null?Zn:"0.5rem",n["--persona-message-assistant-radius"]=(V=(je=n["--persona-components-message-assistant-borderRadius"])!=null?je:n["--persona-radius-lg"])!=null?V:"0.5rem",n["--persona-header-bg"]=(Ee=n["--persona-components-header-background"])!=null?Ee:n["--persona-surface"],n["--persona-header-border"]=(Fe=n["--persona-components-header-border"])!=null?Fe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Oe=n["--persona-components-header-iconBackground"])!=null?Oe:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ue=n["--persona-components-header-iconForeground"])!=null?Ue:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(pt=n["--persona-components-header-titleForeground"])!=null?pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(rt=n["--persona-components-header-subtitleForeground"])!=null?rt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Tt=n["--persona-components-header-actionIconForeground"])!=null?Tt:n["--persona-muted"];let o=($t=e.components)==null?void 0:$t.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(j=e.components)==null?void 0:j.introCard;n["--persona-intro-card-bg"]=(Vt=n["--persona-components-introCard-background"])!=null?Vt:n["--persona-surface"],n["--persona-intro-card-radius"]=(Je=n["--persona-components-introCard-borderRadius"])!=null?Je:"1rem",n["--persona-intro-card-padding"]=(Ot=n["--persona-components-introCard-padding"])!=null?Ot:"1.5rem",n["--persona-intro-card-shadow"]=(he=(re=r==null?void 0:r.shadow)!=null?re:n["--persona-components-introCard-shadow"])!=null?he:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(wt=n["--persona-components-input-background"])!=null?wt:n["--persona-surface"],n["--persona-input-placeholder"]=(Ut=n["--persona-components-input-placeholder"])!=null?Ut:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Zt=n["--persona-components-message-user-background"])!=null?Zt:n["--persona-accent"],n["--persona-message-user-text"]=(vn=n["--persona-components-message-user-text"])!=null?vn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(kt=n["--persona-components-message-user-shadow"])!=null?kt:"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"]=(ht=n["--persona-components-message-assistant-text"])!=null?ht:n["--persona-text"],n["--persona-message-assistant-border"]=(yt=n["--persona-components-message-assistant-border"])!=null?yt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(qt=n["--persona-components-message-assistant-shadow"])!=null?qt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(On=(tt=n["--persona-components-scrollToBottom-background"])!=null?tt:n["--persona-button-primary-bg"])!=null?On:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(xn=(eo=n["--persona-components-scrollToBottom-foreground"])!=null?eo:n["--persona-button-primary-fg"])!=null?xn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Nn=n["--persona-components-scrollToBottom-border"])!=null?Nn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(mt=n["--persona-components-scrollToBottom-size"])!=null?mt:"40px",n["--persona-scroll-to-bottom-radius"]=(ur=(_n=(So=n["--persona-components-scrollToBottom-borderRadius"])!=null?So:n["--persona-button-radius"])!=null?_n:n["--persona-radius-full"])!=null?ur:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Or=(Rn=n["--persona-components-scrollToBottom-shadow"])!=null?Rn:n["--persona-palette-shadows-sm"])!=null?Or:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Uo=n["--persona-components-scrollToBottom-padding"])!=null?Uo:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Ro=n["--persona-components-scrollToBottom-gap"])!=null?Ro:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Vn=(vt=n["--persona-components-scrollToBottom-fontSize"])!=null?vt:n["--persona-palette-typography-fontSize-sm"])!=null?Vn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($n=n["--persona-components-scrollToBottom-iconSize"])!=null?$n:"14px",n["--persona-tool-bubble-shadow"]=(wn=n["--persona-components-toolBubble-shadow"])!=null?wn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Rt=n["--persona-components-reasoningBubble-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(to=n["--persona-components-composer-shadow"])!=null?to:"none",n["--persona-md-inline-code-bg"]=(no=n["--persona-components-markdown-inlineCode-background"])!=null?no:n["--persona-container"],n["--persona-md-inline-code-color"]=(Un=n["--persona-components-markdown-inlineCode-foreground"])!=null?Un:n["--persona-text"],n["--persona-md-link-color"]=(Po=(zo=n["--persona-components-markdown-link-foreground"])!=null?zo:n["--persona-accent"])!=null?Po:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(qo=n["--persona-components-markdown-codeBlock-background"])!=null?qo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(zn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?zn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Bt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Bt:"inherit",n["--persona-md-table-header-bg"]=(Cn=n["--persona-components-markdown-table-headerBackground"])!=null?Cn:n["--persona-container"],n["--persona-md-table-border-color"]=(oo=n["--persona-components-markdown-table-borderColor"])!=null?oo:n["--persona-border"],n["--persona-md-hr-color"]=(jo=n["--persona-components-markdown-hr-color"])!=null?jo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Wo=n["--persona-components-markdown-blockquote-borderColor"])!=null?Wo:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Ko=n["--persona-components-markdown-blockquote-background"])!=null?Ko:"transparent",n["--persona-md-blockquote-text-color"]=(Ao=n["--persona-components-markdown-blockquote-textColor"])!=null?Ao:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(qn=n["--persona-components-collapsibleWidget-container"])!=null?qn:n["--persona-surface"],n["--cw-surface"]=(uo=n["--persona-components-collapsibleWidget-surface"])!=null?uo:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Gt=n["--persona-components-message-border"])!=null?Gt: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 M=w.toolbar;M.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=M.iconHoverColor),M.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=M.iconHoverBackground),M.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=M.iconPadding),M.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=M.iconBorderRadius),M.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=M.iconBorder),M.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=M.toggleGroupGap),M.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=M.toggleBorderRadius),M.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=M.copyBackground),M.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=M.copyBorder),M.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=M.copyColor),M.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=M.copyBorderRadius),M.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=M.copyPadding),M.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=M.copyMenuBackground,n["--persona-dropdown-bg"]=(Yt=n["--persona-dropdown-bg"])!=null?Yt:M.copyMenuBackground),M.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=M.copyMenuBorder,n["--persona-dropdown-border"]=(jn=n["--persona-dropdown-border"])!=null?jn:M.copyMenuBorder),M.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=M.copyMenuShadow,n["--persona-dropdown-shadow"]=(Go=n["--persona-dropdown-shadow"])!=null?Go:M.copyMenuShadow),M.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=M.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ro=n["--persona-dropdown-radius"])!=null?ro:M.copyMenuBorderRadius),M.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=M.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(mo=n["--persona-dropdown-item-hover-bg"])!=null?mo:M.copyMenuItemHoverBackground),M.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=M.iconBackground),M.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=M.toolbarBorder)}if(w!=null&&w.tab){let M=w.tab;M.background&&(n["--persona-artifact-tab-bg"]=M.background),M.activeBackground&&(n["--persona-artifact-tab-active-bg"]=M.activeBackground),M.activeBorder&&(n["--persona-artifact-tab-active-border"]=M.activeBorder),M.borderRadius&&(n["--persona-artifact-tab-radius"]=M.borderRadius),M.textColor&&(n["--persona-artifact-tab-color"]=M.textColor),M.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=M.hoverBackground),M.listBackground&&(n["--persona-artifact-tab-list-bg"]=M.listBackground),M.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=M.listBorderColor),M.listPadding&&(n["--persona-artifact-tab-list-padding"]=M.listPadding)}if(w!=null&&w.pane){let M=w.pane;if(M.toolbarBackground){let Gn=(Kn=Gr(e,M.toolbarBackground))!=null?Kn:M.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Gn}}return n}var Yf={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"}}},Ru=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ml=()=>{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"},Xf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ml()},Qf=e=>Xf(e),Jf=e=>nn(e),Zf=e=>{var n;let t=nn(void 0,{validate:!1});return nn({...e,palette:{...t.palette,colors:{...Yf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Za=e=>{let t=Qf(e),n=Ru(e==null?void 0:e.theme),o=Ru(e==null?void 0:e.darkTheme);return t==="dark"?Zf(Bs(n!=null?n:{},o!=null?o:{})):Jf(n)},eg=e=>Iu(e),Yr=(e,t)=>{var s;let n=Za(t),o=eg(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)},Pu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ml())});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(ml());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 fl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Tr(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]:Tr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var ei=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?{...At,...n}:n!=null?n:At,this.theme=nn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?fl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?fl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):fl(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=Tr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:nn();this.config={...this.config,darkTheme:Tr(s,r,n)}}else this.config=Tr(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=Tr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:nn();this.config={...this.config,darkTheme:Tr(l,d,i)},o=!0}else this.config=Tr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=nn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=nn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...At},this.theme=nn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=nn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function ti(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 ni(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Wu(e,t){return t==="rem"?e*16:e}function Bu(e,t){return t==="rem"?e/16:e}function Xr(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function oi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function ri(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 Hs(e,t){let n=s=>{var l;let a=Xr(s),i=a.startsWith("rgb")?(l=ri(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 gl(e){var g;let t=Xr(e),n=t.startsWith("rgb")?(g=ri(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 hl(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 si(e){let{h:t,s:n,l:o}=gl(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]=hl(t,l,d)}return a}var kr=["50","100","200","300","400","500","600","700","800","900","950"],ai=["primary","secondary","accent","gray","success","warning","error","info"];function Hu(e,t){return`palette.colors.${e}.${t}`}function bl(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.")?bl(e,`theme.${o}`,n+1):"#cbd5e1"}function Du(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var xo=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ds=["primary","secondary","accent","gray"],Fu={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Fs={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:xo,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Os={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:xo,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Ns={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:xo,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},_s={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:xo,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Vs={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:xo,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},$s={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:xo,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Us={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:xo,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},zs={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:xo,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},qs={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:xo,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},rr=[Fs,Os,Ns,_s,Vs,$s,Us,zs,qs];function js(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=tg(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 tg(e,t,n,o){let r=t==="solid";if(o==="role-header")return ng(e,r,n);if(o==="role-input")return og(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 ng(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 og(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 rg=/^palette\.colors\.(\w+)\.(\d+)$/;function ii(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(rg);if(!r)return null;let s=r[1],a=Ds.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=js(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 sg={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"}]}]},ag={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},ig={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},lg={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)"}]}]},cg={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"}]}]},dg={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"}}]},pg={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)"}]},ug={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"}]}]},Er=[ag,ig,cg,lg,sg,dg,pg,ug];function Ou(){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:ai.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 Nu={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"}}]},_u=Ou(),Vu=Nu,$u=[Ou(),Nu],mg={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:lo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ja},{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"}]}]},fg={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"}]}]},gg={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"}]}]},hg={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"}]}]},bg={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"}]}]},yg={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"}}]},vg={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"}}]},xg={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"}}]},wg={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"}}]},Cg={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"}]},yl=[mg,fg,gg,hg,bg],vl=[yg,vg,xg,wg,Cg],xl=[...yl,...vl],wl=1024*1024,Sg=["What can you help me with?","Tell me about your features","How does this work?"],Ks={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 Ag(e){return Number(e)*wl}function Tg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/wl)):String(t):"10"}function kg(e){var t;return(t=Ks[String(e)])!=null?t:Ks.images}function Eg(e){let t=Array.isArray(e)?e:Ks.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Ks)){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 Mg={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"}]},Lg={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:Sg}]},Ig={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:""}]},Rg={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}]},Pg={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"}]}]},Wg={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"}]}]},Bg={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:lo},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},Hg={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:""}]},Dg={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"}]},Fg={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"}]},Og={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"}]},Ng={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"}]},_g={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:""}]},Vg={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)}]},$g={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*wl,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:Tg,parseValue:Ag},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Ks.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:Eg,parseValue:kg}]},Ug={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"}]}]},zg={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}]},qg={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"}]}]},jg={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}]},Kg={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}]},Gs=[{label:"Content",sections:[Mg,Lg]},{label:"Layout",sections:[Ig,Rg,Pg,Wg]},{label:"Widget",sections:[Bg,Hg,Dg,Fg,Og,Ng]},{label:"Features",sections:[_g,Vg,$g,Ug,zg]},{label:"Developer",collapsedByDefault:!0,sections:[qg,jg,Kg]}],Cl=Gs.flatMap(e=>e.sections),Sl={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"}]}]},Al={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"}]},Tl={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"}]},kl={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:Fs},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Os},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ns},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:_s},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Vs},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:$s},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Us},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:zs},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:qs}]},El={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"}}]},Ml={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Uu=[Sl,Al,Tl,kl,El,Ml],li=[{id:"style",label:"Style",sections:Er},{id:"design-system",label:"Design System",sections:xl},{id:"configure",label:"Configure",sections:Cl}];function zu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Gg(e,t,n){return{...e,id:`${n}-${e.id}`,path:zu(e.path,t)}}function qu(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function ju(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=>Gg(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])=>[zu(d,t),l]))}))}}var Ll=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Qr=[...Ll];function ci(e){return Qr.find(t=>t.id===e)}var Ku=require("marked"),Yg=e=>{if(e)return e},Il=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Ku.Marked({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=Yg(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},di=e=>e?Il({markedOptions:e.options,renderer:e.renderer}):Il(),ov=Il();var Ys=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Gu=Au(require("dompurify"),1),Xg={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"]},Qg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Jg=()=>{let e=(0,Gu.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Qg.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Xg)},pi=e=>e===!1?null:typeof e=="function"?e:Jg();var Rl="webmcp:",ui={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Xu(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}:${Zg(t.join(""))}`}function Yu(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 Zg(e){let t=Yu(e,0).toString(36),n=Yu(e,2654435761).toString(36);return`${t}.${n}`}var mi=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 ui.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=nh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return wo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let p=typeof document!="undefined"&&!!document.modelContext;return wo(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=eh(t),a;try{a=await r.getTools()}catch(p){let w=p instanceof Error?p.message:String(p);return wo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(p=>p.name===s);if(!i)return wo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return wo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return wo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return wo("User declined the tool call.");if(o!=null&&o.aborted)return wo("Aborted by cancel()");let l=new AbortController,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,ah(n),{signal:l.signal});return oh(p)}catch(p){if(m)return wo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return wo("Aborted by cancel()");let w=p instanceof Error?p.message:String(p);return wo(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){ui.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,ui.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:rh;try{return await n(t)}catch(r){return ui.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=>th(t,o))}},eh=e=>e.startsWith(Rl)?e.slice(Rl.length):e,Jr=e=>e.startsWith(Rl),th=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},nh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},oh=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:ih(t)}]}},wo=e=>({isError:!0,content:[{type:"text",text:e}]}),rh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=sh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var Yg=Object.create;var Za=Object.defineProperty;var Xg=Object.getOwnPropertyDescriptor;var Qg=Object.getOwnPropertyNames;var Jg=Object.getPrototypeOf,Zg=Object.prototype.hasOwnProperty;var ef=(e,t)=>{for(var n in t)Za(e,n,{get:t[n],enumerable:!0})},Lu=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Qg(t))!Zg.call(e,r)&&r!==n&&Za(e,r,{get:()=>t[r],enumerable:!(o=Xg(t,r))||o.enumerable});return e};var Iu=(e,t,n)=>(n=e!=null?Yg(Jg(e)):{},Lu(t||!e||!e.__esModule?Za(n,"default",{value:e,enumerable:!0}):n,e)),tf=e=>Lu(Za({},"__esModule",{value:!0}),e);var Xy={};ef(Xy,{ADVANCED_TOKENS_SECTION:()=>Wl,ALL_ROLES:()=>ir,ALL_TABS:()=>di,BRAND_PALETTE_SECTION:()=>Ll,BUILT_IN_PRESETS:()=>Bl,COLORS_SECTIONS:()=>Yu,COLOR_FAMILIES:()=>li,COMPONENTS_SECTIONS:()=>Tl,COMPONENT_COLOR_SECTIONS:()=>Al,COMPONENT_SHAPE_SECTIONS:()=>Sl,CONFIGURE_SECTIONS:()=>El,CONFIGURE_SUB_GROUPS:()=>ea,CONTRAST_PAIRS:()=>hs,CSS_NAMED_COLORS:()=>Ia,DEVICE_DIMENSIONS:()=>Nr,HOME_SUGGESTION_CHIPS:()=>Cc,INTERFACE_ROLES_SECTION:()=>Rl,MOCK_BROWSER_CONTENT:()=>Ac,MOCK_WORKSPACE_CONTENT:()=>Tc,PALETTE_SECTION:()=>Ku,PREVIEW_STORAGE_ADAPTER:()=>wc,RADIUS_PRESETS:()=>bs,ROLE_ASSISTANT_MESSAGES:()=>js,ROLE_BORDERS:()=>Qs,ROLE_FAMILIES:()=>$s,ROLE_FAMILY_LABELS:()=>Uu,ROLE_HEADER:()=>zs,ROLE_INPUT:()=>Ys,ROLE_INTENSITIES:()=>ko,ROLE_LINKS_FOCUS:()=>Xs,ROLE_PRIMARY_ACTIONS:()=>Ks,ROLE_SCROLL_TO_BOTTOM:()=>Gs,ROLE_SURFACES:()=>Us,ROLE_USER_MESSAGES:()=>qs,SEMANTIC_COLORS_SECTION:()=>Gu,SHADE_KEYS:()=>Lr,SHELL_STYLE_ID:()=>ka,STATUS_COLORS_SECTION:()=>Pl,STATUS_PALETTE_SECTION:()=>Il,STYLE_SECTIONS:()=>Ir,STYLE_SECTIONS_V2:()=>Xu,THEME_EDITOR_PRESETS:()=>os,THEME_SECTION:()=>Ml,ThemeEditorState:()=>ni,ZOOM_MAX:()=>rl,ZOOM_MIN:()=>ol,appendPreviewTranscriptEntry:()=>Bg,applySceneConfig:()=>cl,applyShellTheme:()=>al,buildPreviewConfig:()=>mr,buildPreviewConfigWithMessages:()=>Dg,buildShellCss:()=>sl,buildSrcdoc:()=>il,buildSummary:()=>gr,buildTranscriptStreamFrames:()=>Hg,coerceColor:()=>_r,coerceFamily:()=>Ra,coerceIntensity:()=>Pa,coerceRadius:()=>Ha,coerceRoundnessStyle:()=>Ba,coerceScheme:()=>Wa,convertFromPx:()=>_u,convertToPx:()=>Nu,createPreviewMessages:()=>Ec,createPreviewTranscriptEntry:()=>ll,createThemeEditorTools:()=>Rc,createThemePreview:()=>Og,detectRoleAssignment:()=>ci,escapeHtml:()=>Ea,findSection:()=>Ju,formatCssValue:()=>ri,generateColorScale:()=>ii,getPreviewTranscriptPresetLabel:()=>Wg,getShellPalette:()=>Sc,getThemeEditorPreset:()=>pi,hexToHsl:()=>vl,hslToHex:()=>xl,isValidHex:()=>si,normalizeColorValue:()=>ts,paletteColorPath:()=>Vu,parseCssValue:()=>oi,presetStreamsText:()=>kc,quickContrastWarnings:()=>Vr,resolveRoleAssignment:()=>Js,resolveThemeColorPath:()=>wl,rgbToHex:()=>ai,runContrastChecks:()=>vs,scopeSection:()=>Zu,tokenRefDisplayName:()=>$u,toolResult:()=>Ho,wcagContrastRatio:()=>Vs});module.exports=tf(Xy);var Ru=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function _s(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];Ru(s)&&Ru(r)?n[o]=_s(s,r):n[o]=r}return n}var fo="min(440px, calc(100vw - 24px))",ei="440px",Rt={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:fo,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 Pu(e,t){if(!(!e&&!t))return e?t?_s(e,t):e:t}function Wu(e){var t,n,o,r,s,a,i,d,l,m,p,f,u,C,v,M,I,R,W,D,B;return e?{...Rt,...e,theme:Pu(Rt.theme,e.theme),darkTheme:Pu(Rt.darkTheme,e.darkTheme),launcher:{...Rt.launcher,...e.launcher,dock:{...(t=Rt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Rt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Rt.copy,...e.copy},sendButton:{...Rt.sendButton,...e.sendButton},statusIndicator:{...Rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Rt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ye,Oe,we,K,pe,G,ve,ce;let x=(ye=Rt.features)==null?void 0:ye.artifacts,w=(Oe=e.features)==null?void 0:Oe.artifacts,E=(we=Rt.features)==null?void 0:we.scrollToBottom,S=(K=e.features)==null?void 0:K.scrollToBottom,T=(pe=Rt.features)==null?void 0:pe.streamAnimation,_=(G=e.features)==null?void 0:G.streamAnimation,U=(ve=Rt.features)==null?void 0:ve.askUserQuestion,Y=(ce=e.features)==null?void 0:ce.askUserQuestion,he=x===void 0&&w===void 0?void 0:{...x,...w,layout:{...x==null?void 0:x.layout,...w==null?void 0:w.layout}},fe=E===void 0&&S===void 0?void 0:{...E,...S},ae=T===void 0&&_===void 0?void 0:{...T,..._},Ee=U===void 0&&Y===void 0?void 0:{...U,...Y,styles:{...U==null?void 0:U.styles,...Y==null?void 0:Y.styles}};return{...Rt.features,...e.features,...fe!==void 0?{scrollToBottom:fe}:{},...he!==void 0?{artifacts:he}:{},...ae!==void 0?{streamAnimation:ae}:{},...Ee!==void 0?{askUserQuestion:Ee}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Rt.suggestionChips,suggestionChipsConfig:{...Rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Rt.layout,...e.layout,header:{...(a=Rt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Rt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(m=Rt.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=Rt.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(R=Rt.layout)==null?void 0:R.slots,...(W=e.layout)==null?void 0:W.slots}},markdown:{...Rt.markdown,...e.markdown,options:{...(D=Rt.markdown)==null?void 0:D.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...Rt.messageActions,...e.messageActions}}:Rt}var nf={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"}},of={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"}},rf={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:fo,maxWidth:ei,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 Zr(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."))?Zr(e,o):o}function Bu(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=Zr(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 sf(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 Hu(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]=Hu(s,r):n[o]=r}return n}function af(e,t){return t?Hu(e,t):e}function an(e,t={}){var r,s,a,i,d,l,m,p,f,u,C,v,M;let n={palette:nf,semantic:of,components:rf},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,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:af(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=sf(o);if(!I.valid)throw new Error(`Theme validation failed: ${I.errors.map(R=>R.message).join(", ")}`)}if(t.plugins)for(let I of t.plugins)o=I.transform(o);return o}function Du(e){var v,M,I,R,W,D,B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we,K,pe,G,ve,ce,ne,Se,ze,te,re,ie,st,Te,ue,Ue,Be,me,Q,_e,Ht,be,de,Pn,Ut,gn,Fn,to,qe,V,Le,He,De,Ve,mt,at,Pt,jt,j,zt,Ze,Vt,se,Ce,kt,Kt,tn,An,Wt,Mt,wt,St,Gt,ot,On,no,Tn,Nn,bt,Lo,_n,fr,Wn,$r,jo,Do,At,Vn,$n,kn,Lt,oo,ro,Un,Ko,Fo,Go,zn,Ft,En,so,Yo,Oo,Xo,Io,qn,yo,vt,Xt,Qt,jn,Qo,ao,vo,Kn,$,io;let t=Bu(e),n={};for(let[xe,Gn]of Object.entries(t)){let lo=xe.replace(/\./g,"-");n[`--persona-${lo}`]=Gn.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(I=n["--persona-semantic-colors-accent"])!=null?I:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(R=n["--persona-semantic-colors-surface"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(W=n["--persona-semantic-colors-background"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(B=n["--persona-semantic-colors-text"])!=null?B:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(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"]=(E=n["--persona-semantic-colors-border"])!=null?E:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(T=n["--persona-components-voice-recording-indicator"])!=null?T:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(_=n["--persona-components-voice-recording-background"])!=null?_:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(U=n["--persona-components-voice-processing-icon"])!=null?U:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Y=n["--persona-components-voice-speaking-icon"])!=null?Y:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(he=n["--persona-components-approval-requested-background"])!=null?he:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(fe=n["--persona-components-approval-requested-border"])!=null?fe:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ae=n["--persona-components-approval-requested-text"])!=null?ae:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Ee=n["--persona-components-approval-requested-shadow"])!=null?Ee:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(ye=n["--persona-components-approval-approve-background"])!=null?ye:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Oe=n["--persona-components-approval-deny-background"])!=null?Oe:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(we=n["--persona-components-attachment-image-background"])!=null?we:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(K=n["--persona-components-attachment-image-border"])!=null?K:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(pe=n["--persona-semantic-typography-fontFamily"])!=null?pe:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(G=n["--persona-semantic-typography-fontSize"])!=null?G:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ve=n["--persona-semantic-typography-fontWeight"])!=null?ve:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ce=n["--persona-semantic-typography-lineHeight"])!=null?ce:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(ne=n["--persona-palette-radius-sm"])!=null?ne:"0.125rem",n["--persona-radius-md"]=(Se=n["--persona-palette-radius-md"])!=null?Se:"0.375rem",n["--persona-radius-lg"]=(ze=n["--persona-palette-radius-lg"])!=null?ze:"0.5rem",n["--persona-radius-xl"]=(te=n["--persona-palette-radius-xl"])!=null?te:"0.75rem",n["--persona-radius-full"]=(re=n["--persona-palette-radius-full"])!=null?re:"9999px",n["--persona-launcher-radius"]=(st=(ie=n["--persona-components-launcher-borderRadius"])!=null?ie:n["--persona-palette-radius-full"])!=null?st:"9999px",n["--persona-launcher-bg"]=(Te=n["--persona-components-launcher-background"])!=null?Te:n["--persona-primary"],n["--persona-launcher-fg"]=(ue=n["--persona-components-launcher-foreground"])!=null?ue:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ue=n["--persona-components-launcher-border"])!=null?Ue:n["--persona-border"],n["--persona-button-primary-bg"]=(Be=n["--persona-components-button-primary-background"])!=null?Be:n["--persona-primary"],n["--persona-button-primary-fg"]=(me=n["--persona-components-button-primary-foreground"])!=null?me:n["--persona-text-inverse"],n["--persona-button-radius"]=(_e=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?_e:"9999px",n["--persona-panel-radius"]=(be=(Ht=n["--persona-components-panel-borderRadius"])!=null?Ht:n["--persona-radius-xl"])!=null?be:"0.75rem",n["--persona-panel-border"]=(de=n["--persona-components-panel-border"])!=null?de:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ut=(Pn=n["--persona-components-panel-shadow"])!=null?Pn:n["--persona-palette-shadows-xl"])!=null?Ut:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(gn=n["--persona-components-launcher-shadow"])!=null?gn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(to=(Fn=n["--persona-components-input-borderRadius"])!=null?Fn:n["--persona-radius-lg"])!=null?to:"0.5rem",n["--persona-message-user-radius"]=(V=(qe=n["--persona-components-message-user-borderRadius"])!=null?qe:n["--persona-radius-lg"])!=null?V:"0.5rem",n["--persona-message-assistant-radius"]=(He=(Le=n["--persona-components-message-assistant-borderRadius"])!=null?Le:n["--persona-radius-lg"])!=null?He:"0.5rem",n["--persona-header-bg"]=(De=n["--persona-components-header-background"])!=null?De:n["--persona-surface"],n["--persona-header-border"]=(Ve=n["--persona-components-header-border"])!=null?Ve:n["--persona-divider"],n["--persona-header-icon-bg"]=(mt=n["--persona-components-header-iconBackground"])!=null?mt:n["--persona-primary"],n["--persona-header-icon-fg"]=(at=n["--persona-components-header-iconForeground"])!=null?at:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pt=n["--persona-components-header-titleForeground"])!=null?Pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(jt=n["--persona-components-header-subtitleForeground"])!=null?jt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(j=n["--persona-components-header-actionIconForeground"])!=null?j:n["--persona-muted"];let o=(zt=e.components)==null?void 0:zt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(Ze=e.components)==null?void 0:Ze.introCard;n["--persona-intro-card-bg"]=(Vt=n["--persona-components-introCard-background"])!=null?Vt:n["--persona-surface"],n["--persona-intro-card-radius"]=(se=n["--persona-components-introCard-borderRadius"])!=null?se:"1rem",n["--persona-intro-card-padding"]=(Ce=n["--persona-components-introCard-padding"])!=null?Ce:"1.5rem",n["--persona-intro-card-shadow"]=(Kt=(kt=r==null?void 0:r.shadow)!=null?kt:n["--persona-components-introCard-shadow"])!=null?Kt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(tn=n["--persona-components-input-background"])!=null?tn:n["--persona-surface"],n["--persona-input-placeholder"]=(An=n["--persona-components-input-placeholder"])!=null?An:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Wt=n["--persona-components-message-user-background"])!=null?Wt:n["--persona-accent"],n["--persona-message-user-text"]=(Mt=n["--persona-components-message-user-text"])!=null?Mt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(wt=n["--persona-components-message-user-shadow"])!=null?wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(St=n["--persona-components-message-assistant-background"])!=null?St: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"]=(ot=n["--persona-components-message-assistant-border"])!=null?ot:n["--persona-border"],n["--persona-message-assistant-shadow"]=(On=n["--persona-components-message-assistant-shadow"])!=null?On:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Tn=(no=n["--persona-components-scrollToBottom-background"])!=null?no:n["--persona-button-primary-bg"])!=null?Tn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bt=(Nn=n["--persona-components-scrollToBottom-foreground"])!=null?Nn:n["--persona-button-primary-fg"])!=null?bt:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Lo=n["--persona-components-scrollToBottom-border"])!=null?Lo:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(_n=n["--persona-components-scrollToBottom-size"])!=null?_n:"40px",n["--persona-scroll-to-bottom-radius"]=($r=(Wn=(fr=n["--persona-components-scrollToBottom-borderRadius"])!=null?fr:n["--persona-button-radius"])!=null?Wn:n["--persona-radius-full"])!=null?$r:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Do=(jo=n["--persona-components-scrollToBottom-shadow"])!=null?jo:n["--persona-palette-shadows-sm"])!=null?Do:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(At=n["--persona-components-scrollToBottom-padding"])!=null?At:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Vn=n["--persona-components-scrollToBottom-gap"])!=null?Vn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(kn=($n=n["--persona-components-scrollToBottom-fontSize"])!=null?$n:n["--persona-palette-typography-fontSize-sm"])!=null?kn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Lt=n["--persona-components-scrollToBottom-iconSize"])!=null?Lt:"14px",n["--persona-tool-bubble-shadow"]=(oo=n["--persona-components-toolBubble-shadow"])!=null?oo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(ro=n["--persona-components-reasoningBubble-shadow"])!=null?ro:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Un=n["--persona-components-composer-shadow"])!=null?Un:"none",n["--persona-md-inline-code-bg"]=(Ko=n["--persona-components-markdown-inlineCode-background"])!=null?Ko:n["--persona-container"],n["--persona-md-inline-code-color"]=(Fo=n["--persona-components-markdown-inlineCode-foreground"])!=null?Fo:n["--persona-text"],n["--persona-md-link-color"]=(zn=(Go=n["--persona-components-markdown-link-foreground"])!=null?Go:n["--persona-accent"])!=null?zn:"#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"]=(Ft=n["--persona-components-markdown-codeBlock-background"])!=null?Ft:n["--persona-container"],n["--persona-md-code-block-border-color"]=(En=n["--persona-components-markdown-codeBlock-borderColor"])!=null?En:n["--persona-border"],n["--persona-md-code-block-text-color"]=(so=n["--persona-components-markdown-codeBlock-textColor"])!=null?so:"inherit",n["--persona-md-table-header-bg"]=(Yo=n["--persona-components-markdown-table-headerBackground"])!=null?Yo:n["--persona-container"],n["--persona-md-table-border-color"]=(Oo=n["--persona-components-markdown-table-borderColor"])!=null?Oo:n["--persona-border"],n["--persona-md-hr-color"]=(Xo=n["--persona-components-markdown-hr-color"])!=null?Xo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Io=n["--persona-components-markdown-blockquote-borderColor"])!=null?Io:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(qn=n["--persona-components-markdown-blockquote-background"])!=null?qn:"transparent",n["--persona-md-blockquote-text-color"]=(yo=n["--persona-components-markdown-blockquote-textColor"])!=null?yo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(vt=n["--persona-components-collapsibleWidget-container"])!=null?vt:n["--persona-surface"],n["--cw-surface"]=(Xt=n["--persona-components-collapsibleWidget-surface"])!=null?Xt:n["--persona-surface"],n["--cw-border"]=(Qt=n["--persona-components-collapsibleWidget-border"])!=null?Qt:n["--persona-border"],n["--persona-message-border"]=(jn=n["--persona-components-message-border"])!=null?jn: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 xe=C.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(Qo=n["--persona-dropdown-bg"])!=null?Qo:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(ao=n["--persona-dropdown-border"])!=null?ao:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(vo=n["--persona-dropdown-shadow"])!=null?vo:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=($=n["--persona-dropdown-item-hover-bg"])!=null?$:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(C!=null&&C.tab){let xe=C.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(C!=null&&C.pane){let xe=C.pane;if(xe.toolbarBackground){let Gn=(io=Zr(e,xe.toolbarBackground))!=null?io:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Gn}}return n}var lf={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"}}},Fu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bl=()=>{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"},cf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":bl()},df=e=>cf(e),pf=e=>an(e),uf=e=>{var n;let t=an(void 0,{validate:!1});return an({...e,palette:{...t.palette,colors:{...lf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ti=e=>{let t=df(e),n=Fu(e==null?void 0:e.theme),o=Fu(e==null?void 0:e.darkTheme);return t==="dark"?uf(_s(n!=null?n:{},o!=null?o:{})):pf(n)},mf=e=>Du(e),es=(e,t)=>{let n=ti(t),o=mf(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},Ou=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(bl())});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(bl());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 yl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Mr(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]:Mr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var ni=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?{...Rt,...n}:n!=null?n:Rt,this.theme=an(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?yl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?yl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):yl(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=Mr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:an();this.config={...this.config,darkTheme:Mr(s,r,n)}}else this.config=Mr(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=Mr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:an();this.config={...this.config,darkTheme:Mr(l,d,i)},o=!0}else this.config=Mr(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=an((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=an(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Rt},this.theme=an(),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=an(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function oi(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 ri(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Nu(e,t){return t==="rem"?e*16:e}function _u(e,t){return t==="rem"?e/16:e}function ts(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 si(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function ai(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 Vs(e,t){let n=s=>{var l;let a=ts(s),i=a.startsWith("rgb")?(l=ai(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 vl(e){var f;let t=ts(e),n=t.startsWith("rgb")?(f=ai(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 xl(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 ii(e){let{h:t,s:n,l:o}=vl(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]=xl(t,l,d)}return a}var Lr=["50","100","200","300","400","500","600","700","800","900","950"],li=["primary","secondary","accent","gray","success","warning","error","info"];function Vu(e,t){return`palette.colors.${e}.${t}`}function wl(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.")?wl(e,`theme.${o}`,n+1):"#cbd5e1"}function $u(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"}],$s=["primary","secondary","accent","gray"],Uu={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Us={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"}]},zs={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"}]},qs={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"}]},js={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"}]},Ks={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"}]},Gs={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"}]},Ys={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"}]},Xs={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"}]},Qs={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},ir=[Us,zs,qs,js,Ks,Gs,Ys,Xs,Qs];function Js(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=gf(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 gf(e,t,n,o){let r=t==="solid";if(o==="role-header")return ff(e,r,n);if(o==="role-input")return hf(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 ff(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 hf(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 bf=/^palette\.colors\.(\w+)\.(\d+)$/;function ci(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(bf);if(!r)return null;let s=r[1],a=$s.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=Js(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 yf={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"}]}]},vf={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"}]},xf={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"}}]},wf={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)"}]}]},Cf={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"}]}]},Sf={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"}}]},Af={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)"}]},Tf={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"}]}]},Ir=[vf,xf,Cf,wf,yf,Sf,Af,Tf];function qu(){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:li.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 ju={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"}}]},Ku=qu(),Gu=ju,Yu=[qu(),ju],kf={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:fo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:ei},{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"}]}]},Ef={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Mf={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},Lf={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"}]}]},If={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"}]}]},Rf={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"}}]},Pf={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"}}]},Wf={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"}}]},Bf={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"}}]},Hf={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"}]},ns=[{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"}],Cl="0 5px 15px rgba(15, 23, 42, 0.08)",zu=[{value:Cl,label:"Default"},...ns],Df={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:ns},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:ns},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:ns},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:ns},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:Cl,options:zu},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:Cl,options:zu},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:ns}]},Sl=[kf,Ef,Mf,Lf,If,Df],Al=[Rf,Pf,Wf,Bf,Hf],Tl=[...Sl,...Al],kl=1024*1024,Ff=["What can you help me with?","Tell me about your features","How does this work?"],Zs={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 Of(e){return Number(e)*kl}function Nf(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/kl)):String(t):"10"}function _f(e){var t;return(t=Zs[String(e)])!=null?t:Zs.images}function Vf(e){let t=Array.isArray(e)?e:Zs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Zs)){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 $f={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"}]},Uf={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:Ff}]},zf={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:""}]},qf={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}]},jf={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"}]}]},Kf={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"}]}]},Gf={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:fo},{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"}]},Yf={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:""}]},Xf={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"}]},Qf={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"}]},Jf={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"}]},Zf={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"}]},eh={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:""}]},th={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)}]},nh={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*kl,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:Nf,parseValue:Of},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Zs.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:Vf,parseValue:_f}]},oh={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"}]}]},rh={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}]},sh={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"}]}]},ah={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}]},ih={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}]},ea=[{label:"Content",sections:[$f,Uf]},{label:"Layout",sections:[zf,qf,jf,Kf]},{label:"Widget",sections:[Gf,Yf,Xf,Qf,Jf,Zf]},{label:"Features",sections:[eh,th,nh,oh,rh]},{label:"Developer",collapsedByDefault:!0,sections:[sh,ah,ih]}],El=ea.flatMap(e=>e.sections),Ml={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"}]}]},Ll={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"}]},Il={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"}]},Rl={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:Us},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:zs},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:qs},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:js},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Ks},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Gs},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ys},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Xs},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Qs}]},Pl={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"}}]},Wl={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Xu=[Ml,Ll,Il,Rl,Pl,Wl],di=[{id:"style",label:"Style",sections:Ir},{id:"design-system",label:"Design System",sections:Tl},{id:"configure",label:"Configure",sections:El}];function Qu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function lh(e,t,n){return{...e,id:`${n}-${e.id}`,path:Qu(e.path,t)}}function Ju(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Zu(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=>lh(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])=>[Qu(d,t),l]))}))}}var Bl=[{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"]}],os=[...Bl];function pi(e){return os.find(t=>t.id===e)}var em=require("marked"),ch=e=>{if(e)return e},Hl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new em.Marked({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=ch(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},ui=e=>e?Hl({markedOptions:e.options,renderer:e.renderer}):Hl(),bv=Hl();var ta=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var tm=Iu(require("dompurify"),1),dh={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"]},ph=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,uh=()=>{let e=(0,tm.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!ph.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,dh)},mi=e=>e===!1?null:typeof e=="function"?e:uh();var Rr="webmcp:",Dl=new Map,nm=e=>{var t;Dl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Dl.set(n.name,o)}},Fl=e=>Dl.get(sm(e)),gi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function rm(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}:${mh(t.join(""))}`}function om(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 mh(e){let t=om(e,0).toString(36),n=om(e,2654435761).toString(36);return`${t}.${n}`}var fi=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 gi.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}nm(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=fh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Eo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return Eo(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=sm(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return Eo(`Failed to read WebMCP registry: ${v}`)}nm(a);let i=a.find(C=>C.name===s);if(!i)return Eo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Eo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return Eo("Aborted by cancel()");let d=Fl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Eo("User declined the tool call.");if(o!=null&&o.aborted)return Eo("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,vh(n),{signal:m.signal});return hh(C)}catch(C){if(p)return Eo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Eo("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return Eo(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){gi.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,gi.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:bh;try{return await n(t)}catch(r){return gi.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=>gh(t,o))}},sm=e=>e.startsWith(Rr)?e.slice(Rr.length):e,rs=e=>e.startsWith(Rr),gh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},fh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},hh=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:xh(t)}]}},Eo=e=>({isError:!0,content:[{type:"text",text:e}]}),bh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=yh(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)},sh=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)}},ah=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ih=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Zr=require("partial-json"),Qu=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),es=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)}},lh=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`},Ju=e=>e.status==="complete"?lh(e):e.status==="pending"?"Waiting":"",ch=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 Zu=e=>e.status==="complete"?ch(e):"Using tool...",fi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Qs=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 fi(t)},gi=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 fi(t)},Pl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Qs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},hi=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Xs(o,n.slice(s,a.index),[]),a[1]!==void 0?Xs(o,a[1],["bold"]):a[2]!==void 0?Xs(o,a[2],["italic"]):a[3]!==void 0&&Xs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Xs(o,n.slice(s),[]),o},Xs=(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})},dh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(n)},yh=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)}},vh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},xh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var ss=require("partial-json"),am=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),as=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)}},wh=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`},im=e=>e.status==="complete"?wh(e):e.status==="pending"?"Waiting":"",Ch=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 lm=e=>e.status==="complete"?Ch(e):"Using tool...",hi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},oa=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 hi(t)},bi=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 hi(t)},Ol=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=oa(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},yi=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&na(o,n.slice(s,a.index),[]),a[1]!==void 0?na(o,a[1],["bold"]):a[2]!==void 0?na(o,a[2],["italic"]):a[3]!==void 0&&na(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&na(o,n.slice(s),[]),o},na=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Sh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
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()=>{}}},Mr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},em=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},tm=()=>{var t;let e=dh();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)}},nm=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Zr.parse)(n,Zr.STR|Zr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Qu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Qu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var om=()=>{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 bi=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 ph="https://api.runtype.com/v1/dispatch",yi="https://api.runtype.com";function uh(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 Wl=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 mh(e){switch(e){case"json":return nm;case"regex-json":return tm;case"xml":return om;default:return em}}var rm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function fh(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=rm(n);if(!rm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Mr(e);return Mr(t)!==null&&a===null?t:e}var Js=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:ph,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:mh(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 mi(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$/,""))||yi}/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$/,""))||yi}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let F=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:F}),F}let l=await this.buildPayload(t.messages),m=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([F])=>F!=="sessionId"&&F!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Wl).map(F=>{var B,v,x;return{id:F.id,role:F.role,content:(x=(v=(B=F.contentParts)!=null?B:F.llmContent)!=null?v:F.rawContent)!=null?x:F.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?Xu(g):void 0,S=this.clientToolsFingerprintSessionId===d.sessionId,L=p&&S&&this.lastSentClientToolsFingerprint===w,R=!1,I=null,D;for(let F=0;;F++){let v={...u,...p&&(R||!L)&&g?{clientTools:g}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),D=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),D.status===409&&F===0&&p){let x=await D.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){R=!0,this.lastSentClientToolsFingerprint=null;continue}I=x!=null?x:{error:"Chat request failed"}}break}if(!D.ok){let F=I!=null?I:await D.json().catch(()=>({error:"Chat request failed"}));if(D.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(D.status===429){let v=new Error(F.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let B=new Error(F.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!D.body){let F=new Error("No response body received");throw n({type:"error",error:F}),F}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(D.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||yi}/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(/\/+$/,""))||yi}/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(Wl).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(Wl).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 cn,Fn,Zn,je;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=V=>{let Ee=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,Fe=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,Oe=V.tools?V.tools.map(Ue=>({...Ue,chunks:Ue.chunks?[...Ue.chunks]:void 0})):void 0;return{...V,reasoning:Ee,toolCall:Fe,tools:Oe}},u=V=>{if(V.role!=="assistant"||V.variant)return!0;let Ee=Array.isArray(V.contentParts)&&V.contentParts.length>0,Fe=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||Ee||Fe||!!V.stopReason},g=V=>{u(V)&&n({type:"message",message:m(V)})},p=null,w=null,S={current:null},L={current:null},R=!1,I=new Map,D=new Map,F=new Map,B=new Map,v={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},E=(V,Ee,Fe="")=>`${V}::${Ee}::${Fe}`,C=(V,Ee)=>`${V}::${Ee}::`,k=(V,Ee,Fe,Oe)=>{let Ue=E(V,Ee,Fe),pt=F.get(Ue);if(pt)return pt;let rt=Fe?`-${Fe}`:"",Tt={id:`nested-${V}-${Ee}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Fe?{partId:Fe}:{},agentMetadata:{executionId:Oe,parentToolId:V,parentStepId:Ee}};return F.set(Ue,Tt),g(Tt),Tt},O=V=>{if(V==null)return null;try{return String(V)}catch{return null}},U=V=>{var Ee,Fe,Oe,Ue,pt;return O((pt=(Ue=(Oe=(Fe=(Ee=V.stepId)!=null?Ee:V.step_id)!=null?Fe:V.step)!=null?Oe:V.parentId)!=null?Ue:V.flowStepId)!=null?pt:V.flow_step_id)},K=V=>{var Ee,Fe,Oe,Ue,pt,rt,Tt;return O((Tt=(rt=(pt=(Ue=(Oe=(Fe=(Ee=V.callId)!=null?Ee:V.call_id)!=null?Fe:V.requestId)!=null?Oe:V.request_id)!=null?Ue:V.toolCallId)!=null?pt:V.tool_call_id)!=null?rt:V.stepId)!=null?Tt:V.step_id)},fe=o,ae=!1,ge=()=>{if(p)return p;let V;return!ae&&fe?(V=fe,ae=!0):fe&&L.current?V=`${fe}_${L.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,p={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(p),p},le=(V,Ee)=>{v.lastId=Ee,V&&v.byStep.set(V,Ee)},ye=(V,Ee)=>{var pt;let Fe=(pt=V.reasoningId)!=null?pt:V.id,Oe=U(V);if(Fe){let rt=String(Fe);return le(Oe,rt),rt}if(Oe){let rt=v.byStep.get(Oe);if(rt)return v.lastId=rt,rt}if(v.lastId&&!Ee)return v.lastId;if(!Ee)return null;let Ue=`reason-${l()}`;return le(Oe,Ue),Ue},Ne=V=>{let Ee=I.get(V);if(Ee)return Ee;let Fe={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:V,status:"streaming",chunks:[]}};return I.set(V,Fe),g(Fe),Fe},xe=(V,Ee)=>{x.lastId=Ee,V&&x.byCall.set(V,Ee)},J=new Set,Ie=new Map,X=new Set,we=new Map,Ae=V=>{if(!V)return!1;let Ee=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ee==="emit_artifact_markdown"||Ee==="emit_artifact_component"},pe=(V,Ee)=>{var pt;let Fe=(pt=V.toolId)!=null?pt:V.id,Oe=K(V);if(Fe){let rt=String(Fe);return xe(Oe,rt),rt}if(Oe){let rt=x.byCall.get(Oe);if(rt)return x.lastId=rt,rt}if(x.lastId&&!Ee)return x.lastId;if(!Ee)return null;let Ue=`tool-${l()}`;return xe(Oe,Ue),Ue},Ce=V=>{let Ee=D.get(V);if(Ee)return Ee;let Fe={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:V,status:"pending"}};return D.set(V,Fe),g(Fe),Fe},qe=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let Ee=Number(V);if(!Number.isNaN(Ee)&&Number.isFinite(Ee))return Ee;let Fe=Date.parse(V);if(!Number.isNaN(Fe))return Fe}return Date.now()},ne=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},oe=new Map,se=new Map,ot=new Map,ve=new Map,ce=null,ze=(V,Ee,Fe)=>{var Tt;let Oe=ot.get(V);Oe||(Oe=[],ot.set(V,Oe));let Ue=0,pt=Oe.length;for(;Ue<pt;){let $t=Ue+pt>>>1;Oe[$t].seq<Ee?Ue=$t+1:pt=$t}((Tt=Oe[Ue])==null?void 0:Tt.seq)===Ee?Oe[Ue]={seq:Ee,text:Fe}:Oe.splice(Ue,0,{seq:Ee,text:Fe});let rt="";for(let $t=0;$t<Oe.length;$t++)rt+=Oe[$t].text;return rt},De=(V,Ee)=>{let Fe=ne(Ee),Oe=se.get(V.id),Ue=fh(Oe,Fe);V.rawContent=Ue;let pt=oe.get(V.id),rt=Je=>{var re;let Ot=(re=V.content)!=null?re:"";Je.trim()!==""&&(Ot.trim().length===0||Je.startsWith(Ot)||Je.trimStart().startsWith(Ot.trim()))&&(V.content=Je)},Tt=()=>{var Je;if(pt){let Ot=(Je=pt.close)==null?void 0:Je.call(pt);Ot instanceof Promise&&Ot.catch(()=>{})}oe.delete(V.id),se.delete(V.id),V.streaming=!1,g(V)};if(!pt){rt(Fe),Tt();return}let $t=Mr(Ue);if($t!==null&&$t.trim()!==""){rt($t),Tt();return}let j=Je=>{var he;let Ot=typeof Je=="string"?Je:(he=Je==null?void 0:Je.text)!=null?he:null;if(Ot!==null&&Ot.trim()!=="")return Ot;let re=pt.getExtractedText();return re!==null&&re.trim()!==""?re:Fe},Vt;try{Vt=pt.processChunk(Ue)}catch{rt(Fe),Tt();return}if(Vt instanceof Promise){Vt.then(Je=>{rt(j(Je)),Tt()}).catch(()=>{rt(Fe),Tt()});return}rt(j(Vt)),Tt()},de=[],Y=!1,$e,Mt=()=>{Y||(Y=!0,queueMicrotask(()=>{Y=!1,$e()}))},ue=new bi((V,Ee)=>{de.push({payloadType:V,payload:Ee}),Mt()}),ie=null,In=new Map,_t=(cn=this.config.iterationDisplay)!=null?cn:"separate";for($e=()=>{var V,Ee,Fe,Oe,Ue,pt,rt,Tt,$t,j,Vt,Je,Ot,re,he,wt,Ut,Zt,vn,kt,Ct,ht,yt,qt,tt,On,eo,xn,Nn,mt,So,_n,ur,Rn,Or,Uo,Ro,vt,Vn,$n,wn,Rt,to,no,Un,zo,Po,qo,zn,Bt,Cn,oo,jo,Wo,Ko,Ao,qn,uo,gt,Gt,Yt,jn,Go,ro,mo,Kn,M,Gn,fo,Bo,To,fs,go,ho,bo,Ho,mr,Ia,gs,Ra,Nr,ft,hs,so,Pn,Pa,Wa,_r,Do,Ba,fr,bs,Fo,ys,Yo,Xo,Ha,Da,pl,gr,Qo,Fa,vs,Jo,Oa,xs,Zo,ws,Na,Oo,_a,er,Ht,Vr,$r,Cs,ko,Va,Ss,As,$a,Ur,zr,hr,Ua,za,Ts,ks,Es,Ms,Sn,Yn,No,st,Ls,br,yo,qa;for(let tr=0;tr<de.length;tr++){let Ge=de[tr].payloadType,T=de[tr].payload;if(Ge==="reason_start"){let z=(V=ye(T,!0))!=null?V:`reason-${l()}`,H=Ne(z);H.reasoning=(Ee=H.reasoning)!=null?Ee:{id:z,status:"streaming",chunks:[]},H.reasoning.startedAt=(Oe=H.reasoning.startedAt)!=null?Oe:qe((Fe=T.startedAt)!=null?Fe:T.timestamp),H.reasoning.completedAt=void 0,H.reasoning.durationMs=void 0,H.streaming=!0,H.reasoning.status="streaming",g(H)}else if(Ge==="reason_delta"||Ge==="reason_chunk"){let z=(pt=(Ue=ye(T,!1))!=null?Ue:ye(T,!0))!=null?pt:`reason-${l()}`,H=Ne(z);H.reasoning=(rt=H.reasoning)!=null?rt:{id:z,status:"streaming",chunks:[]},H.reasoning.startedAt=($t=H.reasoning.startedAt)!=null?$t:qe((Tt=T.startedAt)!=null?Tt:T.timestamp);let Z=(Je=(Vt=(j=T.reasoningText)!=null?j:T.text)!=null?Vt:T.delta)!=null?Je:"";if(Z&&T.hidden!==!0){let te=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(te!==void 0){let G=ze(z,te,String(Z));H.reasoning.chunks=[G]}else H.reasoning.chunks.push(String(Z))}if(H.reasoning.status=T.done?"complete":"streaming",T.done){H.reasoning.completedAt=qe((Ot=T.completedAt)!=null?Ot:T.timestamp);let te=(re=H.reasoning.startedAt)!=null?re:Date.now();H.reasoning.durationMs=Math.max(0,((he=H.reasoning.completedAt)!=null?he:Date.now())-te)}H.streaming=H.reasoning.status!=="complete",g(H)}else if(Ge==="reason_complete"){let z=(Ut=(wt=ye(T,!1))!=null?wt:ye(T,!0))!=null?Ut:`reason-${l()}`,H=I.get(z);if(H!=null&&H.reasoning){H.reasoning.status="complete",H.reasoning.completedAt=qe((Zt=T.completedAt)!=null?Zt:T.timestamp);let te=(vn=H.reasoning.startedAt)!=null?vn:Date.now();H.reasoning.durationMs=Math.max(0,((kt=H.reasoning.completedAt)!=null?kt:Date.now())-te),H.streaming=!1,g(H)}let Z=U(T);Z&&v.byStep.delete(Z)}else if(Ge==="tool_start"){let z=(Ct=pe(T,!0))!=null?Ct:`tool-${l()}`,H=(ht=T.toolName)!=null?ht:T.name;if(Ae(H)){J.add(z);continue}let Z=Ce(z),te=(yt=Z.toolCall)!=null?yt:{id:z,status:"pending"};te.name=H!=null?H:te.name,te.status="running",T.args!==void 0?te.args=T.args:T.parameters!==void 0&&(te.args=T.parameters),te.startedAt=(tt=te.startedAt)!=null?tt:qe((qt=T.startedAt)!=null?qt:T.timestamp),te.completedAt=void 0,te.durationMs=void 0,Z.toolCall=te,Z.streaming=!0;let G=T.agentContext;(G||T.executionId)&&(Z.agentMetadata={executionId:(On=G==null?void 0:G.executionId)!=null?On:T.executionId,iteration:(eo=G==null?void 0:G.iteration)!=null?eo:T.iteration}),g(Z)}else if(Ge==="tool_chunk"||Ge==="tool_delta"){let z=(Nn=(xn=pe(T,!1))!=null?xn:pe(T,!0))!=null?Nn:`tool-${l()}`;if(J.has(z))continue;let H=Ce(z),Z=(mt=H.toolCall)!=null?mt:{id:z,status:"running"};Z.startedAt=(_n=Z.startedAt)!=null?_n:qe((So=T.startedAt)!=null?So:T.timestamp);let te=(Or=(Rn=(ur=T.text)!=null?ur:T.delta)!=null?Rn:T.message)!=null?Or:"";te&&(Z.chunks=(Uo=Z.chunks)!=null?Uo:[],Z.chunks.push(String(te))),Z.status="running",H.toolCall=Z,H.streaming=!0;let G=T.agentContext;(G||T.executionId)&&(H.agentMetadata=(Vn=H.agentMetadata)!=null?Vn:{executionId:(Ro=G==null?void 0:G.executionId)!=null?Ro:T.executionId,iteration:(vt=G==null?void 0:G.iteration)!=null?vt:T.iteration}),g(H)}else if(Ge==="tool_complete"){let z=(wn=($n=pe(T,!1))!=null?$n:pe(T,!0))!=null?wn:`tool-${l()}`;if(J.has(z)){J.delete(z);continue}let H=Ce(z),Z=(Rt=H.toolCall)!=null?Rt:{id:z,status:"running"};Z.status="complete",T.result!==void 0&&(Z.result=T.result),typeof T.duration=="number"&&(Z.duration=T.duration),Z.completedAt=qe((to=T.completedAt)!=null?to:T.timestamp);let te=(no=T.duration)!=null?no:T.executionTime;if(typeof te=="number")Z.durationMs=te;else{let Ve=(Un=Z.startedAt)!=null?Un:Date.now();Z.durationMs=Math.max(0,((zo=Z.completedAt)!=null?zo:Date.now())-Ve)}H.toolCall=Z,H.streaming=!1;let G=T.agentContext;(G||T.executionId)&&(H.agentMetadata=(zn=H.agentMetadata)!=null?zn:{executionId:(Po=G==null?void 0:G.executionId)!=null?Po:T.executionId,iteration:(qo=G==null?void 0:G.iteration)!=null?qo:T.iteration}),g(H);let Be=K(T);Be&&x.byCall.delete(Be)}else if(Ge==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let z=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,H=(Bt=z!=null?z:T.toolId)!=null?Bt:`local-${l()}`,Z=Ce(H),te=T.toolName,G=Jr(te),Be=(Cn=Z.toolCall)!=null?Cn:{id:H,status:"pending"};Be.name=te,Be.args=T.parameters,Be.status=G?"running":"complete",Be.chunks=(oo=Be.chunks)!=null?oo:[],Be.startedAt=(Wo=Be.startedAt)!=null?Wo:qe((jo=T.startedAt)!=null?jo:T.timestamp),G?(Be.completedAt=void 0,Be.duration=void 0,Be.durationMs=void 0):Be.completedAt=(Ko=Be.completedAt)!=null?Ko:Be.startedAt,Z.toolCall=Be,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(qn=T.executionId)!=null?qn:(Ao=Z.agentMetadata)==null?void 0:Ao.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(Z)}else if(Ge==="text_start"){if((uo=T.toolContext)!=null&&uo.toolId)continue;let z=T.partId;if(z!==void 0&&L.current!==null&&z!==L.current){let H=p;H&&(H.streaming=!1,g(H),ce=H,p=null,R=!0)}z!==void 0&&(L.current=z)}else if(Ge==="text_end"){if((gt=T.toolContext)!=null&&gt.toolId)continue;let z=p;z&&(z.streaming=!1,g(z),ce=z,p=null,R=!0)}else if(Ge==="step_chunk"||Ge==="step_delta"){let z=T.stepType,H=T.executionType;if(z==="tool"||H==="context")continue;let Z=T.toolContext;if(Z!=null&&Z.toolId){let Ve=String((Yt=(Gt=T.id)!=null?Gt:Z.stepId)!=null?Yt:`step-${l()}`),et=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Re=`${Z.toolId}::${Ve}`,Xe=B.get(Re);if(et!==""&&Xe!==void 0&&Xe!==""&&Xe!==et){let St=F.get(E(Z.toolId,Ve,Xe));St&&St.streaming!==!1&&(St.streaming=!1,g(St))}et!==""&&B.set(Re,et);let Pt=k(Z.toolId,Ve,et,Z.executionId),on=(mo=(ro=(Go=(jn=T.text)!=null?jn:T.delta)!=null?Go:T.content)!=null?ro:T.chunk)!=null?mo:"";on&&(Pt.content+=String(on),Pt.streaming=!0,g(Pt)),T.isComplete&&(Pt.streaming=!1,g(Pt));continue}let te=T.partId;if(te!==void 0&&L.current!==null&&te!==L.current){let Ve=p;Ve&&(Ve.streaming=!1,g(Ve),ce=Ve,p=null,R=!0)}te!==void 0&&(L.current=te);let G=te!==void 0&&(Kn=ve.get(te))!=null?Kn:ge();te!==void 0&&(G.partId||(G.partId=te),ve.set(te,G));let Be=(Bo=(fo=(Gn=(M=T.text)!=null?M:T.delta)!=null?Gn:T.content)!=null?fo:T.chunk)!=null?Bo:"";if(Be){let Ve=typeof T.seq=="number"?T.seq:void 0,et=te!=null?te:G.id,Re=Ve!==void 0?ze(et,Ve,String(Be)):((To=se.get(G.id))!=null?To:"")+Be;G.rawContent=Re,oe.has(G.id)||oe.set(G.id,this.createStreamParser());let Xe=oe.get(G.id),Pt=Re.trim().startsWith("{")||Re.trim().startsWith("[");if(Pt&&se.set(G.id,Re),Xe.__isPlainTextParser===!0){G.content=Ve!==void 0?Re:G.content+Be,se.delete(G.id),oe.delete(G.id),G.rawContent=void 0,g(G);continue}let St=Xe.processChunk(Re);if(St instanceof Promise)St.then(Lt=>{var mn;let rn=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(rn!==null&&rn.trim()!=="")G.content=rn,g(G);else if(!Pt&&!Re.trim().startsWith("<")){let An=p,Xt=An&&An.id===G.id?An:G;Xt.id===G.id&&(Xt.content=Ve!==void 0?Re:Xt.content+Be,se.delete(Xt.id),oe.delete(Xt.id),Xt.rawContent=void 0,g(Xt))}}).catch(()=>{G.content=Ve!==void 0?Re:G.content+Be,se.delete(G.id),oe.delete(G.id),G.rawContent=void 0,g(G)});else{let Lt=typeof St=="string"?St:(fs=St==null?void 0:St.text)!=null?fs:null;Lt!==null&&Lt.trim()!==""?(G.content=Lt,g(G)):!Pt&&!Re.trim().startsWith("<")&&(G.content=Ve!==void 0?Re:G.content+Be,se.delete(G.id),oe.delete(G.id),G.rawContent=void 0,g(G))}}if(T.isComplete){let Ve=(ho=(go=T.result)==null?void 0:go.response)!=null?ho:G.content;if(Ve){let et=se.get(G.id),Re=et!=null?et:ne(Ve);G.rawContent=Re;let Xe=oe.get(G.id),Pt=null,on=!1;if(Xe&&(Pt=Xe.getExtractedText(),Pt===null&&(Pt=Mr(Re)),Pt===null)){let St=Xe.processChunk(Re);St instanceof Promise?(on=!0,St.then(Lt=>{var mn;let rn=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(rn!==null){let An=p;An&&An.id===G.id&&(An.content=rn,An.streaming=!1,oe.delete(An.id),se.delete(An.id),g(An))}})):Pt=typeof St=="string"?St:(bo=St==null?void 0:St.text)!=null?bo:null}if(!on){Pt!==null&&Pt.trim()!==""?G.content=Pt:se.has(G.id)||(G.content=ne(Ve));let St=oe.get(G.id);if(St){let Lt=(Ho=St.close)==null?void 0:Ho.call(St);Lt instanceof Promise&&Lt.catch(()=>{}),oe.delete(G.id)}se.delete(G.id),G.streaming=!1,g(G)}}}}else if(Ge==="step_complete"){let z=T.stepType,H=T.executionType;if(z==="tool"||H==="context")continue;let Z=T.toolContext;if(Z!=null&&Z.toolId){let Ve=String((Ia=(mr=T.id)!=null?mr:Z.stepId)!=null?Ia:"");if(Ve){let et=C(Z.toolId,Ve);for(let[Re,Xe]of F)Re.startsWith(et)&&Xe.streaming!==!1&&(Xe.streaming=!1,g(Xe));B.delete(`${Z.toolId}::${Ve}`)}continue}let te=T.stopReason;if(R){if(p!==null){let Re=p;te&&(Re.stopReason=te),oe.delete(Re.id),se.delete(Re.id),Re.streaming!==!1&&(Re.streaming=!1,g(Re))}let Ve=(gs=T.result)==null?void 0:gs.response,et=ce;et&&(te&&(et.stopReason=te),Ve!=null?De(et,Ve):(oe.delete(et.id),se.delete(et.id))),ce=null;continue}let G=(Ra=T.result)==null?void 0:Ra.response,Be=ge();if(te&&(Be.stopReason=te),G!=null){let Ve=oe.get(Be.id),et=!1,Re=!1;if(Ve){let Xe=Ve.getExtractedText(),Pt=se.get(Be.id),on=Pt!=null?Pt:ne(G);if(Be.rawContent=on,Xe!==null&&Xe.trim()!=="")Be.content=Xe,et=!0;else{let St=Mr(on);if(St!==null)Be.content=St,et=!0;else{let Lt=Ve.processChunk(on);if(Lt instanceof Promise)Re=!0,Lt.then(rn=>{var An;let mn=typeof rn=="string"?rn:(An=rn==null?void 0:rn.text)!=null?An:null;if(mn!==null&&mn.trim()!==""){let Xt=p;Xt&&Xt.id===Be.id&&(Xt.content=mn,Xt.streaming=!1,oe.delete(Xt.id),se.delete(Xt.id),g(Xt))}else{let Xt=Ve.getExtractedText(),ao=p;ao&&ao.id===Be.id&&(Xt!==null&&Xt.trim()!==""?ao.content=Xt:se.has(ao.id)||(ao.content=ne(G)),ao.streaming=!1,oe.delete(ao.id),se.delete(ao.id),g(ao))}});else{let rn=typeof Lt=="string"?Lt:(Nr=Lt==null?void 0:Lt.text)!=null?Nr:null;if(rn!==null&&rn.trim()!=="")Be.content=rn,et=!0;else{let mn=Ve.getExtractedText();mn!==null&&mn.trim()!==""&&(Be.content=mn,et=!0)}}}}}if(!Re){if(!Be.rawContent){let Xe=se.get(Be.id);Be.rawContent=Xe!=null?Xe:ne(G)}if(!et&&!se.has(Be.id)&&(Be.content=ne(G)),Ve){let Xe=(ft=Ve.close)==null?void 0:ft.call(Ve);Xe instanceof Promise&&Xe.catch(()=>{})}oe.delete(Be.id),se.delete(Be.id),Be.streaming=!1,g(Be)}}else oe.delete(Be.id),se.delete(Be.id),Be.streaming=!1,g(Be)}else if(Ge==="flow_complete"){let z=(hs=T.result)==null?void 0:hs.response;if(R){if(p!==null){let H=p;oe.delete(H.id),se.delete(H.id),H.streaming!==!1&&(H.streaming=!1,g(H))}}else if(z!=null){let H=ge(),Z=se.get(H.id),te=Z!=null?Z:ne(z);H.rawContent=te;let G=ne(z),Be=oe.get(H.id);if(Be){let Re=Mr(te);if(Re!==null)G=Re;else{let Xe=Be.processChunk(te);Xe instanceof Promise&&Xe.then(on=>{var Lt;let St=typeof on=="string"?on:(Lt=on==null?void 0:on.text)!=null?Lt:null;St!==null&&(H.content=St,H.streaming=!1,g(H))});let Pt=Be.getExtractedText();Pt!==null&&(G=Pt)}}oe.delete(H.id),se.delete(H.id);let Ve=G!==H.content,et=H.streaming!==!1;Ve&&(H.content=G),H.streaming=!1,(Ve||et)&&g(H)}else if(p!==null){let H=p;oe.delete(H.id),se.delete(H.id),H.streaming!==!1&&(H.streaming=!1,g(H))}n({type:"status",status:"idle"})}else if(Ge==="agent_start")ie={executionId:T.executionId,agentId:(so=T.agentId)!=null?so:"virtual",agentName:(Pn=T.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(Pa=T.maxTurns)!=null?Pa:1,startedAt:qe(T.startedAt)};else if(Ge==="agent_iteration_start"){if(ie&&(ie.currentIteration=T.iteration),_t==="separate"&&T.iteration>1){let z=p;z&&(z.streaming=!1,g(z),In.set(T.iteration-1,z),p=null)}}else if(Ge==="agent_turn_start")w=null;else if(Ge==="agent_turn_delta"){if(T.contentType==="text"){let z=ge();z.content+=(Wa=T.delta)!=null?Wa:"",z.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:ie==null?void 0:ie.agentName},w=z,g(z)}else if(T.contentType==="thinking"){let z=(_r=T.turnId)!=null?_r:`agent-think-${T.iteration}`,H=Ne(z);H.reasoning=(Do=H.reasoning)!=null?Do:{id:z,status:"streaming",chunks:[]},H.reasoning.chunks.push((Ba=T.delta)!=null?Ba:""),H.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},g(H)}else if(T.contentType==="tool_input"){let z=(fr=T.toolCallId)!=null?fr:x.lastId;if(z){let H=D.get(z);H!=null&&H.toolCall&&(H.toolCall.chunks=(bs=H.toolCall.chunks)!=null?bs:[],H.toolCall.chunks.push((Fo=T.delta)!=null?Fo:""),g(H))}}}else if(Ge==="agent_turn_complete"){let z=T.turnId;if(z){let te=I.get(z);if(te!=null&&te.reasoning){te.reasoning.status="complete",te.reasoning.completedAt=qe(T.completedAt);let G=(ys=te.reasoning.startedAt)!=null?ys:Date.now();te.reasoning.durationMs=Math.max(0,((Yo=te.reasoning.completedAt)!=null?Yo:Date.now())-G),te.streaming=!1,g(te)}}let H=T.stopReason,Z=p!=null?p:w;if(H&&Z!==null){let te=T.turnId;(!te||((Xo=Z.agentMetadata)==null?void 0:Xo.turnId)===te)&&(Z.stopReason=H,g(Z))}}else if(Ge==="agent_tool_start"){p&&(p.streaming=!1,g(p),p=null);let z=(Ha=T.toolCallId)!=null?Ha:`agent-tool-${l()}`;xe(K(T),z);let H=Ce(z),Z=(Da=H.toolCall)!=null?Da:{id:z,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(gr=(pl=T.toolName)!=null?pl:T.name)!=null?gr:Z.name,Z.status="running",T.parameters!==void 0&&(Z.args=T.parameters),Z.startedAt=qe((Qo=T.startedAt)!=null?Qo:T.timestamp),H.toolCall=Z,H.streaming=!0,H.agentMetadata={executionId:T.executionId,iteration:T.iteration},g(H)}else if(Ge==="agent_tool_delta"){let z=(Fa=T.toolCallId)!=null?Fa:x.lastId;if(z){let H=(vs=D.get(z))!=null?vs:Ce(z);H.toolCall&&(H.toolCall.chunks=(Jo=H.toolCall.chunks)!=null?Jo:[],H.toolCall.chunks.push((Oa=T.delta)!=null?Oa:""),H.toolCall.status="running",H.streaming=!0,g(H))}}else if(Ge==="agent_tool_complete"){let z=(xs=T.toolCallId)!=null?xs:x.lastId;if(z){let H=(Zo=D.get(z))!=null?Zo:Ce(z);if(H.toolCall){H.toolCall.status="complete",T.result!==void 0&&(H.toolCall.result=T.result),typeof T.executionTime=="number"&&(H.toolCall.durationMs=T.executionTime),H.toolCall.completedAt=qe((ws=T.completedAt)!=null?ws:T.timestamp),H.streaming=!1,g(H);let Z=K(T);Z&&x.byCall.delete(Z)}}}else if(Ge==="agent_media"){let z=Array.isArray(T.media)?T.media:[],H=[];for(let Z of z){if(!Z||typeof Z!="object")continue;let te=Z,G=typeof te.type=="string"?te.type:void 0,Be=typeof te.mediaType=="string"?te.mediaType.toLowerCase():"",Ve=null,et="";if(G==="media"){let Re=typeof te.data=="string"?te.data:void 0;if(!Re)continue;et=Be.length>0?Be:"application/octet-stream",Ve=`data:${et};base64,${Re}`}else if(G==="image-url"){let Re=typeof te.url=="string"?te.url:void 0;if(!Re)continue;et=Be,Ve=Re}else if(G==="file-url"){let Re=typeof te.url=="string"?te.url:void 0;if(!Re)continue;et=Be,Ve=Re}else continue;if(Ve)if(G==="image-url"||et.startsWith("image/"))H.push({type:"image",image:Ve,...et?{mimeType:et}:{}});else if(et.startsWith("audio/"))H.push({type:"audio",audio:Ve,mimeType:et});else if(et.startsWith("video/"))H.push({type:"video",video:Ve,mimeType:et});else{let Re=et||"application/octet-stream";H.push({type:"file",data:Ve,mimeType:Re,filename:uh(Re)})}}if(H.length>0){let Z=l(),te=T.toolCallId,Be={id:`agent-media-${typeof te=="string"&&te.length>0?`${te}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:H,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};g(Be);let Ve=p;Ve&&(Ve.streaming=!1,g(Ve)),p=null,S.current=null}}else if(Ge!=="agent_iteration_complete"){if(Ge==="agent_reflection"||Ge==="agent_reflect"){let z=`agent-reflection-${T.executionId}-${T.iteration}`,H={id:z,role:"assistant",content:(Na=T.reflection)!=null?Na:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Oo=T.reflection)!=null?Oo:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};g(H)}else if(Ge==="agent_complete"){ie&&(ie.status=T.success?"complete":"error",ie.completedAt=qe(T.completedAt),ie.stopReason=T.stopReason);let z=p;z&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}else if(Ge==="agent_error"){let z=typeof T.error=="string"?T.error:(er=(_a=T.error)==null?void 0:_a.message)!=null?er:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(Ge!=="agent_ping"){if(Ge==="agent_approval_start"){let z=(Ht=T.approvalId)!=null?Ht:`approval-${l()}`,H={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Vr=ie==null?void 0:ie.agentId)!=null?Vr:"virtual",executionId:(Cs=($r=T.executionId)!=null?$r:ie==null?void 0:ie.executionId)!=null?Cs:"",toolName:(ko=T.toolName)!=null?ko:"",toolType:T.toolType,description:(Ss=T.description)!=null?Ss:`Execute ${(Va=T.toolName)!=null?Va:"tool"}`,parameters:T.parameters}};g(H)}else if(Ge==="step_await"&&T.awaitReason==="approval_required"){let z=(As=T.approvalId)!=null?As:`approval-${l()}`,H={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:($a=ie==null?void 0:ie.agentId)!=null?$a:"virtual",executionId:(zr=(Ur=T.executionId)!=null?Ur:ie==null?void 0:ie.executionId)!=null?zr:"",toolName:(hr=T.toolName)!=null?hr:"",toolType:T.toolType,description:(za=T.description)!=null?za:`Execute ${(Ua=T.toolName)!=null?Ua:"tool"}`,parameters:T.parameters}};g(H)}else if(Ge==="agent_approval_complete"){let z=T.approvalId;if(z){let Z={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(Ts=T.decision)!=null?Ts:"approved",agentId:(ks=ie==null?void 0:ie.agentId)!=null?ks:"virtual",executionId:(Ms=(Es=T.executionId)!=null?Es:ie==null?void 0:ie.executionId)!=null?Ms:"",toolName:(Sn=T.toolName)!=null?Sn:"",description:(Yn=T.description)!=null?Yn:"",resolvedAt:Date.now()}};g(Z)}}else if(Ge==="artifact_start"||Ge==="artifact_delta"||Ge==="artifact_update"||Ge==="artifact_complete"){if(Ge==="artifact_start"){let z=T.artifactType,H=String(T.id),Z=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:H,artifactType:z,title:Z,component:typeof T.component=="string"?T.component:void 0}),we.set(H,{markdown:"",title:Z}),!X.has(H)){X.add(H);let te={id:`artifact-ref-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:H,title:Z,artifactType:z,status:"streaming"}})};Ie.set(H,te),g(te)}}else if(Ge==="artifact_delta"){let z=String(T.id),H=typeof T.delta=="string"?T.delta:String((No=T.delta)!=null?No:"");n({type:"artifact_delta",id:z,artDelta:H});let Z=we.get(z);Z&&(Z.markdown+=H)}else if(Ge==="artifact_update"){let z=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:z,component:typeof T.component=="string"?T.component:void 0})}else if(Ge==="artifact_complete"){let z=String(T.id);n({type:"artifact_complete",id:z});let H=Ie.get(z);if(H){H.streaming=!1;try{let Z=JSON.parse((st=H.rawContent)!=null?st:"{}");if(Z.props){Z.props.status="complete";let te=we.get(z);te!=null&&te.markdown&&(Z.props.markdown=te.markdown)}H.rawContent=JSON.stringify(Z)}catch{}we.delete(z),g(H),Ie.delete(z)}}}else if(Ge==="transcript_insert"){let z=T.message;if(!z||typeof z!="object")continue;let H=String((Ls=z.id)!=null?Ls:`msg-${l()}`),Z=z.role,G={id:H,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(G),G.rawContent)try{let Be=JSON.parse(G.rawContent),Ve=(br=Be==null?void 0:Be.props)==null?void 0:br.artifactId;typeof Ve=="string"&&X.add(Ve)}catch{}p=null,S.current=null,oe.delete(H),se.delete(H)}else if(Ge==="error"||Ge==="step_error"||Ge==="dispatch_error"||Ge==="flow_error"){let z=null;if(T.error instanceof Error)z=T.error;else if(Ge==="dispatch_error"){let H=(yo=T.message)!=null?yo:T.error;H!=null&&H!==""&&(z=new Error(String(H)))}else if(Ge==="step_error"||Ge==="flow_error"){let H=T.error;typeof H=="string"&&H!==""?z=new Error(H):H!=null&&typeof H=="object"&&"message"in H&&(z=new Error(String((qa=H.message)!=null?qa:H)))}else Ge==="error"&&T.error!=null&&T.error!==""&&(z=new Error(String(T.error)));if(z){n({type:"error",error:z});let H=p;H&&H.streaming&&(H.streaming=!1,g(H)),n({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:V,value:Ee}=await r.read();if(V)break;a+=s.decode(Ee,{stream:!0});let Fe=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()=>{}}},Pr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},cm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},dm=()=>{var t;let e=Sh();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},pm=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,ss.parse)(n,ss.STR|ss.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?am(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=am(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var um=()=>{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 vi=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Ah="https://api.runtype.com/v1/dispatch",xi="https://api.runtype.com";function Th(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 Nl=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 kh(e){switch(e){case"json":return pm;case"regex-json":return dm;case"xml":return um;default:return cm}}var mm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Eh(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=mm(n);if(!mm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Pr(e);return Pr(t)!==null&&a===null?t:e}var ra=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:Ah,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:kh(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 fi(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$/,""))||xi}/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$/,""))||xi}/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,p={sessionId:d.sessionId,messages:t.messages.filter(Nl).map(D=>{var B,x,w;return{id:D.id,role:D.role,content:(w=(x=(B=D.contentParts)!=null?B:D.llmContent)!=null?x:D.rawContent)!=null?w: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}},f=l.clientTools,u=!!(f&&f.length>0),C=u?rm(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=u&&v&&this.lastSentClientToolsFingerprint===C,I=!1,R=null,W;for(let D=0;;D++){let x={...p,...u&&(I||!M)&&f?{clientTools:f}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",x),W=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),signal:o.signal}),W.status===409&&D===0&&u){let w=await W.json().catch(()=>null);if((w==null?void 0:w.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=w!=null?w:{error:"Chat request failed"}}break}if(!W.ok){let D=R!=null?R:await W.json().catch(()=>({error:"Chat request failed"}));if(W.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(W.status===429){let x=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let B=new Error(D.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!W.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=C!=null?C:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(W.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$/,""))||xi}/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(/\/+$/,""))||xi}/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(Nl).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(Nl).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 gn,Fn,to,qe;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=V=>{let Le=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,He=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,De=V.tools?V.tools.map(Ve=>({...Ve,chunks:Ve.chunks?[...Ve.chunks]:void 0})):void 0;return{...V,reasoning:Le,toolCall:He,tools:De}},p=V=>{if(V.role!=="assistant"||V.variant)return!0;let Le=Array.isArray(V.contentParts)&&V.contentParts.length>0,He=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||Le||He||!!V.stopReason},f=V=>{p(V)&&n({type:"message",message:m(V)})},u=null,C=null,v={current:null},M={current:null},I=!1,R=new Map,W=new Map,D=new Map,B=new Map,x={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},E=(V,Le,He="")=>`${V}::${Le}::${He}`,S=(V,Le)=>`${V}::${Le}::`,T=(V,Le,He,De)=>{let Ve=E(V,Le,He),mt=D.get(Ve);if(mt)return mt;let at=He?`-${He}`:"",Pt={id:`nested-${V}-${Le}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:De,parentToolId:V,parentStepId:Le}};return D.set(Ve,Pt),f(Pt),Pt},_=V=>{if(V==null)return null;try{return String(V)}catch{return null}},U=V=>{var Le,He,De,Ve,mt;return _((mt=(Ve=(De=(He=(Le=V.stepId)!=null?Le:V.step_id)!=null?He:V.step)!=null?De:V.parentId)!=null?Ve:V.flowStepId)!=null?mt:V.flow_step_id)},Y=V=>{var Le,He,De,Ve,mt,at,Pt;return _((Pt=(at=(mt=(Ve=(De=(He=(Le=V.callId)!=null?Le:V.call_id)!=null?He:V.requestId)!=null?De:V.request_id)!=null?Ve:V.toolCallId)!=null?mt:V.tool_call_id)!=null?at:V.stepId)!=null?Pt:V.step_id)},he=o,fe=!1,ae=()=>{if(u)return u;let V;return!fe&&he?(V=he,fe=!0):he&&M.current?V=`${he}_${M.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(u),u},Ee=(V,Le)=>{x.lastId=Le,V&&x.byStep.set(V,Le)},ye=(V,Le)=>{var mt;let He=(mt=V.reasoningId)!=null?mt:V.id,De=U(V);if(He){let at=String(He);return Ee(De,at),at}if(De){let at=x.byStep.get(De);if(at)return x.lastId=at,at}if(x.lastId&&!Le)return x.lastId;if(!Le)return null;let Ve=`reason-${l()}`;return Ee(De,Ve),Ve},Oe=V=>{let Le=R.get(V);if(Le)return Le;let He={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:V,status:"streaming",chunks:[]}};return R.set(V,He),f(He),He},we=(V,Le)=>{w.lastId=Le,V&&w.byCall.set(V,Le)},K=new Set,pe=new Map,G=new Set,ve=new Map,ce=V=>{if(!V)return!1;let Le=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return Le==="emit_artifact_markdown"||Le==="emit_artifact_component"},ne=(V,Le)=>{var mt;let He=(mt=V.toolId)!=null?mt:V.id,De=Y(V);if(He){let at=String(He);return we(De,at),at}if(De){let at=w.byCall.get(De);if(at)return w.lastId=at,at}if(w.lastId&&!Le)return w.lastId;if(!Le)return null;let Ve=`tool-${l()}`;return we(De,Ve),Ve},Se=V=>{let Le=W.get(V);if(Le)return Le;let He={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:V,status:"pending"}};return W.set(V,He),f(He),He},ze=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let Le=Number(V);if(!Number.isNaN(Le)&&Number.isFinite(Le))return Le;let He=Date.parse(V);if(!Number.isNaN(He))return He}return Date.now()},te=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},re=new Map,ie=new Map,st=new Map,Te=new Map,ue=null,Ue=(V,Le,He)=>{var Pt;let De=st.get(V);De||(De=[],st.set(V,De));let Ve=0,mt=De.length;for(;Ve<mt;){let jt=Ve+mt>>>1;De[jt].seq<Le?Ve=jt+1:mt=jt}((Pt=De[Ve])==null?void 0:Pt.seq)===Le?De[Ve]={seq:Le,text:He}:De.splice(Ve,0,{seq:Le,text:He});let at="";for(let jt=0;jt<De.length;jt++)at+=De[jt].text;return at},Be=(V,Le)=>{let He=te(Le),De=ie.get(V.id),Ve=Eh(De,He);V.rawContent=Ve;let mt=re.get(V.id),at=Ze=>{var se;let Vt=(se=V.content)!=null?se:"";Ze.trim()!==""&&(Vt.trim().length===0||Ze.startsWith(Vt)||Ze.trimStart().startsWith(Vt.trim()))&&(V.content=Ze)},Pt=()=>{var Ze;if(mt){let Vt=(Ze=mt.close)==null?void 0:Ze.call(mt);Vt instanceof Promise&&Vt.catch(()=>{})}re.delete(V.id),ie.delete(V.id),V.streaming=!1,f(V)};if(!mt){at(He),Pt();return}let jt=Pr(Ve);if(jt!==null&&jt.trim()!==""){at(jt),Pt();return}let j=Ze=>{var Ce;let Vt=typeof Ze=="string"?Ze:(Ce=Ze==null?void 0:Ze.text)!=null?Ce:null;if(Vt!==null&&Vt.trim()!=="")return Vt;let se=mt.getExtractedText();return se!==null&&se.trim()!==""?se:He},zt;try{zt=mt.processChunk(Ve)}catch{at(He),Pt();return}if(zt instanceof Promise){zt.then(Ze=>{at(j(Ze)),Pt()}).catch(()=>{at(He),Pt()});return}at(j(zt)),Pt()},me=[],Q=!1,_e,Ht=()=>{Q||(Q=!0,queueMicrotask(()=>{Q=!1,_e()}))},be=new vi((V,Le)=>{me.push({payloadType:V,payload:Le}),Ht()}),de=null,Pn=new Map,Ut=(gn=this.config.iterationDisplay)!=null?gn:"separate";for(_e=()=>{var V,Le,He,De,Ve,mt,at,Pt,jt,j,zt,Ze,Vt,se,Ce,kt,Kt,tn,An,Wt,Mt,wt,St,Gt,ot,On,no,Tn,Nn,bt,Lo,_n,fr,Wn,$r,jo,Do,At,Vn,$n,kn,Lt,oo,ro,Un,Ko,Fo,Go,zn,Ft,En,so,Yo,Oo,Xo,Io,qn,yo,vt,Xt,Qt,jn,Qo,ao,vo,Kn,$,io,xe,Gn,lo,xo,xs,wo,Co,So,No,hr,Da,ws,Fa,Ur,yt,Cs,co,Bn,Oa,Na,zr,_o,_a,br,Ss,Vo,As,Jo,Zo,Va,$a,fl,yr,er,Ua,Ts,tr,za,ks,nr,Es,qa,$o,ja,or,Ot,qr,jr,Ms,Ro,Ka,Ls,Is,Ga,Kr,Gr,vr,Ya,Xa,Rs,Ps,Ws,Bs,Mn,Yn,Uo,ct,Hs,xr,Ao;for(let Yr=0;Yr<me.length;Yr++){let Ye=me[Yr].payloadType,k=me[Yr].payload;if(Ye==="reason_start"){let z=(V=ye(k,!0))!=null?V:`reason-${l()}`,P=Oe(z);P.reasoning=(Le=P.reasoning)!=null?Le:{id:z,status:"streaming",chunks:[]},P.reasoning.startedAt=(De=P.reasoning.startedAt)!=null?De:ze((He=k.startedAt)!=null?He:k.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",f(P)}else if(Ye==="reason_delta"||Ye==="reason_chunk"){let z=(mt=(Ve=ye(k,!1))!=null?Ve:ye(k,!0))!=null?mt:`reason-${l()}`,P=Oe(z);P.reasoning=(at=P.reasoning)!=null?at:{id:z,status:"streaming",chunks:[]},P.reasoning.startedAt=(jt=P.reasoning.startedAt)!=null?jt:ze((Pt=k.startedAt)!=null?Pt:k.timestamp);let Z=(Ze=(zt=(j=k.reasoningText)!=null?j:k.text)!=null?zt:k.delta)!=null?Ze:"";if(Z&&k.hidden!==!0){let le=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(le!==void 0){let X=Ue(z,le,String(Z));P.reasoning.chunks=[X]}else P.reasoning.chunks.push(String(Z))}if(P.reasoning.status=k.done?"complete":"streaming",k.done){P.reasoning.completedAt=ze((Vt=k.completedAt)!=null?Vt:k.timestamp);let le=(se=P.reasoning.startedAt)!=null?se:Date.now();P.reasoning.durationMs=Math.max(0,((Ce=P.reasoning.completedAt)!=null?Ce:Date.now())-le)}P.streaming=P.reasoning.status!=="complete",f(P)}else if(Ye==="reason_complete"){let z=(Kt=(kt=ye(k,!1))!=null?kt:ye(k,!0))!=null?Kt:`reason-${l()}`,P=R.get(z);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=ze((tn=k.completedAt)!=null?tn:k.timestamp);let le=(An=P.reasoning.startedAt)!=null?An:Date.now();P.reasoning.durationMs=Math.max(0,((Wt=P.reasoning.completedAt)!=null?Wt:Date.now())-le),P.streaming=!1,f(P)}let Z=U(k);Z&&x.byStep.delete(Z)}else if(Ye==="tool_start"){let z=(Mt=ne(k,!0))!=null?Mt:`tool-${l()}`,P=(wt=k.toolName)!=null?wt:k.name;if(ce(P)){K.add(z);continue}let Z=Se(z),le=(St=Z.toolCall)!=null?St:{id:z,status:"pending"};le.name=P!=null?P:le.name,le.status="running",k.args!==void 0?le.args=k.args:k.parameters!==void 0&&(le.args=k.parameters),le.startedAt=(ot=le.startedAt)!=null?ot:ze((Gt=k.startedAt)!=null?Gt:k.timestamp),le.completedAt=void 0,le.durationMs=void 0,Z.toolCall=le,Z.streaming=!0;let X=k.agentContext;(X||k.executionId)&&(Z.agentMetadata={executionId:(On=X==null?void 0:X.executionId)!=null?On:k.executionId,iteration:(no=X==null?void 0:X.iteration)!=null?no:k.iteration}),f(Z)}else if(Ye==="tool_chunk"||Ye==="tool_delta"){let z=(Nn=(Tn=ne(k,!1))!=null?Tn:ne(k,!0))!=null?Nn:`tool-${l()}`;if(K.has(z))continue;let P=Se(z),Z=(bt=P.toolCall)!=null?bt:{id:z,status:"running"};Z.startedAt=(_n=Z.startedAt)!=null?_n:ze((Lo=k.startedAt)!=null?Lo:k.timestamp);let le=($r=(Wn=(fr=k.text)!=null?fr:k.delta)!=null?Wn:k.message)!=null?$r:"";le&&(Z.chunks=(jo=Z.chunks)!=null?jo:[],Z.chunks.push(String(le))),Z.status="running",P.toolCall=Z,P.streaming=!0;let X=k.agentContext;(X||k.executionId)&&(P.agentMetadata=(Vn=P.agentMetadata)!=null?Vn:{executionId:(Do=X==null?void 0:X.executionId)!=null?Do:k.executionId,iteration:(At=X==null?void 0:X.iteration)!=null?At:k.iteration}),f(P)}else if(Ye==="tool_complete"){let z=(kn=($n=ne(k,!1))!=null?$n:ne(k,!0))!=null?kn:`tool-${l()}`;if(K.has(z)){K.delete(z);continue}let P=Se(z),Z=(Lt=P.toolCall)!=null?Lt:{id:z,status:"running"};Z.status="complete",k.result!==void 0&&(Z.result=k.result),typeof k.duration=="number"&&(Z.duration=k.duration),Z.completedAt=ze((oo=k.completedAt)!=null?oo:k.timestamp);let le=(ro=k.duration)!=null?ro:k.executionTime;if(typeof le=="number")Z.durationMs=le;else{let Ne=(Un=Z.startedAt)!=null?Un:Date.now();Z.durationMs=Math.max(0,((Ko=Z.completedAt)!=null?Ko:Date.now())-Ne)}P.toolCall=Z,P.streaming=!1;let X=k.agentContext;(X||k.executionId)&&(P.agentMetadata=(zn=P.agentMetadata)!=null?zn:{executionId:(Fo=X==null?void 0:X.executionId)!=null?Fo:k.executionId,iteration:(Go=X==null?void 0:X.iteration)!=null?Go:k.iteration}),f(P);let Re=Y(k);Re&&w.byCall.delete(Re)}else if(Ye==="step_await"&&k.awaitReason==="local_tool_required"&&k.toolName){let z=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,P=(Ft=z!=null?z:k.toolId)!=null?Ft:`local-${l()}`,Z=Se(P),le=k.toolName,X=rs(le),Re=(En=Z.toolCall)!=null?En:{id:P,status:"pending"};Re.name=le,Re.args=k.parameters,Re.status=X?"running":"complete",Re.chunks=(so=Re.chunks)!=null?so:[],Re.startedAt=(Oo=Re.startedAt)!=null?Oo:ze((Yo=k.startedAt)!=null?Yo:k.timestamp),X?(Re.completedAt=void 0,Re.duration=void 0,Re.durationMs=void 0):Re.completedAt=(Xo=Re.completedAt)!=null?Xo:Re.startedAt,Z.toolCall=Re,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(qn=k.executionId)!=null?qn:(Io=Z.agentMetadata)==null?void 0:Io.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},f(Z)}else if(Ye==="text_start"){if((yo=k.toolContext)!=null&&yo.toolId)continue;let z=k.partId;if(z!==void 0&&M.current!==null&&z!==M.current){let P=u;P&&(P.streaming=!1,f(P),ue=P,u=null,I=!0)}z!==void 0&&(M.current=z)}else if(Ye==="text_end"){if((vt=k.toolContext)!=null&&vt.toolId)continue;let z=u;z&&(z.streaming=!1,f(z),ue=z,u=null,I=!0)}else if(Ye==="step_chunk"||Ye==="step_delta"){let z=k.stepType,P=k.executionType;if(z==="tool"||P==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Qt=(Xt=k.id)!=null?Xt:Z.stepId)!=null?Qt:`step-${l()}`),dt=k.partId!==void 0&&k.partId!==null?String(k.partId):"",Xe=`${Z.toolId}::${Ne}`,Qe=B.get(Xe);if(dt!==""&&Qe!==void 0&&Qe!==""&&Qe!==dt){let It=D.get(E(Z.toolId,Ne,Qe));It&&It.streaming!==!1&&(It.streaming=!1,f(It))}dt!==""&&B.set(Xe,dt);let et=T(Z.toolId,Ne,dt,Z.executionId),Jt=(vo=(ao=(Qo=(jn=k.text)!=null?jn:k.delta)!=null?Qo:k.content)!=null?ao:k.chunk)!=null?vo:"";Jt&&(et.content+=String(Jt),et.streaming=!0,f(et)),k.isComplete&&(et.streaming=!1,f(et));continue}let le=k.partId;if(le!==void 0&&M.current!==null&&le!==M.current){let Ne=u;Ne&&(Ne.streaming=!1,f(Ne),ue=Ne,u=null,I=!0)}le!==void 0&&(M.current=le);let X=le!==void 0&&(Kn=Te.get(le))!=null?Kn:ae();le!==void 0&&(X.partId||(X.partId=le),Te.set(le,X));let Re=(Gn=(xe=(io=($=k.text)!=null?$:k.delta)!=null?io:k.content)!=null?xe:k.chunk)!=null?Gn:"";if(Re){let Ne=typeof k.seq=="number"?k.seq:void 0,dt=le!=null?le:X.id,Xe=Ne!==void 0?Ue(dt,Ne,String(Re)):((lo=ie.get(X.id))!=null?lo:"")+Re;X.rawContent=Xe,re.has(X.id)||re.set(X.id,this.createStreamParser());let Qe=re.get(X.id),et=Xe.trim().startsWith("{")||Xe.trim().startsWith("[");if(et&&ie.set(X.id,Xe),Qe.__isPlainTextParser===!0){X.content=Ne!==void 0?Xe:X.content+Re,ie.delete(X.id),re.delete(X.id),X.rawContent=void 0,f(X);continue}let It=Qe.processChunk(Xe);if(It instanceof Promise)It.then(Dt=>{var yn;let ln=typeof Dt=="string"?Dt:(yn=Dt==null?void 0:Dt.text)!=null?yn:null;if(ln!==null&&ln.trim()!=="")X.content=ln,f(X);else if(!et&&!Xe.trim().startsWith("<")){let hn=u,nn=hn&&hn.id===X.id?hn:X;nn.id===X.id&&(nn.content=Ne!==void 0?Xe:nn.content+Re,ie.delete(nn.id),re.delete(nn.id),nn.rawContent=void 0,f(nn))}}).catch(()=>{X.content=Ne!==void 0?Xe:X.content+Re,ie.delete(X.id),re.delete(X.id),X.rawContent=void 0,f(X)});else{let Dt=typeof It=="string"?It:(xo=It==null?void 0:It.text)!=null?xo:null;Dt!==null&&Dt.trim()!==""?(X.content=Dt,f(X)):!et&&!Xe.trim().startsWith("<")&&(X.content=Ne!==void 0?Xe:X.content+Re,ie.delete(X.id),re.delete(X.id),X.rawContent=void 0,f(X))}}if(k.isComplete){let Ne=(wo=(xs=k.result)==null?void 0:xs.response)!=null?wo:X.content;if(Ne){let dt=ie.get(X.id),Xe=dt!=null?dt:te(Ne);X.rawContent=Xe;let Qe=re.get(X.id),et=null,Jt=!1;if(Qe&&(et=Qe.getExtractedText(),et===null&&(et=Pr(Xe)),et===null)){let It=Qe.processChunk(Xe);It instanceof Promise?(Jt=!0,It.then(Dt=>{var yn;let ln=typeof Dt=="string"?Dt:(yn=Dt==null?void 0:Dt.text)!=null?yn:null;if(ln!==null){let hn=u;hn&&hn.id===X.id&&(hn.content=ln,hn.streaming=!1,re.delete(hn.id),ie.delete(hn.id),f(hn))}})):et=typeof It=="string"?It:(Co=It==null?void 0:It.text)!=null?Co:null}if(!Jt){et!==null&&et.trim()!==""?X.content=et:ie.has(X.id)||(X.content=te(Ne));let It=re.get(X.id);if(It){let Dt=(So=It.close)==null?void 0:So.call(It);Dt instanceof Promise&&Dt.catch(()=>{}),re.delete(X.id)}ie.delete(X.id),X.streaming=!1,f(X)}}}}else if(Ye==="step_complete"){let z=k.stepType,P=k.executionType;if(z==="tool"||P==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((hr=(No=k.id)!=null?No:Z.stepId)!=null?hr:"");if(Ne){let dt=S(Z.toolId,Ne);for(let[Xe,Qe]of D)Xe.startsWith(dt)&&Qe.streaming!==!1&&(Qe.streaming=!1,f(Qe));B.delete(`${Z.toolId}::${Ne}`)}continue}let le=k.stopReason;if(I){if(u!==null){let Xe=u;le&&(Xe.stopReason=le),re.delete(Xe.id),ie.delete(Xe.id),Xe.streaming!==!1&&(Xe.streaming=!1,f(Xe))}let Ne=(Da=k.result)==null?void 0:Da.response,dt=ue;dt&&(le&&(dt.stopReason=le),Ne!=null?Be(dt,Ne):(re.delete(dt.id),ie.delete(dt.id))),ue=null;continue}let X=(ws=k.result)==null?void 0:ws.response,Re=ae();if(le&&(Re.stopReason=le),X!=null){let Ne=re.get(Re.id),dt=!1,Xe=!1;if(Ne){let Qe=Ne.getExtractedText(),et=ie.get(Re.id),Jt=et!=null?et:te(X);if(Re.rawContent=Jt,Qe!==null&&Qe.trim()!=="")Re.content=Qe,dt=!0;else{let It=Pr(Jt);if(It!==null)Re.content=It,dt=!0;else{let Dt=Ne.processChunk(Jt);if(Dt instanceof Promise)Xe=!0,Dt.then(ln=>{var hn;let yn=typeof ln=="string"?ln:(hn=ln==null?void 0:ln.text)!=null?hn:null;if(yn!==null&&yn.trim()!==""){let nn=u;nn&&nn.id===Re.id&&(nn.content=yn,nn.streaming=!1,re.delete(nn.id),ie.delete(nn.id),f(nn))}else{let nn=Ne.getExtractedText(),po=u;po&&po.id===Re.id&&(nn!==null&&nn.trim()!==""?po.content=nn:ie.has(po.id)||(po.content=te(X)),po.streaming=!1,re.delete(po.id),ie.delete(po.id),f(po))}});else{let ln=typeof Dt=="string"?Dt:(Fa=Dt==null?void 0:Dt.text)!=null?Fa:null;if(ln!==null&&ln.trim()!=="")Re.content=ln,dt=!0;else{let yn=Ne.getExtractedText();yn!==null&&yn.trim()!==""&&(Re.content=yn,dt=!0)}}}}}if(!Xe){if(!Re.rawContent){let Qe=ie.get(Re.id);Re.rawContent=Qe!=null?Qe:te(X)}if(!dt&&!ie.has(Re.id)&&(Re.content=te(X)),Ne){let Qe=(Ur=Ne.close)==null?void 0:Ur.call(Ne);Qe instanceof Promise&&Qe.catch(()=>{})}re.delete(Re.id),ie.delete(Re.id),Re.streaming=!1,f(Re)}}else re.delete(Re.id),ie.delete(Re.id),Re.streaming=!1,f(Re)}else if(Ye==="flow_complete"){let z=(yt=k.result)==null?void 0:yt.response;if(I){if(u!==null){let P=u;re.delete(P.id),ie.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}}else if(z!=null){let P=ae(),Z=ie.get(P.id),le=Z!=null?Z:te(z);P.rawContent=le;let X=te(z),Re=re.get(P.id);if(Re){let Xe=Pr(le);if(Xe!==null)X=Xe;else{let Qe=Re.processChunk(le);Qe instanceof Promise&&Qe.then(Jt=>{var Dt;let It=typeof Jt=="string"?Jt:(Dt=Jt==null?void 0:Jt.text)!=null?Dt:null;It!==null&&(P.content=It,P.streaming=!1,f(P))});let et=Re.getExtractedText();et!==null&&(X=et)}}re.delete(P.id),ie.delete(P.id);let Ne=X!==P.content,dt=P.streaming!==!1;Ne&&(P.content=X),P.streaming=!1,(Ne||dt)&&f(P)}else if(u!==null){let P=u;re.delete(P.id),ie.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}n({type:"status",status:"idle"})}else if(Ye==="agent_start")de={executionId:k.executionId,agentId:(Cs=k.agentId)!=null?Cs:"virtual",agentName:(co=k.agentName)!=null?co:"",status:"running",currentIteration:0,maxTurns:(Bn=k.maxTurns)!=null?Bn:1,startedAt:ze(k.startedAt)};else if(Ye==="agent_iteration_start"){if(de&&(de.currentIteration=k.iteration),Ut==="separate"&&k.iteration>1){let z=u;z&&(z.streaming=!1,f(z),Pn.set(k.iteration-1,z),u=null)}}else if(Ye==="agent_turn_start")C=null;else if(Ye==="agent_turn_delta"){if(k.contentType==="text"){let z=ae();z.content+=(Oa=k.delta)!=null?Oa:"",z.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId,agentName:de==null?void 0:de.agentName},C=z,f(z)}else if(k.contentType==="thinking"){let z=(Na=k.turnId)!=null?Na:`agent-think-${k.iteration}`,P=Oe(z);P.reasoning=(zr=P.reasoning)!=null?zr:{id:z,status:"streaming",chunks:[]},P.reasoning.chunks.push((_o=k.delta)!=null?_o:""),P.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId},f(P)}else if(k.contentType==="tool_input"){let z=(_a=k.toolCallId)!=null?_a:w.lastId;if(z){let P=W.get(z);P!=null&&P.toolCall&&(P.toolCall.chunks=(br=P.toolCall.chunks)!=null?br:[],P.toolCall.chunks.push((Ss=k.delta)!=null?Ss:""),f(P))}}}else if(Ye==="agent_turn_complete"){let z=k.turnId;if(z){let le=R.get(z);if(le!=null&&le.reasoning){le.reasoning.status="complete",le.reasoning.completedAt=ze(k.completedAt);let X=(Vo=le.reasoning.startedAt)!=null?Vo:Date.now();le.reasoning.durationMs=Math.max(0,((As=le.reasoning.completedAt)!=null?As:Date.now())-X),le.streaming=!1,f(le)}}let P=k.stopReason,Z=u!=null?u:C;if(P&&Z!==null){let le=k.turnId;(!le||((Jo=Z.agentMetadata)==null?void 0:Jo.turnId)===le)&&(Z.stopReason=P,f(Z))}}else if(Ye==="agent_tool_start"){u&&(u.streaming=!1,f(u),u=null);let z=(Zo=k.toolCallId)!=null?Zo:`agent-tool-${l()}`;we(Y(k),z);let P=Se(z),Z=(Va=P.toolCall)!=null?Va:{id:z,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(fl=($a=k.toolName)!=null?$a:k.name)!=null?fl:Z.name,Z.status="running",k.parameters!==void 0&&(Z.args=k.parameters),Z.startedAt=ze((yr=k.startedAt)!=null?yr:k.timestamp),P.toolCall=Z,P.streaming=!0,P.agentMetadata={executionId:k.executionId,iteration:k.iteration},f(P)}else if(Ye==="agent_tool_delta"){let z=(er=k.toolCallId)!=null?er:w.lastId;if(z){let P=(Ua=W.get(z))!=null?Ua:Se(z);P.toolCall&&(P.toolCall.chunks=(Ts=P.toolCall.chunks)!=null?Ts:[],P.toolCall.chunks.push((tr=k.delta)!=null?tr:""),P.toolCall.status="running",P.streaming=!0,f(P))}}else if(Ye==="agent_tool_complete"){let z=(za=k.toolCallId)!=null?za:w.lastId;if(z){let P=(ks=W.get(z))!=null?ks:Se(z);if(P.toolCall){P.toolCall.status="complete",k.result!==void 0&&(P.toolCall.result=k.result),typeof k.executionTime=="number"&&(P.toolCall.durationMs=k.executionTime),P.toolCall.completedAt=ze((nr=k.completedAt)!=null?nr:k.timestamp),P.streaming=!1,f(P);let Z=Y(k);Z&&w.byCall.delete(Z)}}}else if(Ye==="agent_media"){let z=Array.isArray(k.media)?k.media:[],P=[];for(let Z of z){if(!Z||typeof Z!="object")continue;let le=Z,X=typeof le.type=="string"?le.type:void 0,Re=typeof le.mediaType=="string"?le.mediaType.toLowerCase():"",Ne=null,dt="";if(X==="media"){let Xe=typeof le.data=="string"?le.data:void 0;if(!Xe)continue;dt=Re.length>0?Re:"application/octet-stream",Ne=`data:${dt};base64,${Xe}`}else if(X==="image-url"){let Xe=typeof le.url=="string"?le.url:void 0;if(!Xe)continue;dt=Re,Ne=Xe}else if(X==="file-url"){let Xe=typeof le.url=="string"?le.url:void 0;if(!Xe)continue;dt=Re,Ne=Xe}else continue;if(Ne)if(X==="image-url"||dt.startsWith("image/"))P.push({type:"image",image:Ne,...dt?{mimeType:dt}:{}});else if(dt.startsWith("audio/"))P.push({type:"audio",audio:Ne,mimeType:dt});else if(dt.startsWith("video/"))P.push({type:"video",video:Ne,mimeType:dt});else{let Xe=dt||"application/octet-stream";P.push({type:"file",data:Ne,mimeType:Xe,filename:Th(Xe)})}}if(P.length>0){let Z=l(),le=k.toolCallId,Re={id:`agent-media-${typeof le=="string"&&le.length>0?`${le}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(Re);let Ne=u;Ne&&(Ne.streaming=!1,f(Ne)),u=null,v.current=null}}else if(Ye!=="agent_iteration_complete"){if(Ye==="agent_reflection"||Ye==="agent_reflect"){let z=`agent-reflection-${k.executionId}-${k.iteration}`,P={id:z,role:"assistant",content:(Es=k.reflection)!=null?Es:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(qa=k.reflection)!=null?qa:""]},agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(P)}else if(Ye==="agent_complete"){de&&(de.status=k.success?"complete":"error",de.completedAt=ze(k.completedAt),de.stopReason=k.stopReason);let z=u;z&&(z.streaming=!1,f(z)),n({type:"status",status:"idle"})}else if(Ye==="agent_error"){let z=typeof k.error=="string"?k.error:(ja=($o=k.error)==null?void 0:$o.message)!=null?ja:"Agent execution error";k.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(Ye!=="agent_ping"){if(Ye==="agent_approval_start"){let z=(or=k.approvalId)!=null?or:`approval-${l()}`,P={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ot=de==null?void 0:de.agentId)!=null?Ot:"virtual",executionId:(jr=(qr=k.executionId)!=null?qr:de==null?void 0:de.executionId)!=null?jr:"",toolName:(Ms=k.toolName)!=null?Ms:"",toolType:k.toolType,description:(Ka=k.description)!=null?Ka:`Execute ${(Ro=k.toolName)!=null?Ro:"tool"}`,parameters:k.parameters}};f(P)}else if(Ye==="step_await"&&k.awaitReason==="approval_required"){let z=(Ls=k.approvalId)!=null?Ls:`approval-${l()}`,P={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Is=de==null?void 0:de.agentId)!=null?Is:"virtual",executionId:(Kr=(Ga=k.executionId)!=null?Ga:de==null?void 0:de.executionId)!=null?Kr:"",toolName:(Gr=k.toolName)!=null?Gr:"",toolType:k.toolType,description:(Ya=k.description)!=null?Ya:`Execute ${(vr=k.toolName)!=null?vr:"tool"}`,parameters:k.parameters}};f(P)}else if(Ye==="agent_approval_complete"){let z=k.approvalId;if(z){let Z={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(Xa=k.decision)!=null?Xa:"approved",agentId:(Rs=de==null?void 0:de.agentId)!=null?Rs:"virtual",executionId:(Ws=(Ps=k.executionId)!=null?Ps:de==null?void 0:de.executionId)!=null?Ws:"",toolName:(Bs=k.toolName)!=null?Bs:"",description:(Mn=k.description)!=null?Mn:"",resolvedAt:Date.now()}};f(Z)}}else if(Ye==="artifact_start"||Ye==="artifact_delta"||Ye==="artifact_update"||Ye==="artifact_complete"){if(Ye==="artifact_start"){let z=k.artifactType,P=String(k.id),Z=typeof k.title=="string"?k.title:void 0;if(n({type:"artifact_start",id:P,artifactType:z,title:Z,component:typeof k.component=="string"?k.component:void 0}),ve.set(P,{markdown:"",title:Z}),!G.has(P)){G.add(P);let le={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:Z,artifactType:z,status:"streaming"}})};pe.set(P,le),f(le)}}else if(Ye==="artifact_delta"){let z=String(k.id),P=typeof k.delta=="string"?k.delta:String((Yn=k.delta)!=null?Yn:"");n({type:"artifact_delta",id:z,artDelta:P});let Z=ve.get(z);Z&&(Z.markdown+=P)}else if(Ye==="artifact_update"){let z=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};n({type:"artifact_update",id:String(k.id),props:z,component:typeof k.component=="string"?k.component:void 0})}else if(Ye==="artifact_complete"){let z=String(k.id);n({type:"artifact_complete",id:z});let P=pe.get(z);if(P){P.streaming=!1;try{let Z=JSON.parse((Uo=P.rawContent)!=null?Uo:"{}");if(Z.props){Z.props.status="complete";let le=ve.get(z);le!=null&&le.markdown&&(Z.props.markdown=le.markdown)}P.rawContent=JSON.stringify(Z)}catch{}ve.delete(z),f(P),pe.delete(z)}}}else if(Ye==="transcript_insert"){let z=k.message;if(!z||typeof z!="object")continue;let P=String((ct=z.id)!=null?ct:`msg-${l()}`),Z=z.role,X={id:P,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(f(X),X.rawContent)try{let Re=JSON.parse(X.rawContent),Ne=(Hs=Re==null?void 0:Re.props)==null?void 0:Hs.artifactId;typeof Ne=="string"&&G.add(Ne)}catch{}u=null,v.current=null,re.delete(P),ie.delete(P)}else if(Ye==="error"||Ye==="step_error"||Ye==="dispatch_error"||Ye==="flow_error"){let z=null;if(k.error instanceof Error)z=k.error;else if(Ye==="dispatch_error"){let P=(xr=k.message)!=null?xr:k.error;P!=null&&P!==""&&(z=new Error(String(P)))}else if(Ye==="step_error"||Ye==="flow_error"){let P=k.error;typeof P=="string"&&P!==""?z=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(z=new Error(String((Ao=P.message)!=null?Ao:P)))}else Ye==="error"&&k.error!=null&&k.error!==""&&(z=new Error(String(k.error)));if(z){n({type:"error",error:z});let P=u;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}}}}me.length=0};;){let{done:V,value:Le}=await r.read();if(V)break;a+=s.decode(Le,{stream:!0});let He=a.split(`
10
10
 
11
- `);a=(Fn=Fe.pop())!=null?Fn:"";for(let Oe of Fe){let Ue=Oe.split(`
12
- `),pt="message",rt="";for(let j of Ue)j.startsWith("event:")?pt=j.replace("event:","").trim():j.startsWith("data:")&&(rt+=j.replace("data:","").trim());if(!rt)continue;let Tt;try{Tt=JSON.parse(rt)}catch(j){n({type:"error",error:j instanceof Error?j:new Error("Failed to parse chat stream payload")});continue}let $t=pt!=="message"?pt:(Zn=Tt.type)!=null?Zn:"message";if((je=this.onSSEEvent)==null||je.call(this,$t,Tt),this.parseSSEEvent){S.current=p;let j=await this.handleCustomSSEEvent(Tt,n,S,g,l,L);if(S.current&&S.current!==p&&(p=S.current),j)continue}ue.push($t,Tt),$e()}}ue.flushPending(),$e(),ue.destroy()}};function vi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Zs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var xi="[Image]";function Bl(e){return{type:"text",text:e}}var sm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],gh=["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=[...sm,...gh];function hh(e){return sm.includes(e)||e.startsWith("image/")}function wi(e){return hh(e.type)}async function am(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;wi(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 im(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 bh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function lm(e,t){let n=bh(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 Ci=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 Si=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 ea=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 Si;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=R=>{w||(w=!0,clearTimeout(L),p(new Error(R)))},L=setTimeout(()=>S("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(L),g())},{once:!0}),this.ws.addEventListener("error",()=>{S("WebSocket connection failed to "+m+"."+u)},{once:!0}),this.ws.addEventListener("close",R=>{if(!R.wasClean&&!w){let I=R.code!==1006?` (code ${R.code})`:"";S("WebSocket connection failed"+I+"."+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 Ci(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 Lr=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 ta(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ea(e.runtype);case"browser":if(!Lr.isSupported())throw new Error("Browser speech recognition not supported");return new Lr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function cm(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ta({type:"runtype",runtype:e.runtype});if(Lr.isSupported())return ta({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 cm(e),!0}catch{return!1}}function dm(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=(Fn=He.pop())!=null?Fn:"";for(let De of He){let Ve=De.split(`
12
+ `),mt="message",at="";for(let j of Ve)j.startsWith("event:")?mt=j.replace("event:","").trim():j.startsWith("data:")&&(at+=j.replace("data:","").trim());if(!at)continue;let Pt;try{Pt=JSON.parse(at)}catch(j){n({type:"error",error:j instanceof Error?j:new Error("Failed to parse chat stream payload")});continue}let jt=mt!=="message"?mt:(to=Pt.type)!=null?to:"message";if((qe=this.onSSEEvent)==null||qe.call(this,jt,Pt),this.parseSSEEvent){v.current=u;let j=await this.handleCustomSSEEvent(Pt,n,v,f,l,M);if(v.current&&v.current!==u&&(u=v.current),j)continue}be.push(jt,Pt),_e()}}be.flushPending(),_e(),be.destroy()}};function wi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function sa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ci="[Image]";function _l(e){return{type:"text",text:e}}var gm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Mh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],qo=[...gm,...Mh];function Lh(e){return gm.includes(e)||e.startsWith("image/")}function Si(e){return Lh(e.type)}async function fm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Si(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 hm(e,t=qo,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 Ih(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function bm(e,t){let n=Ih(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ai=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let 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 aa=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=...`,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=I=>{C||(C=!0,clearTimeout(M),u(new Error(I)))},M=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+m+"."+p)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!C){let R=I.code!==1006?` (code ${I.code})`:"";v("WebSocket connection failed"+R+"."+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 Ai(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,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 Wr=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 ia(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new aa(e.runtype);case"browser":if(!Wr.isSupported())throw new Error("Browser speech recognition not supported");return new Wr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ym(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ia({type:"runtype",runtype:e.runtype});if(Wr.isSupported())return ia({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vl(e){try{return ym(e),!0}catch{return!1}}function vm(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 na=e=>({isError:!0,content:[{type:"text",text:e}]}),pm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ai=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)&&Jr(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 Js(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=ta(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 L=(S=this.pendingVoiceAssistantMessageId)!=null?S:(w=[...this.messages].reverse().find(R=>R.role==="assistant"))==null?void 0:w.id;L&&this.ttsSpokenMessageIds.add(L)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var 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 Js(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"?vi():n==="assistant"?Zs():`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"?vi():r==="assistant"?Zs():`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=vi(),s=Zs(),a={id:r,role:"user",content:o||xi,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 L=dm(w,this.config.errorMessage);if(L){let R={id:s,role:"assistant",createdAt:new Date().toISOString(),content:L,sequence:this.nextSequence()};this.appendMessage(R)}}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=Zs();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=dm(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,L,R,I,D,F,B;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 E=typeof((L=x[0])==null?void 0:L.question)=="string"?x[0].question:"";E&&(a={[E]:n})}}this.markAskUserQuestionResolved(t,a),(R=this.abortController)==null||R.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof n=="string"?n:Object.entries(n).map(([x,E])=>`${x}: ${Array.isArray(E)?E.join(", "):E}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((x,E)=>{let C=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!C)return;let k=v[C],O=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let x=await v.json().catch(()=>null);throw new Error((D=x==null?void 0:x.error)!=null?D:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(B=(F=this.callbacks).onError)==null||B.call(F,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}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 F,B,v,x,E,C,k;let g=(F=u.toolCall)==null?void 0:F.name,p=(B=u.toolCall)==null?void 0:B.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),L=new AbortController;this.webMcpResolveControllers.add(L),r.push(L);let R=(x=(v=u.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?x:g,I=this.client.executeWebMcpToolCall(g,(E=u.toolCall)==null?void 0:E.args,L.signal),D;if(!I)D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{D=await I}catch(O){let U=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return U||(k=(C=this.callbacks).onError)==null||k.call(C,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(u,na(U?"Aborted by cancel()":pm(O)),S),this.webMcpInflightKeys.delete(w),null}return L.signal.aborted?(this.markWebMcpToolComplete(u,na("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:R,output:D,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,na("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,L,R,I,D,F,B,v,x,E;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){(R=(L=this.callbacks).onError)==null||R.call(L,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(k){(D=(I=this.callbacks).onError)==null||D.call(I,k instanceof Error?k:new Error(String(k)))}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=(F=t.toolCall)==null?void 0:F.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,na("Aborted by cancel()"),a);return}let k=(v=(B=t.agentMetadata)==null?void 0:B.webMcpToolCallId)!=null?v:o;u="resume",await this.resumeWithToolOutput(n,k,C,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,C,a,g)},signal:d})}catch(C){let k=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));(u==="execute"||k||d.aborted)&&this.markWebMcpToolComplete(t,na(k||d.aborted?"Aborted by cancel()":pm(C)),a),k||(E=(x=this.callbacks).onError)==null||E.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,L,R,I,D;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&&Jr(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let F=`${d}:${l}`,B=this.webMcpInflightKeys.has(F),v=this.webMcpResolvedKeys.has(F),x=(S=r.toolCall)==null?void 0:S.name,E=((L=r.agentMetadata)==null?void 0:L.executionId)===d&&((R=r.toolCall)==null?void 0:R.id)===l&&x!==void 0&&Jr(x)&&((I=r.toolCall)==null?void 0:I.status)==="complete";(B||v||E)&&(a.agentMetadata={...(D=a.agentMetadata)!=null?D:{},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},Mo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var A=require("lucide"),yh={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},ke=(e,t=24,n="currentColor",o=2)=>{let r=yh[e];return r?vh(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 vh(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 Ti={allowedTypes:$o,maxFileSize:10*1024*1024,maxFiles:4};function xh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function wh(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 oa=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ti.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ti.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Ti.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ti.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let m=im(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 am(l),g=wi(l)?URL.createObjectURL(l):null,p={id:xh(),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=wi(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=wh(t.file.type),d=ke(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=lm(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=ke("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var um=require("idiomorph"),ki=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;um.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Ei={index:-1,draft:""};function mm(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:{...Ei}}}function fm(e,t){var n,o,r,s,a,i,d,l,m,u,g,p,w,S,L,R,I,D,F,B,v,x,E,C,k,O,U,K,fe,ae,ge,le,ye,Ne,xe,J,Ie,X;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(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:"",(L=(S=e.toolCall)==null?void 0:S.name)!=null?L:"",(D=(I=(R=e.toolCall)==null?void 0:R.chunks)==null?void 0:I.length)!=null?D:0,(x=(v=(B=(F=e.toolCall)==null?void 0:F.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?x:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(C=e.toolCall)!=null&&C.args?JSON.stringify(e.toolCall.args).length:0,(U=(O=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:O.length)!=null?U:0,(ge=(ae=(fe=(K=e.reasoning)==null?void 0:K.chunks)==null?void 0:fe[e.reasoning.chunks.length-1])==null?void 0:ae.length)!=null?ge:0,(xe=(Ne=(ye=(le=e.reasoning)==null?void 0:le.chunks)==null?void 0:ye[e.reasoning.chunks.length-1])==null?void 0:Ne.slice(-32))!=null?xe:"",(Ie=(J=e.contentParts)==null?void 0:J.length)!=null?Ie:0,(X=e.stopReason)!=null?X:"",t].join("\0")}function gm(){return new Map}function hm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function bm(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function ym(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Mi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ra(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function sa(e,t){return ra(e)-e.scrollTop<=t}function Li(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 Ii(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},bn=1e5,sr=bn+1;var aa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ch=["pre","code","a","script","style"],Ri=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:aa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:aa.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:aa.speed,duration:(r=e==null?void 0:e.duration)!=null?r:aa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:aa.buffer}},Sh=[{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"}],xm=new Map;for(let e of Sh)xm.set(e.name,e);var ia=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=xm.get(e))!=null?o:null},Pi=(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},Ah=(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},Th=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Dl=/\s/,kh=(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},Eh=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(Dl.test(s[i])){let l=i;for(;l<s.length&&Dl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let m=i;for(;m<s.length&&!Dl.test(s[m]);)l.appendChild(Ah(o,s[m],t,n.value)),n.value+=1,m+=1;a.appendChild(l),i=m}r.replaceChild(a,e)},Mh=(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(Th(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},la=(e,t,n,o)=>{var u,g;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((u=o==null?void 0:o.skipTags)!=null?u:Ch).map(p=>p.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)kh(d,s)||i.push(d),d=a.nextNode();let l={value:(g=o==null?void 0:o.startIndex)!=null?g:0},m=t==="char"?Eh:Mh;for(let p of i)m(p,n,l);return r.innerHTML},Wi=(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},ca=(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},vm=new WeakMap,Lh=(e,t)=>{var s;if(!e.styles)return;let n=vm.get(t);if(n||(n=new Set,vm.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)},Fl=new WeakMap,Ih=(e,t)=>{if(!e.onAttach)return;let n=Fl.get(t);if(n||(n=new Map,Fl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},wm=e=>{let t=Fl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ol=(e,t)=>{Lh(e,t),Ih(e,t)};function Nl(e,t=bn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var da=0,ar=null;function _l(e=document){var n;if(da++,da===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;ar={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,da=Math.max(0,da-1),da===0&&ar)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=ar.originalOverflow,r.style.position=ar.originalPosition,r.style.top=ar.originalTop,r.style.width=ar.originalWidth,s.scrollTo(0,ar.scrollY),ar=null}}}var Bi={side:"right",width:"420px",animate:!0,reveal:"resize"},un=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},pa=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Lo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Bi.side,width:(r=t==null?void 0:t.width)!=null?r:Bi.width,animate:(s=t==null?void 0:t.animate)!=null?s:Bi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Bi.reveal}};var Co={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var ua=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:o}var la=e=>({isError:!0,content:[{type:"text",text:e}]}),xm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ki=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)&&rs(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 ra(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 Vl((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=ia(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 M=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:C.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,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 ra(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"?wi():n==="assistant"?sa():`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"?wi():r==="assistant"?sa():`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=wi(),s=sa(),a={id:r,role:"user",content:o||Ci,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 M=vm(C,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,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=sa();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=vm(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 M=null;if(v instanceof Response){if(!v.ok){let I=await v.json().catch(()=>null);throw new Error((f=I==null?void 0:I.error)!=null?f:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);M?await this.connectStream(M,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(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,M,I,R,W,D,B;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 E=typeof((M=w[0])==null?void 0:M.question)=="string"?w[0].question:"";E&&(a={[E]:n})}}this.markAskUserQuestionResolved(t,a),(I=this.abortController)==null||I.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(R=t.toolCall)==null?void 0:R.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let x=typeof n=="string"?n:Object.entries(n).map(([w,E])=>`${w}: ${Array.isArray(E)?E.join(", "):E}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:x,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let x=a!=null?a:{};l.forEach((w,E)=>{let S=typeof(w==null?void 0:w.question)=="string"?w.question:"";if(!S)return;let T=x[S],_=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,role:"user",content:_||"*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((W=w==null?void 0:w.error)!=null?W:`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||(B=(D=this.callbacks).onError)==null||B.call(D,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 D,B,x,w,E,S,T;let f=(D=p.toolCall)==null?void 0:D.name,u=(B=p.toolCall)==null?void 0:B.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),M=new AbortController;this.webMcpResolveControllers.add(M),r.push(M);let I=(w=(x=p.agentMetadata)==null?void 0:x.webMcpToolCallId)!=null?w:f,R=this.client.executeWebMcpToolCall(f,(E=p.toolCall)==null?void 0:E.args,M.signal),W;if(!R)W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{W=await R}catch(_){let U=_ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"));return U||(T=(S=this.callbacks).onError)==null||T.call(S,_ instanceof Error?_:new Error(String(_))),this.markWebMcpToolComplete(p,la(U?"Aborted by cancel()":xm(_)),v),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(p,la("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:I,output:W,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,la("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,M,I,R,W,D,B,x,w,E;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){(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 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(T){(W=(R=this.callbacks).onError)==null||W.call(R,T instanceof Error?T:new Error(String(T)))}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=(D=t.toolCall)==null?void 0:D.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,la("Aborted by cancel()"),a);return}let T=(x=(B=t.agentMetadata)==null?void 0:B.webMcpToolCallId)!=null?x:o;p="resume",await this.resumeWithToolOutput(n,T,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,f)},signal:d})}catch(S){let T=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(p==="execute"||T||d.aborted)&&this.markWebMcpToolComplete(t,la(T||d.aborted?"Aborted by cancel()":xm(S)),a),T||(E=(w=this.callbacks).onError)==null||E.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,M,I,R,W;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&&rs(i)&&d&&l&&((C=n.agentMetadata)==null?void 0:C.awaitingLocalTool)===!0){let D=`${d}:${l}`,B=this.webMcpInflightKeys.has(D),x=this.webMcpResolvedKeys.has(D),w=(v=r.toolCall)==null?void 0:v.name,E=((M=r.agentMetadata)==null?void 0:M.executionId)===d&&((I=r.toolCall)==null?void 0:I.id)===l&&w!==void 0&&rs(w)&&((R=r.toolCall)==null?void 0:R.status)==="complete";(B||x||E)&&(a.agentMetadata={...(W=a.agentMetadata)!=null?W:{},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},Wo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var A=require("lucide"),Rh={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},Me=(e,t=24,n="currentColor",o=2)=>{let r=Rh[e];return r?Ph(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 Ph(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 Ei={allowedTypes:qo,maxFileSize:10*1024*1024,maxFiles:4};function Wh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Bh(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 ca=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ei.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ei.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Ei.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ei.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let m=hm(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 fm(l),f=Si(l)?URL.createObjectURL(l):null,u={id:Wh(),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=Si(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=Bh(t.file.type),d=Me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=bm(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=Me("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var wm=require("idiomorph"),Mi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;wm.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Li={index:-1,draft:""};function Cm(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Li}}}function Sm(e,t){var n,o,r,s,a,i,d,l,m,p,f,u,C,v,M,I,R,W,D,B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we,K,pe,G;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:"",(M=(v=e.toolCall)==null?void 0:v.name)!=null?M:"",(W=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?W:0,(w=(x=(B=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:x.slice(-32))!=null?w:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,(U=(_=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:_.length)!=null?U:0,(ae=(fe=(he=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:fe.length)!=null?ae:0,(we=(Oe=(ye=(Ee=e.reasoning)==null?void 0:Ee.chunks)==null?void 0:ye[e.reasoning.chunks.length-1])==null?void 0:Oe.slice(-32))!=null?we:"",(pe=(K=e.contentParts)==null?void 0:K.length)!=null?pe:0,(G=e.stopReason)!=null?G:"",t].join("\0")}function Am(){return new Map}function Tm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function km(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Em(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ii(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function da(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function pa(e,t){return da(e)-e.scrollTop<=t}function Ri(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,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 Pi(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 wn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cn=1e5,lr=Cn+1;var ua={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Hh=["pre","code","a","script","style"],Wi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:ua.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ua.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:ua.speed,duration:(r=e==null?void 0:e.duration)!=null?r:ua.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ua.buffer}},Dh=[{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"}],Lm=new Map;for(let e of Dh)Lm.set(e.name,e);var ma=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Lm.get(e))!=null?o:null},Bi=(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},Fh=(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},Oh=(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},$l=/\s/,Nh=(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},_h=(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($l.test(s[i])){let l=i;for(;l<s.length&&$l.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&&!$l.test(s[m]);)l.appendChild(Fh(o,s[m],t,n.value)),n.value+=1,m+=1;a.appendChild(l),i=m}r.replaceChild(a,e)},Vh=(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(Oh(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},ga=(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:Hh).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Nh(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},m=t==="char"?_h:Vh;for(let u of i)m(u,n,l);return r.innerHTML},Hi=(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},fa=(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},Mm=new WeakMap,$h=(e,t)=>{var s;if(!e.styles)return;let n=Mm.get(t);if(n||(n=new Set,Mm.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)},Ul=new WeakMap,Uh=(e,t)=>{if(!e.onAttach)return;let n=Ul.get(t);if(n||(n=new Map,Ul.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Im=e=>{let t=Ul.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},zl=(e,t)=>{$h(e,t),Uh(e,t)};function ql(e,t=Cn){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 ha=0,cr=null;function jl(e=document){var n;if(ha++,ha===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;cr={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,ha=Math.max(0,ha-1),ha===0&&cr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=cr.originalOverflow,r.style.position=cr.originalPosition,r.style.top=cr.originalTop,r.style.width=cr.originalWidth,s.scrollTo(0,cr.scrollY),cr=null}}}var Di={side:"right",width:"420px",animate:!0,reveal:"resize"},bn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},ba=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Bo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Di.side,width:(r=t==null?void 0:t.width)!=null?r:Di.width,animate:(s=t==null?void 0:t.animate)!=null?s:Di.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Di.reveal}};var Mo={"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 ya=(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 na=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 D,F,B,v,x,E,C,k,O,U,K,fe,ae,ge;let a=(D=s.launcher)!=null?D:{},i=un(s),d=n.querySelector("[data-role='launcher-title']");if(d){let le=(F=a.title)!=null?F:"Chat Assistant";d.textContent=le,d.setAttribute("title",le)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let le=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=le,l.setAttribute("title",le)}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 le=(v=a.agentIconSize)!=null?v:"40px";if(u.style.height=le,u.style.width=le,u.innerHTML="",a.agentIconName){let ye=parseFloat(le)||24,Ne=ke(a.agentIconName,ye*.6,"var(--persona-text-inverse, #ffffff)",2);Ne?(u.appendChild(Ne),u.style.display=""):(u.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let le=(C=a.agentIconSize)!=null?C:"40px";g.style.height=le,g.style.width=le,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let p=n.querySelector("[data-role='launcher-call-to-action-icon']");if(p){let le=(k=a.callToActionIconSize)!=null?k:"32px";p.style.height=le,p.style.width=le,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 ye=0;if(a.callToActionIconPadding?(p.style.boxSizing="border-box",p.style.padding=a.callToActionIconPadding,ye=(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 Ne=parseFloat(le)||24,xe=Math.max(Ne-ye,8),J=ke(a.callToActionIconName,xe,"currentColor",2);J?p.appendChild(J):p.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else p.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}let w=a.position&&Co[a.position]?Co[a.position]:Co["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",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?L:`${S} ${w}`,i||(n.style.zIndex=String((K=a.zIndex)!=null?K:bn));let R="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(fe=a.border)!=null?fe:R,n.style.boxShadow=(ae=a.shadow)!=null?ae: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 Rh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Hi=(e,t={})=>{var S,L,R,I,D,F;let{showClose:n=!0,wrapperClassName:o=Rh,buttonSize:r,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(L=r!=null?r:a.closeButtonSize)!=null?L:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let m=(R=a.closeButtonTooltipText)!=null?R:"Close chat",u=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let g=(D=a.closeButtonIconName)!=null?D:"x",p=(F=a.closeButtonIconText)!=null?F:"\xD7";l.style.color=a.closeButtonColor||Ln.actionIconColor;let w=ke(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 B=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${B} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&m){let B=null,v=()=>{if(B)return;let E=l.ownerDocument,C=E.body;if(!C)return;B=Mo(E,"div","persona-clear-chat-tooltip"),B.textContent=m;let k=Mo(E,"div");k.className="persona-clear-chat-tooltip-arrow",B.appendChild(k);let O=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(sr),B.style.left=`${O.left+O.width/2}px`,B.style.top=`${O.top-8}px`,B.style.transform="translate(-50%, -100%)",C.appendChild(B)},x=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",x),l.addEventListener("focus",v),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",v),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},Ph="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Di=(e,t={})=>{var B,v,x,E,C,k,O,U,K,fe,ae,ge,le;let{wrapperClassName:n=Ph,buttonSize:o,iconSize:r="20px"}=t,a=(v=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?v:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(C=a.iconColor)!=null?C:"",m=(k=a.backgroundColor)!=null?k:"",u=(O=a.borderWidth)!=null?O:"",g=(U=a.borderColor)!=null?U:"",p=(K=a.borderRadius)!=null?K:"",w=(fe=a.paddingX)!=null?fe:"",S=(ae=a.paddingY)!=null?ae:"",L=(ge=a.tooltipText)!=null?ge:"Clear chat",R=(le=a.showTooltip)!=null?le:!0,I=b("div",n),D=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");D.style.height=i,D.style.width=i,D.type="button",D.setAttribute("aria-label",L),D.style.color=l||Ln.actionIconColor;let F=ke(d,r,"currentColor",1);if(F&&(F.style.display="block",D.appendChild(F)),m&&(D.style.backgroundColor=m,D.classList.remove("hover:persona-bg-gray-100")),u||g){let ye=u||"0px",Ne=g||"transparent";D.style.border=`${ye} solid ${Ne}`,D.classList.remove("persona-border-none")}if(p&&(D.style.borderRadius=p,D.classList.remove("persona-rounded-full")),w&&(D.style.paddingLeft=w,D.style.paddingRight=w),S&&(D.style.paddingTop=S,D.style.paddingBottom=S),I.appendChild(D),R&&L){let ye=null,Ne=()=>{if(ye)return;let J=D.ownerDocument,Ie=J.body;if(!Ie)return;ye=Mo(J,"div","persona-clear-chat-tooltip"),ye.textContent=L;let X=Mo(J,"div");X.className="persona-clear-chat-tooltip-arrow",ye.appendChild(X);let we=D.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(sr),ye.style.left=`${we.left+we.width/2}px`,ye.style.top=`${we.top-8}px`,ye.style.transform="translate(-50%, -100%)",Ie.appendChild(ye)},xe=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};I.addEventListener("mouseenter",Ne),I.addEventListener("mouseleave",xe),D.addEventListener("focus",Ne),D.addEventListener("blur",xe),I._cleanupTooltip=()=>{xe(),I.removeEventListener("mouseenter",Ne),I.removeEventListener("mouseleave",xe),D.removeEventListener("focus",Ne),D.removeEventListener("blur",xe)}}return{button:D,wrapper:I}};var Ln={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ir=e=>{var B,v,x,E,C,k,O,U,K,fe,ae,ge,le,ye,Ne,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=(B=t==null?void 0:t.launcher)!=null?B:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(E=r.headerIconHidden)!=null?E:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let J=parseFloat(s)||24,Ie=ke(d,J*.6,"currentColor",1);Ie?l.replaceChildren(Ie):l.textContent=(k=(C=t==null?void 0:t.launcher)==null?void 0:C.agentIconText)!=null?k:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.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=(K=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?K:"\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=Ln.titleColor,u.textContent=(ae=(fe=t==null?void 0:t.launcher)==null?void 0:fe.title)!=null?ae:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Ln.subtitleColor,g.textContent=(le=(ge=t==null?void 0:t.launcher)==null?void 0:ge.subtitle)!=null?le:"Here to help you get answers fast",m.append(u,g),i?o.append(m):o.append(l,m);let p=(ye=r.clearChat)!=null?ye:{},w=(Ne=p.enabled)!=null?Ne:!0,S=(xe=p.placement)!=null?xe:"inline",L=null,R=null;if(w){let Ie=Di(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=Ie.button,R=Ie.wrapper,S==="top-right"&&(R.style.right="48px"),S==="inline"&&o.appendChild(R)}let I=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:D,wrapper:F}=Hi(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(F),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:D,closeButtonWrapper:F,clearChatButton:L,clearChatButtonWrapper:R}},ma=(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 ts(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(sr)):(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 L=document.createElement("hr");a.appendChild(L)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",p.id),p.destructive&&w.setAttribute("data-destructive",""),p.icon){let L=ke(p.icon,16,"currentColor",1.5);L&&w.appendChild(L)}let S=document.createElement("span");S.textContent=p.label,w.appendChild(S),w.addEventListener("click",L=>{L.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 yn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=ke(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 Vl(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=ke(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 Cm(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=ke(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,L;l.style.backgroundColor=(S=d.background)!=null?S:"",l.style.borderColor=(L=d.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=ts({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 L=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"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 Wh=e=>{var o;let t=Ir({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 Bh(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=ke(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=ts({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 Hh=e=>{var I,D,F,B,v,x,E,C,k;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=Cm({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Ln.titleColor,m=(F=l.querySelector(".persona-combo-btn-label"))!=null?F:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Ln.titleColor,m.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(m),Bh(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let U=r.onTitleClick;l.addEventListener("click",K=>{K.target.closest("button")||U()}),l.addEventListener("keydown",K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),U())})}let O=r==null?void 0:r.titleRowHover;O&&(l.style.borderRadius=(x=O.borderRadius)!=null?x:"10px",l.style.padding=(E=O.padding)!=null?E:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var U,K;l.style.backgroundColor=(U=O.background)!=null?U:"",l.style.borderColor=(K=O.border)!=null?K:""}),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||Ln.actionIconColor;let w=(k=a.closeButtonIconName)!=null?k:"x",S=ke(w,"28px","currentColor",1);S?p.appendChild(S):p.textContent="\xD7",o&&p.addEventListener("click",o),g.appendChild(p),i.appendChild(g);let L=b("div");L.style.display="none";let R=b("span");return R.style.display="none",{header:i,iconHolder:L,headerTitle:m,headerSubtitle:R,closeButton:p,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Sm={default:Wh,minimal:Hh},Dh=e=>{var t;return(t=Sm[e])!=null?t:Sm.default},Fi=(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=Dh(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 Oi=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}},Ni=e=>{var B,v,x,E,C,k,O,U,K,fe,ae,ge;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(v=t.useIcon)!=null?v:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(C=t.tooltipText)!=null?C:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=(U=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?U:"Send",l=(fe=(K=e==null?void 0:e.copy)==null?void 0:K.stopButtonLabel)!=null?fe:"Stop",m=(ae=t.showTooltip)!=null?ae:!1,u=(ge=t.size)!=null?ge:"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 L=null,R=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 le=parseFloat(u)||24,ye=(p==null?void 0:p.trim())||"currentColor";r?(L=ke(r,le,ye,2),L?S.appendChild(L):S.textContent=o):S.textContent=o,R=ke(s,le,ye,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 I=null;m&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,w.appendChild(I)),S.setAttribute("aria-label",a),w.appendChild(S);let D="send";return{button:S,wrapper:w,setMode:le=>{if(le===D)return;D=le;let ye=le==="stop"?i:a;if(S.setAttribute("aria-label",ye),I&&(I.textContent=ye),n){if(L&&R){let Ne=le==="stop"?R:L;S.replaceChildren(Ne)}}else S.textContent=le==="stop"?l:d}}},_i=e=>{var I,D,F,B,v,x,E,C,k,O,U,K;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((D=t.provider)==null?void 0:D.type)==="runtype";if(!(o||r))return null;let a=(B=(F=e==null?void 0:e.sendButton)==null?void 0:F.size)!=null?B:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=t.iconName)!=null?v:"mic",m=(x=t.iconSize)!=null?x:a,u=parseFloat(m)||24,g=(C=t.backgroundColor)!=null?C:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,p=(O=t.iconColor)!=null?O:(k=e==null?void 0:e.sendButton)==null?void 0:k.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=ke(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 L=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((K=t.showTooltip)!=null?K:!1)&&L){let fe=b("div","persona-send-button-tooltip");fe.textContent=L,i.appendChild(fe)}return{button:d,wrapper:i}},Vi=e=>{var w,S,L,R,I,D,F,B;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(L=(S=e==null?void 0:e.sendButton)==null?void 0:S.size)!=null?L:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((R=t.allowedTypes)!=null?R:$o).join(","),r.multiple=((I=t.maxFiles)!=null?I:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(D=t.buttonTooltipText)!=null?D:"Attach file");let i=(F=t.buttonIconName)!=null?F:"paperclip",d=n,l=parseFloat(d)||40,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=ke(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=(B=t.buttonTooltipText)!=null?B:"Attach file",p=b("div","persona-send-button-tooltip");return p.textContent=g,s.appendChild(p),{button:a,wrapper:s,input:r,previewsContainer:o}},$i=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},Ui=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var zi=e=>{var w,S,L,R,I,D;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=Ui(),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}=Oi(t);a();let i=Ni(t),d=_i(t),l=Vi(t),m=$i(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",F=>{F.target!==i.button&&F.target!==i.wrapper&&F.target!==(d==null?void 0:d.button)&&F.target!==(d==null?void 0:d.wrapper)&&F.target!==(l==null?void 0:l.button)&&F.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,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:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(R=l==null?void 0:l.wrapper)!=null?R:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:u,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Am=()=>{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=ke("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=ke("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Tm=e=>{var w,S,L,R,I,D;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Ui();o.style.display="none";let r=$i(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Oi(t);s.style.maxHeight="100px",a();let i=Ni(t),d=_i(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",F=>{F.target!==i.button&&F.target!==i.wrapper&&F.target!==(d==null?void 0:d.button)&&F.target!==(d==null?void 0:d.wrapper)&&F.target!==(l==null?void 0:l.button)&&F.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&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:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(R=l==null?void 0:l.wrapper)!=null?R:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:p,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var km=e=>{var m,u,g,p,w,S,L,R,I,D,F,B,v,x,E,C,k;let t=(u=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?u:!0,n=un(e);if(pa(e)){let O=(p=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?p:{},U=b("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(w=O.expandedSize)!=null?w:"anchored",U.style.zIndex=String((L=(S=e==null?void 0:e.launcher)==null?void 0:S.zIndex)!=null?L:bn);let K=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");K.style.width="100%",U.appendChild(K);let fe=b("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(R=O.expandedSize)!=null?R:"anchored",fe.style.zIndex=String((D=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?D:bn),{wrapper:U,panel:K,pillRoot:fe}}if(n){let O=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(U),{wrapper:O,panel:U}}if(!t){let O=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),K=(B=(F=e==null?void 0:e.launcher)==null?void 0:F.width)!=null?B:"100%";return O.style.width=K,U.style.width="100%",O.appendChild(U),{wrapper:O,panel:U}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&Co[r.position]?Co[r.position]:Co["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:bn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?k:e==null?void 0:e.launcherWidth,l=d!=null?d:lo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Fh=(e,t)=>{var F,B,v,x,E,C,k,O,U;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Hi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(B=(F=e==null?void 0:e.launcher)==null?void 0:F.clearChat)==null?void 0:B.enabled)!=null?v:!0,a=null,i=null;if(s){let K=Di(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=K.button,i=K.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=(E=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?E:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(k=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",m.append(u,g);let p=b("div","persona-flex persona-flex-col persona-gap-3"),w=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;w&&(p.style.maxWidth=w,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,p);let L=b("div","persona-composer-overlay persona-pointer-events-none");L.setAttribute("data-persona-composer-overlay",""),L.style.position="absolute",L.style.left="0",L.style.right="0",L.style.bottom="0",L.style.zIndex="20";let R=Tm({config:e}),{root:I,textNode:D}=Am();return n.append(d,r,l,L),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:p,composerOverlay:L,suggestions:R.suggestions,textarea:R.textarea,sendButton:R.sendButton,sendButtonWrapper:R.sendButtonWrapper,micButton:R.micButton,micButtonWrapper:R.micButtonWrapper,composerForm:R.composerForm,statusText:R.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:R.footer,attachmentButton:R.attachmentButton,attachmentButtonWrapper:R.attachmentButtonWrapper,attachmentInput:R.attachmentInput,attachmentPreviewsContainer:R.attachmentPreviewsContainer,actionsRow:R.actionsRow,leftActions:R.leftActions,rightActions:R.rightActions,setSendButtonMode:R.setSendButtonMode,peekBanner:I,peekTextNode:D}},Em=(e,t=!0)=>{var L,R,I,D,F,B,v,x,E;if(pa(e))return Fh(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(L=e==null?void 0:e.layout)==null?void 0:L.header,r=((R=e==null?void 0:e.layout)==null?void 0:R.showHeader)!==!1,s=o?Fi(e,o,{showClose:t}):Ir({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=un(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(D=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?D:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(B=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeSubtitle)!=null?B:"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=zi({config:e}),w=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?ma(n,s,e):(s.header.style.display="none",ma(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 Oh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Nh=(e,t)=>{if(!e)return null;let n=Oh(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},_h=(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},Vh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},$l=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ul=320,Lm=320,$h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Uh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),qh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),jh=(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=`${Ul}px`,l.style.maxHeight=`${Lm}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}),Vh(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}},Kh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!$l(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ul}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Gh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!$l(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ul}px`,r.style.maxHeight=`${Lm}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}},Yh=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!$l(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},fa=()=>{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},Xh=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:fa};if(t){let r=t(o);if(r!==null)return r}return fa()},Qh=(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},Mm=(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},Jh=(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},Zh=(e,t,n)=>{var p,w,S,L,R,I;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 D=b("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let a=(L=t.visibility)!=null?L:"hover",i=(R=t.align)!=null?R:"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],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=(D,F,B)=>{let v=yn({icon:D,label:F,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",B),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},zl=(e,t,n,o,r,s)=>{var J,Ie,X,we,Ae,pe,Ce,qe,ne,oe,se,ot,ve,ce,ze,De,de;let a=n!=null?n:{},i=(J=a.layout)!=null?J:"bubble",d=a.avatar,l=a.timestamp,m=(Ie=d==null?void 0:d.show)!=null?Ie:!1,u=(X=l==null?void 0:l.show)!=null?X:!1,g=(we=d==null?void 0:d.position)!=null?we:"left",p=(Ae=l==null?void 0:l.position)!=null?Ae:"below",w=Jh(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 L=$h(e),R=(Ce=(pe=e.content)==null?void 0:pe.trim())!=null?Ce:"",D=L.length>0&&R===xi,F=Ri((ne=(qe=s==null?void 0:s.widgetConfig)==null?void 0:qe.features)==null?void 0:ne.streamAnimation),B=(ot=(se=(oe=s==null?void 0:s.widgetConfig)==null?void 0:oe.features)==null?void 0:se.streamAnimation)==null?void 0:ot.plugins,v=e.role==="assistant"&&F.type!=="none"?ia(F.type,B):null,x=e.role==="assistant"&&((ve=v==null?void 0:v.isAnimating)==null?void 0:ve.call(v,e))===!0,E=e.role==="assistant"&&v!==null&&(!!e.streaming||x);E&&(v!=null&&v.bubbleClass)&&S.classList.add(v.bubbleClass);let C=document.createElement("div");C.classList.add("persona-message-content"),E&&v&&(v.containerClass&&C.classList.add(v.containerClass),C.style.setProperty("--persona-stream-step",`${F.speed}ms`),C.style.setProperty("--persona-stream-duration",`${F.duration}ms`));let k=E?Pi((ce=e.content)!=null?ce:"",F.buffer,v,e,!!e.streaming):(ze=e.content)!=null?ze:"",O=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=O;E&&(v==null?void 0:v.wrap)==="char"?U=la(O,"char",e.id,{skipTags:v.skipTags}):E&&(v==null?void 0:v.wrap)==="word"&&(U=la(O,"word",e.id,{skipTags:v.skipTags}));let K=null;if(D?(K=document.createElement("div"),K.innerHTML=U,K.style.display="none",C.appendChild(K)):C.innerHTML=U,E&&(v!=null&&v.useCaret)&&!D&&R){let Y=Wi(),$e=C.querySelectorAll(".persona-stream-char, .persona-stream-word"),Mt=$e[$e.length-1];if(Mt!=null&&Mt.parentNode)Mt.parentNode.insertBefore(Y,Mt.nextSibling);else{let ue=C.lastElementChild;ue?ue.appendChild(Y):C.appendChild(Y)}}if(u&&p==="inline"&&e.createdAt){let Y=Mm(e,l);Y.classList.add("persona-ml-2","persona-inline"),C.appendChild(Y)}if(L.length>0){let Y=jh(L,!D&&!!R,()=>{D&&K&&(K.style.display="")});Y?S.appendChild(Y):D&&K&&(K.style.display="")}let fe=Uh(e);if(fe.length>0){let Y=Kh(fe);Y&&S.appendChild(Y)}let ae=zh(e);if(ae.length>0){let Y=Gh(ae);Y&&S.appendChild(Y)}let ge=qh(e);if(ge.length>0){let Y=Yh(ge);Y&&S.appendChild(Y)}if(S.appendChild(C),u&&p==="below"&&e.createdAt){let Y=Mm(e,l);Y.classList.add("persona-mt-1"),S.appendChild(Y)}let le=e.role==="assistant"?Nh(e.stopReason,(de=(De=s==null?void 0:s.widgetConfig)==null?void 0:De.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),$e=F.placeholder==="skeleton",Mt=$e&&F.buffer==="line"&&Y;if(Y)Mt&&S.appendChild(ca());else if($e)S.appendChild(ca());else{let ue=Xh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ue&&S.appendChild(ue)}}if(le&&e.stopReason&&!e.streaming&&(R||(C.style.display="none"),S.appendChild(_h(e.stopReason,le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Y=Zh(e,o,r);S.appendChild(Y)}if(!m||e.role==="system")return S;let Ne=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),xe=Qh(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Ne.append(S,xe):Ne.append(xe,S),S.classList.remove("persona-max-w-[85%]"),S.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ne};var ns=new Set,eb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),tb=(e,t)=>{var 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
- `):""},Im=(e,t)=>{let n=ns.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=ke(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")},ql=(e,t)=>{var ae,ge,le,ye,Ne,xe,J,Ie,X,we,Ae;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(ge=(ae=t==null?void 0:t.features)==null?void 0:ae.reasoningDisplay)!=null?ge:{},s=r.expandable!==!1,a=s&&ns.has(e.id),i=n.status!=="complete",d=tb(e,(le=r.previewMaxLines)!=null?le:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let m=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",p=(ye=t==null?void 0:t.reasoning)!=null?ye:{},w=String((Ne=n.startedAt)!=null?Ne:Date.now()),S=()=>{let pe=b("span","");return pe.setAttribute("data-tool-elapsed",w),pe.textContent=gi(n),pe},L=(xe=p.renderCollapsedSummary)==null?void 0:xe.call(p,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:gi(n),createElapsedElement:S});typeof L=="string"&&L.trim()?(u.textContent=L,m.appendChild(u)):L instanceof HTMLElement?m.appendChild(L):(u.textContent=g,m.appendChild(u));let R=b("span","persona-text-xs persona-text-persona-primary");R.textContent=Ju(n),m.appendChild(R);let I=(J=r.loadingAnimation)!=null?J:"none",D=p.activeTextTemplate,F=p.completeTextTemplate,B=i?D:F,v=L instanceof HTMLElement,x=(pe,Ce,qe)=>{let ne=qe;for(let oe of Ce){let se=b("span","persona-tool-char");se.style.setProperty("--char-index",String(ne)),se.textContent=oe===" "?"\xA0":oe,pe.appendChild(se),ne++}return ne},E=(pe,Ce)=>{u.textContent="";let qe=hi(pe,""),ne=0;for(let oe of qe){let se=oe.styles.length>0?(()=>{let ot=b("span",oe.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return u.appendChild(ot),ot})():u;if(oe.isDuration&&i)se.appendChild(S());else{let ot=oe.isDuration?gi(n):oe.text;Ce?ne=x(se,ot,ne):se.appendChild(document.createTextNode(ot))}}};if(!v&&B)if(R.style.display="none",u.style.display="",i&&I!=="none"){let pe=(Ie=p.loadingAnimationDuration)!=null?Ie:2e3;u.setAttribute("data-preserve-animation","true"),I==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),E(B,!1)):(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),I==="shimmer-color"&&(p.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",p.loadingAnimationColor),p.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",p.loadingAnimationSecondaryColor)),E(B,!0))}else E(B,!1);else if(!v&&i&&I!=="none"){u.style.display="";let pe=(X=p.loadingAnimationDuration)!=null?X:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`);else{u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),I==="shimmer-color"&&(p.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",p.loadingAnimationColor),p.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",p.loadingAnimationSecondaryColor));let Ce=u.textContent||g;u.textContent="",x(u,Ce,0)}n.status==="complete"&&(u.style.display="none")}else v||(n.status==="complete"?u.style.display="none":u.style.display="");let C=null;if(s){C=b("div","persona-flex persona-items-center");let Ce=ke(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?C.appendChild(Ce):C.textContent=a?"Hide":"Show";let qe=b("div","persona-flex persona-items-center persona-ml-auto");qe.append(C),l.append(m,qe)}else l.append(m);let k=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let pe=(Ae=(we=t==null?void 0:t.reasoning)==null?void 0:we.renderCollapsedPreview)==null?void 0:Ae.call(we,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});eb(k,pe)||(k.textContent=d),k.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,k),o;let O=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let U=n.chunks.join(""),K=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return K.textContent=U||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(K),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),C){C.innerHTML="";let Ce=ke(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?C.appendChild(Ce):C.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(l,k,O),o};var os=new Set,nb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ob=(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=es(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},rb=(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=ob(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Zu(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=Pl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Pl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Rm=(e,t,n)=>{var m;let o=os.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=ke(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")},jl=(e,t)=>{var U,K,fe,ae,ge,le,ye,Ne,xe;let n=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),!n)return r;let s=(fe=(K=t==null?void 0:t.features)==null?void 0:K.toolCallDisplay)!=null?fe:{},a=s.expandable!==!1,i=a&&os.has(e.id),{summary:d,previewText:l,isActive:m}=rb(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((ae=n.startedAt)!=null?ae:Date.now()),S=()=>{let J=b("span","");return J.setAttribute("data-tool-elapsed",w),J.textContent=Qs(n),J},L=(le=o.renderCollapsedSummary)==null?void 0:le.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ge=s.collapsedMode)!=null?ge:"tool-call",isActive:m,config:t!=null?t:{},elapsed:Qs(n),createElapsedElement:S});typeof L=="string"&&L.trim()?(p.textContent=L,g.appendChild(p)):L instanceof HTMLElement?g.appendChild(L):(p.textContent=d,g.appendChild(p));let R=(ye=s.loadingAnimation)!=null?ye:"none",I=o.activeTextTemplate,D=o.completeTextTemplate,F=m?I:D,B=L instanceof HTMLElement,v=(J,Ie,X)=>{let we=X;for(let Ae of Ie){let pe=b("span","persona-tool-char");pe.style.setProperty("--char-index",String(we)),pe.textContent=Ae===" "?"\xA0":Ae,J.appendChild(pe),we++}return we},x=(J,Ie)=>{var pe;p.textContent="";let X=((pe=n.name)==null?void 0:pe.trim())||"tool",we=hi(J,X),Ae=0;for(let Ce of we){let qe=Ce.styles.length>0?(()=>{let ne=b("span",Ce.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return p.appendChild(ne),ne})():p;if(Ce.isDuration&&m)qe.appendChild(S());else{let ne=Ce.isDuration?Qs(n):Ce.text;Ie?Ae=v(qe,ne,Ae):qe.appendChild(document.createTextNode(ne))}}};if(!B)if(m&&R!=="none"){let J=(Ne=o.loadingAnimationDuration)!=null?Ne:2e3;if(p.setAttribute("data-preserve-animation","true"),R==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${J}ms`),F&&x(F,!1);else if(p.classList.add(`persona-tool-loading-${R}`),p.style.setProperty("--persona-tool-anim-duration",`${J}ms`),R==="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)),F)x(F,!0);else{let Ie=p.textContent||d;p.textContent="",v(p,Ie,0)}}else F&&x(F,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let J=o.toggleTextColor||o.headerTextColor||"currentColor",Ie=ke(i?"chevron-up":"chevron-down",16,J,2);Ie?E.appendChild(Ie):E.textContent=i?"Hide":"Show";let X=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(E),u.append(g,X)}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 J=(xe=o.renderCollapsedPreview)==null?void 0:xe.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});nb(C,J)||(C.textContent=l),C.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,C),r;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),n.name){let 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,k.appendChild(J)}if(n.args!==void 0){let J=b("div","persona-space-y-1"),Ie=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ie.style.color=o.labelTextColor),Ie.textContent="Arguments";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=es(n.args),J.append(Ie,X),k.appendChild(J)}if(n.chunks&&n.chunks.length){let J=b("div","persona-space-y-1"),Ie=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ie.style.color=o.labelTextColor),Ie.textContent="Activity";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=n.chunks.join(""),J.append(Ie,X),k.appendChild(J)}if(n.status==="complete"&&n.result!==void 0){let J=b("div","persona-space-y-1"),Ie=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ie.style.color=o.labelTextColor),Ie.textContent="Result";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=es(n.result),J.append(Ie,X),k.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`,k.appendChild(J)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let J=o.toggleTextColor||o.headerTextColor||"currentColor",Ie=ke(i?"chevron-up":"chevron-down",16,J,2);Ie?E.appendChild(Ie):E.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",C.style.display=i?"none":C.textContent||C.childNodes.length?"":"none"})(),r.append(u,C,k),r};var ir=require("partial-json");var sb="ask_user_question",Kl=8,rs="data-persona-ask-sheet-for",ab="Other",ib="Other\u2026",Wm="Type your own answer here",Bm="Send",lb="Next",cb="Back",db="Submit all",pb="Skip",ub=3,Gl="data-ask-current-index",Yl="data-ask-question-count",Hm="data-ask-answers",Xl="data-ask-grouped",Dm="data-ask-layout",mb=e=>e.layout==="pills"?"pills":"rows",fb=e=>e.getAttribute(Dm)==="pills"?"pills":"rows",Pm=!1,Fm=e=>e.replace(/["\\]/g,"\\$&"),Rr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===sb,Ql=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ss=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ir.parse)(r,ir.STR|ir.OBJ|ir.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ga=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Kl&&!Pm&&(Pm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Kl}.`)),t.slice(0,Kl)},gb=e=>{var t;return(t=ga(e)[0])!=null?t:null},hb=(e,t)=>{var n;return(n=ga(e)[t])!=null?n:null},bb=(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))},Om=(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},yb=(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=Om(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},vb=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},xb=(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<ub;p++)s.appendChild(vb(o));return s}if(d.forEach((p,w)=>{s.appendChild(yb(p,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let p=o==="rows"?ab:ib;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"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(m=t.freeTextPlaceholder)!=null?m:Wm,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:p),S.appendChild(L),w.appendChild(S);let R=Om(o,a,d.length);R&&w.appendChild(R),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},Nm=(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:Wm,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:Bm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},wb=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:Bm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Cb=(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:cb,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:pb,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:db:(g=n.nextLabel)!=null?g:lb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Pr=e=>{let t=e.getAttribute(Hm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},_m=(e,t)=>{e.setAttribute(Hm,JSON.stringify(t))},co=e=>{var n;let t=Number((n=e.getAttribute(Gl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Sb=(e,t)=>{e.setAttribute(Gl,String(Math.max(0,Math.floor(t))))},as=e=>{var n;let t=Number((n=e.getAttribute(Yl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},lr=e=>e.getAttribute(Xl)==="true",Ab=(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},Tb=(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)))},qi=(e,t)=>{let{payload:n}=ss(t),o=ga(n),r=Pr(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},Vm=e=>{let t=Pr(e),n=co(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var 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=""},$m=e=>{if(!lr(e))return;let t=Pr(e),n=co(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Jl=(e,t,n)=>{let o=Ql(n),r=fb(e),{payload:s,complete:a}=ss(t),i=lr(e),d=co(e),l=as(e),m=i?hb(s,d):gb(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 I=typeof(m==null?void 0:m.question)=="string"?m.question:"";w.textContent=I,w.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let I=xb(m,o,a,r);S.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(Nm(o,r))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!L?e.appendChild(wb(o)):(!u||i)&&L&&L.remove(),e.setAttribute("data-multi-select",u?"true":"false");let R=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=Cb(d,l,o);R?R.replaceWith(I):e.appendChild(I)}else R&&R.remove();Vm(e),$m(e)},kb=(e,t,n)=>{let o=Ql(t),r=mb(o),s=e.toolCall.id,a=ga(n),i=Math.max(1,a.length),d=i>1,l=Ab(e,a),m=d?Tb(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(rs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Yl,String(i)),u.setAttribute(Gl,String(m)),u.setAttribute(Xl,d?"true":"false"),u.setAttribute(Dm,r),_m(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`),bb(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 L=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),u.appendChild(L),r!=="rows"&&u.appendChild(Nm(o,r)),Jl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Eb=(e,t,n)=>{let{payload:o}=ss(t),r=Math.max(1,ga(o).length);r>as(e)&&(e.setAttribute(Yl,String(r)),r>1&&!lr(e)&&e.setAttribute(Xl,"true")),Jl(e,t,n)};var ji=(e,t,n)=>{if(!n||!Rr(e)||Ql(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${rs}]`).forEach(l=>{l.getAttribute(rs)!==r&&l.remove()});let a=n.querySelector(`[${rs}="${Fm(r)}"]`);if(a){Eb(a,e,t);return}let{payload:i}=ss(e),d=kb(e,t,i);n.appendChild(d)},is=(e,t)=>{if(!e)return;let n=t?`[${rs}="${Fm(t)}"]`:`[${rs}]`;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)})},Zl=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=Pr(e),o=co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,_m(e,n),Vm(e),$m(e)},Ki=(e,t,n,o)=>{let r=as(e),s=Math.max(0,Math.min(r-1,o));Sb(e,s),Jl(e,t,n)};var ec=(e,t)=>{var S,L,R,I,D,F,B,v,x,E,C,k;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(S=o==null?void 0:o.backgroundColor)!=null?S:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(L=o==null?void 0:o.borderColor)!=null?L:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(R=o==null?void 0:o.titleColor)!=null?R:"currentColor",m=ke(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=(I=o==null?void 0:o.title)!=null?I:"Approval Required",g.appendChild(p),!r){let O=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",n.status),n.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):n.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):n.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),g.appendChild(O)}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 O=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(O.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(O.style.color=o.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=es(n.parameters),u.appendChild(O)}if(r){let O=b("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let U=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");U.type="button",U.style.backgroundColor=(D=o==null?void 0:o.approveButtonColor)!=null?D:"var(--persona-approval-approve-bg, #22c55e)",U.style.color=(F=o==null?void 0:o.approveButtonTextColor)!=null?F:"#ffffff",U.setAttribute("data-approval-action","approve");let K=ke("shield-check",14,(B=o==null?void 0:o.approveButtonTextColor)!=null?B:"#ffffff",2);K&&(K.style.marginRight="4px",U.appendChild(K));let fe=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");U.appendChild(fe);let ae=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");ae.type="button",ae.style.backgroundColor=(x=o==null?void 0:o.denyButtonColor)!=null?x:"transparent",ae.style.color=(E=o==null?void 0:o.denyButtonTextColor)!=null?E:"var(--persona-feedback-error, #dc2626)",ae.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ae.setAttribute("data-approval-action","deny");let ge=ke("shield-x",14,(C=o==null?void 0:o.denyButtonTextColor)!=null?C:"var(--persona-feedback-error, #dc2626)",2);ge&&(ge.style.marginRight="4px",ae.appendChild(ge));let le=document.createTextNode((k=o==null?void 0:o.denyLabel)!=null?k:"Deny");ae.appendChild(le),O.append(U,ae),u.appendChild(O)}return a.append(i,u),s.appendChild(a),s};var Um=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(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 ha=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 ba=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 Mb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Lb=new Set(["step_start","execution_start"]),Ib=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Rb=new Set(["step_complete","agent_turn_complete"]),Pb=new Set(["flow_complete","agent_complete"]),zm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),jm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Wr=(e,t)=>{let n=e[t];return jm(n)?n:void 0};function tc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Gi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Wb(e,t){return typeof t.type=="string"?t.type:e}function Bb(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 Hb(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 qm(e){var o,r,s,a,i;let t=Wr(e,"result"),n=[Wr(e,"tokens"),Wr(e,"totalTokens"),t?Wr(t,"tokens"):void 0,Wr(e,"usage"),t?Wr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Jn(d.output))!=null?o:Jn(d.outputTokens))!=null?r:Jn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Jn(e.outputTokens))!=null?s:Jn(e.completionTokens))!=null?i:t?(a=Jn(t.outputTokens))!=null?a:Jn(t.completionTokens):void 0}function Db(e){var n,o,r,s,a;let t=Wr(e,"result");return(a=(r=(o=(n=Jn(e.executionTime))!=null?n:Jn(e.executionTimeMs))!=null?o:Jn(e.execution_time))!=null?r:Jn(e.duration))!=null?a:t?(s=Jn(t.executionTime))!=null?s:Jn(t.executionTimeMs):void 0}function Fb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ya=class{constructor(t=Fb){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:Gi(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(!jm(n)){zm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Wb(t,n),r=this.now();if(Mb.has(o)){this.startRun(r);return}if(Lb.has(o)){this.run||this.startRun(r);return}if(Ib.has(o)){if(!Hb(o,n))return;let a=Bb(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+tc(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Gi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Rb.has(o)){if(!this.run)return;let a=this.run,i=qm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+tc(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Gi(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(Pb.has(o)){if(!this.run)return;let a=this.run,i=qm(n),d=i!=null?i:a.exactOutputTokens+tc(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Gi(d,m),outputTokens:d,durationMs:m,source:l},this.run=null;return}if(zm.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=Db(n);return s!=null?s:o-t.startedAt}};function ls(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Ob={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)"}},Nb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},_b=["flowName","stepName","reasoningText","text","name","tool","toolName"],Vb=100;function $b(e,t){let n={...Ob,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Nb}function Ub(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function zb(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 qb(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 jb(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 Kb(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 Gb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Yb(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 Xb(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 nc(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");ls(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 U,K;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"),L=ke(d?"chevron-down":"chevron-right","14px","currentColor",2);L&&S.appendChild(L);let R=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(U=o.timestampFormat)!=null?U:"relative";R.textContent=I==="relative"?Ub(e.timestamp,n):zb(e.timestamp);let D=null;o.showSequenceNumbers!==!1&&(D=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(t+1));let F=$b(e.type,o.badgeColors),B=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");B.style.backgroundColor=F.bg,B.style.color=F.text,B.style.borderColor=F.text+"50",B.textContent=e.type;let v=(K=o.descriptionFields)!=null?K:_b,x=qb(e.payload,v),E=null;x&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=x);let C=b("div","persona-flex-1 persona-min-w-0"),k=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=ke("clipboard","12px","currentColor",1.5);return O&&k.appendChild(O),k.addEventListener("click",async fe=>{fe.stopPropagation(),await jb(Kb(e)),k.innerHTML="";let ae=ke("check","12px","currentColor",1.5);ae&&k.appendChild(ae),setTimeout(()=>{k.innerHTML="";let ge=ke("clipboard","12px","currentColor",1.5);ge&&k.appendChild(ge)},1500)}),w.appendChild(S),w.appendChild(R),D&&w.appendChild(D),w.appendChild(B),E&&w.appendChild(E),w.appendChild(C),w.appendChild(k),p.appendChild(w),d&&p.appendChild(Xb(e,a,i)),p}}function Km(e){var w,S,L,R,I;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=(L=i==null?void 0:i.label)!=null?L:"",u=(I=(R=r==null?void 0:r.features)==null?void 0:R.eventStream)!=null?I:{},g=s.find(D=>D.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let D=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>p().element,onClose:o});if(D)return{element:D,update:()=>{},destroy:()=>{}}}return p();function p(){let D=u.classNames,F=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ls(F,D==null?void 0:D.panel);let B=[],v="",x="",E=null,C=[],k={},O=0,U=Mi(),K=0,fe=0,ae=!1,ge=null,le=!1,ye=0,Ne=new Set,xe=new Map,J="",Ie="",X=null,we,Ae,pe,Ce,qe,ne=null,oe=null,se=null;function ot(){let re=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),he=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");ls(he,D==null?void 0:D.headerBar);let wt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(wt.textContent="Events",we=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"),we.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 On=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");On.textContent="Throughput",ne=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"),ne.textContent="-- tok/s",se=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"),se.style.display="none",se.style.pointerEvents="none";let eo=oe,xn=se,Nn=()=>{if(!xn.textContent)return;let So=eo.getBoundingClientRect(),_n=re.getBoundingClientRect();xn.style.left=`${So.left-_n.left}px`,xn.style.top=`${So.bottom-_n.top+4}px`,xn.style.display="block"},mt=()=>{xn.style.display="none"};oe.addEventListener("mouseenter",Nn),oe.addEventListener("mouseleave",mt),oe.appendChild(On),oe.appendChild(ne)}let Ut=b("div","persona-flex-1");Ae=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Zt=b("option","");Zt.value="",Zt.textContent="All events",Ae.appendChild(Zt),pe=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"),pe.type="button",pe.title="Copy All";let kt=ke("clipboard-copy","12px","currentColor",1.5);kt&&pe.appendChild(kt);let Ct=b("span","persona-text-xs");Ct.textContent="Copy All",pe.appendChild(Ct),he.appendChild(wt),he.appendChild(we),oe&&he.appendChild(oe),he.appendChild(Ut),he.appendChild(Ae),he.appendChild(pe);let ht=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ls(ht,D==null?void 0:D.searchBar);let yt=ke("search","14px","var(--persona-muted, #9ca3af)",1.5),qt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");yt&&qt.appendChild(yt),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"),ls(Ce,D==null?void 0:D.searchInput),Ce.type="text",Ce.placeholder="Search event payloads...",qe=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"),qe.type="button",qe.style.display="none";let tt=ke("x","12px","currentColor",2);return tt&&qe.appendChild(tt),ht.appendChild(qt),ht.appendChild(Ce),ht.appendChild(qe),re.appendChild(he),re.appendChild(ht),se&&re.appendChild(se),re}let ve,ce=s.find(re=>re.renderEventStreamToolbar);if(ce!=null&&ce.renderEventStreamToolbar&&r){let re=ce.renderEventStreamToolbar({config:r,defaultRenderer:()=>ot(),eventCount:t.getSize(),filteredCount:0,onFilterChange:he=>{v=he,Fn(),V()},onSearchChange:he=>{x=he,Fn(),V()}});ve=re!=null?re:ot()}else ve=ot();let ze=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");ze.style.display="none";function De(){if(!a||!ne||!oe)return;let re=a();ne.textContent=Gb(re);let he=Yb(re);se&&(se.textContent=he,he||(se.style.display="none")),he?oe.setAttribute("aria-label",he):oe.removeAttribute("aria-label")}let de=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let $e=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ls($e,D==null?void 0:D.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Mt=ke(l,"14px","currentColor",2);Mt&&$e.appendChild(Mt);let ue=b("span","");ue.textContent=m,$e.appendChild(ue);let ie=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ie.style.display="none",de.appendChild(Y),de.appendChild(ie),de.appendChild($e),F.setAttribute("tabindex","0"),F.appendChild(ve),F.appendChild(ze),F.appendChild(de);function In(){let re=t.getAll(),he={};for(let Ct of re)he[Ct.type]=(he[Ct.type]||0)+1;let wt=Object.keys(he).sort(),Ut=wt.length!==C.length||!wt.every((Ct,ht)=>Ct===C[ht]),Zt=!Ut&&wt.some(Ct=>he[Ct]!==k[Ct]),vn=re.length!==Object.values(k).reduce((Ct,ht)=>Ct+ht,0);if(!Ut&&!Zt&&!vn||(C=wt,k=he,!Ae))return;let kt=Ae.value;if(Ae.options[0].textContent="All events",Ut){for(;Ae.options.length>1;)Ae.remove(1);for(let Ct of wt){let ht=b("option","");ht.value=Ct,ht.textContent=`${Ct} (${he[Ct]||0})`,Ae.appendChild(ht)}kt&&wt.includes(kt)?Ae.value=kt:kt&&(Ae.value="",v="")}else for(let Ct=1;Ct<Ae.options.length;Ct++){let ht=Ae.options[Ct];ht.textContent=`${ht.value} (${he[ht.value]||0})`}}function _t(){let re=t.getAll();if(v&&(re=re.filter(he=>he.type===v)),x){let he=x.toLowerCase();re=re.filter(wt=>wt.type.toLowerCase().includes(he)||wt.payload.toLowerCase().includes(he))}return re}function cn(){return v!==""||x!==""}function Fn(){O=0,K=0,U.resume(),$e.style.display="none"}function Zn(re){Ne.has(re)?Ne.delete(re):Ne.add(re),X=re;let he=Y.scrollTop,wt=U.isFollowing();le=!0,U.pause(),V(),Y.scrollTop=he,wt&&U.resume(),le=!1}function je(){return sa(Y,50)}function V(){fe=Date.now(),ae=!1,De(),In();let re=t.getEvictedCount();re>0?(ze.textContent=`${re.toLocaleString()} older events truncated`,ze.style.display=""):ze.style.display="none",B=_t();let he=B.length,wt=t.getSize()>0;we&&(we.textContent=String(t.getSize())),he===0&&wt&&cn()?(ie.textContent=x?`No events matching '${x}'`:"No events matching filter",ie.style.display="",Y.style.display="none"):(ie.style.display="none",Y.style.display=""),pe&&(pe.title=cn()?`Copy Filtered (${he})`:"Copy All"),d&&!U.isFollowing()&&he>O&&(K+=he-O,ue.textContent=m?`${m}${K>0?` (${K})`:""}`:"",$e.style.display=""),O=he;let Ut=t.getAll(),Zt=Ut.length>0?Ut[0].timestamp:0,vn=new Set(B.map(ht=>ht.id));for(let ht of Ne)vn.has(ht)||Ne.delete(ht);let kt=v!==J||x!==Ie,Ct=xe.size===0&&B.length>0;if(kt||Ct||B.length===0){Y.innerHTML="",xe.clear();let ht=document.createDocumentFragment();for(let yt=0;yt<B.length;yt++){let qt=nc(B[yt],yt,Zt,u,Ne,Zn,s,r);xe.set(B[yt].id,qt),ht.appendChild(qt)}Y.appendChild(ht),J=v,Ie=x,X=null}else{if(X!==null){let yt=xe.get(X);if(yt&&yt.parentNode===Y){let qt=B.findIndex(tt=>tt.id===X);if(qt>=0){let tt=nc(B[qt],qt,Zt,u,Ne,Zn,s,r);Y.insertBefore(tt,yt),yt.remove(),xe.set(X,tt)}}X=null}let ht=new Set(B.map(yt=>yt.id));for(let[yt,qt]of xe)ht.has(yt)||(qt.remove(),xe.delete(yt));for(let yt=0;yt<B.length;yt++){let qt=B[yt];if(!xe.has(qt.id)){let tt=nc(qt,yt,Zt,u,Ne,Zn,s,r);xe.set(qt.id,tt),Y.appendChild(tt)}}}U.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function Ee(){if(Date.now()-fe>=Vb){ge!==null&&(cancelAnimationFrame(ge),ge=null),V();return}ae||(ae=!0,ge=requestAnimationFrame(()=>{ge=null,V()}))}let Fe=(re,he)=>{if(!pe)return;pe.innerHTML="";let wt=ke(re,"12px","currentColor",1.5);wt&&pe.appendChild(wt);let Ut=b("span","persona-text-xs");Ut.textContent="Copy All",pe.appendChild(Ut),setTimeout(()=>{pe.innerHTML="";let Zt=ke("clipboard-copy","12px","currentColor",1.5);Zt&&pe.appendChild(Zt);let vn=b("span","persona-text-xs");vn.textContent="Copy All",pe.appendChild(vn),pe.disabled=!1},he)},Oe=async()=>{if(pe){pe.disabled=!0;try{let re;cn()?re=B:n?(re=await n(),re.length===0&&(re=t.getAll())):re=t.getAll();let he=re.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(he,null,2)),Fe("check",1500)}catch{Fe("x",1500)}}},Ue=()=>{Ae&&(v=Ae.value,Fn(),V())},pt=()=>{!Ce||!qe||(qe.style.display=Ce.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{x=Ce.value,Fn(),V()},150))},rt=()=>{!Ce||!qe||(Ce.value="",x="",qe.style.display="none",E&&clearTimeout(E),Fn(),V())},Tt=()=>{if(le)return;let re=Y.scrollTop,{action:he,nextLastScrollTop:wt}=Li({following:U.isFollowing(),currentScrollTop:re,lastScrollTop:ye,nearBottom:je(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=wt,he==="resume"?(U.resume(),K=0,$e.style.display="none"):he==="pause"&&(U.pause(),d&&(ue.textContent=m,$e.style.display=""))},$t=re=>{let he=Ii({following:U.isFollowing(),deltaY:re.deltaY,nearBottom:je(),resumeWhenNearBottom:!0});he==="pause"?(U.pause(),d&&(ue.textContent=m,$e.style.display="")):he==="resume"&&(U.resume(),K=0,$e.style.display="none")},j=()=>{d&&(Y.scrollTop=Y.scrollHeight,U.resume(),K=0,$e.style.display="none")},Vt=re=>{let he=re.target;if(!he||he.closest("button"))return;let wt=he.closest("[data-event-id]");if(!wt)return;let Ut=wt.getAttribute("data-event-id");Ut&&Zn(Ut)},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?(rt(),Ce.blur(),F.focus()):o&&o())};pe&&pe.addEventListener("click",Oe),Ae&&Ae.addEventListener("change",Ue),Ce&&Ce.addEventListener("input",pt),qe&&qe.addEventListener("click",rt),Y.addEventListener("scroll",Tt),Y.addEventListener("wheel",$t,{passive:!0}),Y.addEventListener("click",Vt),$e.addEventListener("click",j),F.addEventListener("keydown",Je);function Ot(){E&&clearTimeout(E),ge!==null&&(cancelAnimationFrame(ge),ge=null),ae=!1,xe.clear(),pe&&pe.removeEventListener("click",Oe),Ae&&Ae.removeEventListener("change",Ue),Ce&&Ce.removeEventListener("input",pt),qe&&qe.removeEventListener("click",rt),Y.removeEventListener("scroll",Tt),Y.removeEventListener("wheel",$t),Y.removeEventListener("click",Vt),$e.removeEventListener("click",j),F.removeEventListener("keydown",Je)}return{element:F,update:Ee,destroy:Ot}}}function Gm(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 Ym=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",m=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Gm(e,t)});if(m)return m}return Gm(e,t)};var oc=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)})}},Br=new oc;Br.register("PersonaArtifactCard",Ym);function Qb(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 Xm(e,t){var Ae,pe,Ce,qe;let n=(pe=(Ae=e.features)==null?void 0:Ae.artifacts)==null?void 0:pe.layout,r=((Ce=n==null?void 0:n.toolbarPreset)!=null?Ce:"default")==="document",s=(qe=n==null?void 0:n.panePadding)==null?void 0:qe.trim(),a=e.markdown?di(e.markdown):null,i=pi(e.sanitize),d=ne=>{let oe=a?a(ne):Ys(ne);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"),u.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var ne;m(),(ne=t.onDismiss)==null||ne.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 ne;m(),(ne=t.onDismiss)==null||ne.call(t)});let S="rendered",L=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),R=r?yn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yn({icon:"eye",label:"Rendered view"}),I=r?yn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yn({icon:"code-2",label:"Source"}),D=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),F=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(B&&v&&v.length>0),E=null,C,k=null,O=null;if(r&&(F||B)&&!x){if(C=F?Vl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let ne=ke("chevron-down",14,"currentColor",2);ne&&C.appendChild(ne)}}else r&&x?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),C=F?Vl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),E.append(C,k)):r?C=yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):C=yn({icon:"copy",label:"Copy"});let U=r?yn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yn({icon:"refresh-cw",label:"Refresh"}),K=r?yn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yn({icon:"x",label:"Close"}),fe=()=>{var ve,ce,ze;let ne=(ve=xe.find(De=>De.id===J))!=null?ve:xe[xe.length-1],oe=(ce=ne==null?void 0:ne.id)!=null?ce:null,se=(ne==null?void 0:ne.artifactType)==="markdown"&&(ze=ne.markdown)!=null?ze:"",ot=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:se,jsonPayload:ot,id:oe}},ae=async()=>{var ve;let{markdown:ne,jsonPayload:oe}=fe(),se=(ve=xe.find(ce=>ce.id===J))!=null?ve:xe[xe.length-1],ot=(se==null?void 0:se.artifactType)==="markdown"?ne:se?oe:"";try{await navigator.clipboard.writeText(ot)}catch{}};if(C.addEventListener("click",async()=>{let ne=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(ne&&x){let{markdown:oe,jsonPayload:se,id:ot}=fe();try{await ne({actionId:"primary",artifactId:ot,markdown:oe,jsonPayload:se})}catch{}return}await ae()}),k&&(v!=null&&v.length)){let ne=()=>{var se;return(se=u.closest("[data-persona-root]"))!=null?se:document.body},oe=()=>{O=ts({items:v.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:ot,jsonPayload:ve,id:ce}=fe(),ze=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{ze?await ze({actionId:se,artifactId:ce,markdown:ot,jsonPayload:ve}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(ot):se==="json"||se==="source"?await navigator.clipboard.writeText(ve):await navigator.clipboard.writeText(ot||ve)}catch{}},anchor:E!=null?E:k,position:"bottom-right",portal:ne()})};u.isConnected?oe():requestAnimationFrame(oe),k.addEventListener("click",se=>{se.stopPropagation(),O==null||O.toggle()})}U.addEventListener("click",async()=>{var ne;try{await((ne=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:ne.call(n))}catch{}X()}),K.addEventListener("click",()=>{var ne;m(),(ne=t.onDismiss)==null||ne.call(t)});let ge=()=>{r&&(R.setAttribute("aria-pressed",S==="rendered"?"true":"false"),I.setAttribute("aria-pressed",S==="source"?"true":"false"))};R.addEventListener("click",()=>{S="rendered",ge(),X()}),I.addEventListener("click",()=>{S="source",ge(),X()});let le=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(g.replaceChildren(),L.append(R,I),E?D.append(E,U,K):D.append(C,U,K),g.append(L,le,D),ge()):(g.appendChild(p),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let ye=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"),Ne=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ye.style.paddingLeft=s,ye.style.paddingRight=s,Ne.style.padding=s),u.appendChild(g),u.appendChild(ye),u.appendChild(Ne);let xe=[],J=null,Ie=!1,X=()=>{var ot,ve,ce,ze;let ne=r&&xe.length<=1;ye.classList.toggle("persona-hidden",ne),ye.replaceChildren();for(let De of xe){let de=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");de.type="button",de.textContent=De.title||De.id.slice(0,8),De.id===J&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>t.onSelect(De.id)),ye.appendChild(de)}Ne.replaceChildren();let oe=J&&xe.find(De=>De.id===J)||xe[xe.length-1];if(!oe)return;if(r){let De=oe.artifactType==="markdown"?"MD":(ot=oe.component)!=null?ot:"Component",Y=(oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${Y} \xB7 ${De}`}else p.textContent="Artifacts";if(oe.artifactType==="markdown"){if(r&&S==="source"){let de=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(ve=oe.markdown)!=null?ve:"",Ne.appendChild(de);return}let De=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");De.innerHTML=d((ce=oe.markdown)!=null?ce:""),Ne.appendChild(De);return}let se=oe.component?Br.get(oe.component):void 0;if(se){let de={message:{id:oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=se((ze=oe.props)!=null?ze:{},de);if(Y){Ne.appendChild(Y);return}}catch{}}Ne.appendChild(Qb(oe))},we=()=>{var oe;let ne=xe.length>0;if(u.classList.toggle("persona-hidden",!ne),l){let se=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,ve=((oe=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&ve&&Ie?(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(ne){var oe,se,ot;xe=ne.artifacts,J=(ot=(se=ne.selectedId)!=null?se:(oe=ne.artifacts[ne.artifacts.length-1])==null?void 0:oe.id)!=null?ot:null,xe.length>0&&(Ie=!0),X(),we()},setMobileOpen(ne){Ie=ne,!ne&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):we()}}}function po(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Qm(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!po(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Jb(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 Yi(e,t){var d,l,m,u,g,p,w,S,L,R;if(!po(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Jb(e),Qm(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=(L=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:L.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(R=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:R.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Qm(e,t)}var Jm=["panel","seamless"];function Xi(e,t){var i,d,l,m,u,g;for(let p of Jm)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"),!po(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=Jm.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 Zm(e,t){var n,o,r;return!t||!po(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function Zb(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 ey(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 ty(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ny(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function ef(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 tf(e,t,n,o,r,s){let a=Zb(r,200),i=ny(t,n,o,200);i=Math.max(a,i);let d=ey(s);return d!==null&&(i=Math.min(i,d)),ty(e,a,i)}var nf={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"}},rc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,S,L;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(S=nf[a])!=null?S:nf.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 R=b("p","persona-text-sm persona-text-persona-muted");R.textContent=i.description,d.appendChild(R)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(R=>{var v,x;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${R.name}`;let D=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=R.label,I.appendChild(D);let F=(v=R.type)!=null?v:"text",B;F==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=F),B.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",B.id=`${t.id}-${a}-${R.name}`,B.name=R.name,B.placeholder=(x=R.placeholder)!=null?x:"",R.required&&(B.required=!0),I.appendChild(B),m.appendChild(I)});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=(L=i.submitLabel)!=null?L:"Submit",u.appendChild(g),u.appendChild(p),m.appendChild(u),s.replaceChildren(d,m),m.addEventListener("submit",async R=>{var B,v;R.preventDefault();let I=(B=n.formEndpoint)!=null?B:"/form",D=new FormData(m),F={};D.forEach((x,E)=>{F[E]=x}),F.type=a,p.disabled=!0,g.textContent="Submitting\u2026";try{let x=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let E=await x.json();g.textContent=(v=E.message)!=null?v:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(x){g.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{p.disabled=!1}})})};var sc=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()}},ac=new sc;var of=()=>{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 oy=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ry=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},lc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=oy(e),n=ry(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}},ic=e=>typeof e=="string"?e:e==null?"":String(e),va={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ic(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=ic(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:ic(n.text)}}},rf=e=>Array.isArray(e)?e.map(t=>String(t)):[],cc=e=>{let t=new Set(rf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(rf(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 sy=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}},ay=e=>e.map(t=>({...t,streaming:!1})),iy=e=>e.map(t=>({...t,status:"complete"})),sf=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?sy(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?ay(n.messages):void 0,artifacts:n.artifacts?iy(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var dc=require("partial-json");function af(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Br.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 lf(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 cf(e){let t=lf(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 df(e){let t=lf(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 ly=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function pf(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=ly}=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 L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let R=[];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 W,D,B,x,w,E,S,T,_,U,Y,he,fe;let a=(W=s.launcher)!=null?W:{},i=bn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ae=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ae,d.setAttribute("title",ae)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ae=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ae,l.setAttribute("title",ae)}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 ae=(x=a.agentIconSize)!=null?x:"40px";if(p.style.height=ae,p.style.width=ae,p.innerHTML="",a.agentIconName){let Ee=parseFloat(ae)||24,ye=Me(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);ye?(p.appendChild(ye),p.style.display=""):(p.textContent=(w=a.agentIconText)!=null?w:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ae=(S=a.agentIconSize)!=null?S:"40px";f.style.height=ae,f.style.width=ae,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ae=(T=a.callToActionIconSize)!=null?T:"32px";u.style.height=ae,u.style.width=ae,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 Ee=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,Ee=(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 ye=parseFloat(ae)||24,Oe=Math.max(ye-Ee,8),we=Me(a.callToActionIconName,Oe,"currentColor",2);we?u.appendChild(we):u.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else u.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}let C=a.position&&Mo[a.position]?Mo[a.position]:Mo["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",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:`${v} ${C}`,i||(n.style.zIndex=String((Y=a.zIndex)!=null?Y:Cn));let I="1px solid var(--persona-border, #e5e7eb)",R="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=(he=a.border)!=null?he:I,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:R,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(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 zh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Fi=(e,t={})=>{var v,M,I,R,W,D;let{showClose:n=!0,wrapperClassName:o=zh,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},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",p=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let f=(W=a.closeButtonIconName)!=null?W:"x",u=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Rn.actionIconColor;let C=Me(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 B=a.closeButtonBorderWidth||"0px",x=a.closeButtonBorderColor||"transparent";l.style.border=`${B} 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 B=null,x=()=>{if(B)return;let E=l.ownerDocument,S=E.body;if(!S)return;B=Wo(E,"div","persona-clear-chat-tooltip"),B.textContent=m;let T=Wo(E,"div");T.className="persona-clear-chat-tooltip-arrow",B.appendChild(T);let _=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(lr),B.style.left=`${_.left+_.width/2}px`,B.style.top=`${_.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},w=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",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}},qh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Oi=(e,t={})=>{var B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee;let{wrapperClassName:n=qh,buttonSize:o,iconSize:r="20px"}=t,a=(x=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?x:{},i=(w=o!=null?o:a.size)!=null?w:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(S=a.iconColor)!=null?S:"",m=(T=a.backgroundColor)!=null?T:"",p=(_=a.borderWidth)!=null?_:"",f=(U=a.borderColor)!=null?U:"",u=(Y=a.borderRadius)!=null?Y:"",C=(he=a.paddingX)!=null?he:"",v=(fe=a.paddingY)!=null?fe:"",M=(ae=a.tooltipText)!=null?ae:"Clear chat",I=(Ee=a.showTooltip)!=null?Ee:!0,R=b("div",n),W=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");W.style.height=i,W.style.width=i,W.type="button",W.setAttribute("aria-label",M),W.style.color=l||Rn.actionIconColor;let D=Me(d,r,"currentColor",1);if(D&&(D.style.display="block",W.appendChild(D)),m&&(W.style.backgroundColor=m,W.classList.remove("hover:persona-bg-gray-100")),p||f){let ye=p||"0px",Oe=f||"transparent";W.style.border=`${ye} solid ${Oe}`,W.classList.remove("persona-border-none")}if(u&&(W.style.borderRadius=u,W.classList.remove("persona-rounded-full")),C&&(W.style.paddingLeft=C,W.style.paddingRight=C),v&&(W.style.paddingTop=v,W.style.paddingBottom=v),R.appendChild(W),I&&M){let ye=null,Oe=()=>{if(ye)return;let K=W.ownerDocument,pe=K.body;if(!pe)return;ye=Wo(K,"div","persona-clear-chat-tooltip"),ye.textContent=M;let G=Wo(K,"div");G.className="persona-clear-chat-tooltip-arrow",ye.appendChild(G);let ve=W.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(lr),ye.style.left=`${ve.left+ve.width/2}px`,ye.style.top=`${ve.top-8}px`,ye.style.transform="translate(-50%, -100%)",pe.appendChild(ye)},we=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};R.addEventListener("mouseenter",Oe),R.addEventListener("mouseleave",we),W.addEventListener("focus",Oe),W.addEventListener("blur",we),R._cleanupTooltip=()=>{we(),R.removeEventListener("mouseenter",Oe),R.removeEventListener("mouseleave",we),W.removeEventListener("focus",Oe),W.removeEventListener("blur",we)}}return{button:W,wrapper:R}};var Rn={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))"},Br=e=>{var B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(B=t==null?void 0:t.launcher)!=null?B:{},s=(x=r.headerIconSize)!=null?x:"48px",a=(w=r.closeButtonPlacement)!=null?w:"inline",i=(E=r.headerIconHidden)!=null?E:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let K=parseFloat(s)||24,pe=Me(d,K*.6,"currentColor",1);pe?l.replaceChildren(pe):l.textContent=(T=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?T:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let K=b("img");K.src=t.launcher.iconUrl,K.alt="",K.className="persona-rounded-xl persona-object-cover",K.style.height=s,K.style.width=s,l.replaceChildren(K)}else l.textContent=(Y=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?Y:"\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=Rn.titleColor,p.textContent=(fe=(he=t==null?void 0:t.launcher)==null?void 0:he.title)!=null?fe:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Rn.subtitleColor,f.textContent=(Ee=(ae=t==null?void 0:t.launcher)==null?void 0:ae.subtitle)!=null?Ee:"Here to help you get answers fast",m.append(p,f),i?o.append(m):o.append(l,m);let u=(ye=r.clearChat)!=null?ye:{},C=(Oe=u.enabled)!=null?Oe:!0,v=(we=u.placement)!=null?we:"inline",M=null,I=null;if(C){let pe=Oi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=pe.button,I=pe.wrapper,v==="top-right"&&(I.style.right="48px"),v==="inline"&&o.appendChild(I)}let R=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:W,wrapper:D}=Fi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:W,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},va=(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 is(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(lr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of t){if(u.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let 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 M=Me(u.icon,16,"currentColor",1.5);M&&C.appendChild(M)}let v=document.createElement("span");v.textContent=u.label,C.appendChild(v),C.addEventListener("click",M=>{M.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 Sn(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=Me(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 Kl(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=Me(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 Rm(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=Me(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,M;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=is({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 M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"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 jh=e=>{var o;let t=Br({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 Kh(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=Me(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=is({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 Gh=e=>{var R,W,D,B,x,w,E,S,T;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(R=t==null?void 0:t.launcher)!=null?R:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,m;if(d)l=Rm({label:(W=a.title)!=null?W:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Rn.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=Rn.titleColor,m.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(m),Kh(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 U=r.onTitleClick;l.addEventListener("click",Y=>{Y.target.closest("button")||U()}),l.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),U())})}let _=r==null?void 0:r.titleRowHover;_&&(l.style.borderRadius=(w=_.borderRadius)!=null?w:"10px",l.style.padding=(E=_.padding)!=null?E:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var U,Y;l.style.backgroundColor=(U=_.background)!=null?U:"",l.style.borderColor=(Y=_.border)!=null?Y:""}),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||Rn.actionIconColor;let C=(T=a.closeButtonIconName)!=null?T:"x",v=Me(C,"28px","currentColor",1);v?u.appendChild(v):u.textContent="\xD7",o&&u.addEventListener("click",o),f.appendChild(u),i.appendChild(f);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:m,headerSubtitle:I,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Pm={default:jh,minimal:Gh},Yh=e=>{var t;return(t=Pm[e])!=null?t:Pm.default},Ni=(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=Yh(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 _i=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 B,x,w,E,S,T,_,U,Y,he,fe,ae;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(x=t.useIcon)!=null?x:!1,o=(w=t.iconText)!=null?w:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(T=t.stopTooltipText)!=null?T:"Stop generating",d=(U=(_=e==null?void 0:e.copy)==null?void 0:_.sendButtonLabel)!=null?U:"Send",l=(he=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?he:"Stop",m=(fe=t.showTooltip)!=null?fe:!1,p=(ae=t.size)!=null?ae:"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 M=null,I=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 Ee=parseFloat(p)||24,ye=(u==null?void 0:u.trim())||"currentColor";r?(M=Me(r,Ee,ye,2),M?v.appendChild(M):v.textContent=o):v.textContent=o,I=Me(s,Ee,ye,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 R=null;m&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,C.appendChild(R)),v.setAttribute("aria-label",a),C.appendChild(v);let W="send";return{button:v,wrapper:C,setMode:Ee=>{if(Ee===W)return;W=Ee;let ye=Ee==="stop"?i:a;if(v.setAttribute("aria-label",ye),R&&(R.textContent=ye),n){if(M&&I){let Oe=Ee==="stop"?I:M;v.replaceChildren(Oe)}}else v.textContent=Ee==="stop"?l:d}}},$i=e=>{var R,W,D,B,x,w,E,S,T,_,U,Y;let t=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((W=t.provider)==null?void 0:W.type)==="runtype";if(!(o||r))return null;let a=(B=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?B:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(x=t.iconName)!=null?x:"mic",m=(w=t.iconSize)!=null?w:a,p=parseFloat(m)||24,f=(S=t.backgroundColor)!=null?S:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,u=(_=t.iconColor)!=null?_:(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",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let v=Me(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 M=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&M){let he=b("div","persona-send-button-tooltip");he.textContent=M,i.appendChild(he)}return{button:d,wrapper:i}},Ui=e=>{var C,v,M,I,R,W,D,B;let t=(C=e==null?void 0:e.attachments)!=null?C:{};if(t.enabled!==!0)return null;let n=(M=(v=e==null?void 0:e.sendButton)==null?void 0:v.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:qo).join(","),r.multiple=((R=t.maxFiles)!=null?R:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(W=t.buttonTooltipText)!=null?W:"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 p=Me(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=(B=t.buttonTooltipText)!=null?B:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=f,s.appendChild(u),{button:a,wrapper:s,input:r,previewsContainer:o}},zi=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},qi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ji=e=>{var C,v,M,I,R,W;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=qi(),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}=_i(t);a();let i=Vi(t),d=$i(t),l=Ui(t),m=zi(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",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:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v: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:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:p,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Wm=()=>{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=Me("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=Me("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Bm=e=>{var C,v,M,I,R,W;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=qi();o.style.display="none";let r=zi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=_i(t);s.style.maxHeight="100px",a();let i=Vi(t),d=$i(t),l=Ui(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",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(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:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:u,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Hm=e=>{var m,p,f,u,C,v,M,I,R,W,D,B,x,w,E,S,T;let t=(p=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?p:!0,n=bn(e);if(ba(e)){let _=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?u:{},U=b("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(C=_.expandedSize)!=null?C:"anchored",U.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:Cn);let Y=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",U.appendChild(Y);let he=b("div","persona-widget-pill-root");return he.setAttribute("data-persona-composer-bar",""),he.dataset.state="collapsed",he.dataset.expandedSize=(I=_.expandedSize)!=null?I:"anchored",he.style.zIndex=String((W=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?W:Cn),{wrapper:U,panel:Y,pillRoot:he}}if(n){let _=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(U),{wrapper:_,panel:U}}if(!t){let _=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?B:"100%";return _.style.width=Y,U.style.width="100%",_.appendChild(U),{wrapper:_,panel:U}}let r=(x=e==null?void 0:e.launcher)!=null?x:{},s=r.position&&Mo[r.position]?Mo[r.position]:Mo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((E=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?E:Cn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(T=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?T:e==null?void 0:e.launcherWidth,l=d!=null?d:fo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Xh=(e,t)=>{var D,B,x,w,E,S,T,_,U;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=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=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:B.enabled)!=null?x:!0,a=null,i=null;if(s){let Y=Oi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Y.button,i=Y.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=(E=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?E:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(T=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",m.append(p,f);let u=b("div","persona-flex persona-flex-col persona-gap-3"),C=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;C&&(u.style.maxWidth=C,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,u);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=Bm({config:e}),{root:R,textNode:W}=Wm();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:M,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,introTitle:p,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode,peekBanner:R,peekTextNode:W}},Dm=(e,t=!0)=>{var M,I,R,W,D,B,x,w,E;if(ba(e))return Xh(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?Ni(e,o,{showClose:t}):Br({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=bn(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=(W=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?W:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(B=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",i.append(d,l);let 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=ji({config:e}),C=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?va(n,s,e):(s.header.style.display="none",va(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 Qh=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}},Jh=(e,t)=>{if(!e)return null;let n=Qh(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Zh=(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},eb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Gl=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,Om=320,tb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),ob=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),sb=(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=`${Yl}px`,l.style.maxHeight=`${Om}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}),eb(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}},ab=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(!Gl(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}},ib=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(!Gl(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=`${Om}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}},lb=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(!Gl(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}},xa=()=>{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},cb=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:xa};if(t){let r=t(o);if(r!==null)return r}return xa()},db=(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},Fm=(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},pb=(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},ub=(e,t,n)=>{var u,C,v,M,I,R;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 W=b("div");return W.style.display="none",W.id=`actions-${e.id}`,W.setAttribute("data-actions-for",e.id),W}let a=(M=t.visibility)!=null?M:"hover",i=(I=t.align)!=null?I:"right",d=(R=t.layout)!=null?R:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],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=(W,D,B)=>{let x=Sn({icon:W,label:D,size:14,className:"persona-message-action-btn"});return x.setAttribute("data-action",B),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},Xl=(e,t,n,o,r,s)=>{var K,pe,G,ve,ce,ne,Se,ze,te,re,ie,st,Te,ue,Ue,Be,me;let a=n!=null?n:{},i=(K=a.layout)!=null?K:"bubble",d=a.avatar,l=a.timestamp,m=(pe=d==null?void 0:d.show)!=null?pe:!1,p=(G=l==null?void 0:l.show)!=null?G:!1,f=(ve=d==null?void 0:d.position)!=null?ve:"left",u=(ce=l==null?void 0:l.position)!=null?ce:"below",C=pb(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 M=tb(e),I=(Se=(ne=e.content)==null?void 0:ne.trim())!=null?Se:"",W=M.length>0&&I===Ci,D=Wi((te=(ze=s==null?void 0:s.widgetConfig)==null?void 0:ze.features)==null?void 0:te.streamAnimation),B=(st=(ie=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.features)==null?void 0:ie.streamAnimation)==null?void 0:st.plugins,x=e.role==="assistant"&&D.type!=="none"?ma(D.type,B):null,w=e.role==="assistant"&&((Te=x==null?void 0:x.isAnimating)==null?void 0:Te.call(x,e))===!0,E=e.role==="assistant"&&x!==null&&(!!e.streaming||w);E&&(x!=null&&x.bubbleClass)&&v.classList.add(x.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),E&&x&&(x.containerClass&&S.classList.add(x.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let T=E?Bi((ue=e.content)!=null?ue:"",D.buffer,x,e,!!e.streaming):(Ue=e.content)!=null?Ue:"",_=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=_;E&&(x==null?void 0:x.wrap)==="char"?U=ga(_,"char",e.id,{skipTags:x.skipTags}):E&&(x==null?void 0:x.wrap)==="word"&&(U=ga(_,"word",e.id,{skipTags:x.skipTags}));let Y=null;if(W?(Y=document.createElement("div"),Y.innerHTML=U,Y.style.display="none",S.appendChild(Y)):S.innerHTML=U,E&&(x!=null&&x.useCaret)&&!W&&I){let Q=Hi(),_e=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ht=_e[_e.length-1];if(Ht!=null&&Ht.parentNode)Ht.parentNode.insertBefore(Q,Ht.nextSibling);else{let be=S.lastElementChild;be?be.appendChild(Q):S.appendChild(Q)}}if(p&&u==="inline"&&e.createdAt){let Q=Fm(e,l);Q.classList.add("persona-ml-2","persona-inline"),S.appendChild(Q)}if(M.length>0){let Q=sb(M,!W&&!!I,()=>{W&&Y&&(Y.style.display="")});Q?v.appendChild(Q):W&&Y&&(Y.style.display="")}let he=nb(e);if(he.length>0){let Q=ab(he);Q&&v.appendChild(Q)}let fe=ob(e);if(fe.length>0){let Q=ib(fe);Q&&v.appendChild(Q)}let ae=rb(e);if(ae.length>0){let Q=lb(ae);Q&&v.appendChild(Q)}if(v.appendChild(S),p&&u==="below"&&e.createdAt){let Q=Fm(e,l);Q.classList.add("persona-mt-1"),v.appendChild(Q)}let Ee=e.role==="assistant"?Jh(e.stopReason,(me=(Be=s==null?void 0:s.widgetConfig)==null?void 0:Be.copy)==null?void 0:me.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(T&&T.trim()),_e=D.placeholder==="skeleton",Ht=_e&&D.buffer==="line"&&Q;if(Q)Ht&&v.appendChild(fa());else if(_e)v.appendChild(fa());else{let be=cb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);be&&v.appendChild(be)}}if(Ee&&e.stopReason&&!e.streaming&&(I||(S.style.display="none"),v.appendChild(Zh(e.stopReason,Ee))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Q=ub(e,o,r);v.appendChild(Q)}if(!m||e.role==="system")return v;let Oe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),we=db(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Oe.append(v,we):Oe.append(we,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Oe};var ls=new Set,mb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),gb=(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
+ `):""},Nm=(e,t)=>{let n=ls.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=Me(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")},Ql=(e,t)=>{var fe,ae,Ee,ye,Oe,we,K,pe,G,ve,ce;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=(ae=(fe=t==null?void 0:t.features)==null?void 0:fe.reasoningDisplay)!=null?ae:{},s=r.expandable!==!1,a=s&&ls.has(e.id),i=n.status!=="complete",d=gb(e,(Ee=r.previewMaxLines)!=null?Ee: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=(ye=t==null?void 0:t.reasoning)!=null?ye:{},C=String((Oe=n.startedAt)!=null?Oe:Date.now()),v=()=>{let ne=b("span","");return ne.setAttribute("data-tool-elapsed",C),ne.textContent=bi(n),ne},M=(we=u.renderCollapsedSummary)==null?void 0:we.call(u,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:bi(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(p.textContent=M,m.appendChild(p)):M instanceof HTMLElement?m.appendChild(M):(p.textContent=f,m.appendChild(p));let I=b("span","persona-text-xs persona-text-persona-primary");I.textContent=im(n),m.appendChild(I);let R=(K=r.loadingAnimation)!=null?K:"none",W=u.activeTextTemplate,D=u.completeTextTemplate,B=i?W:D,x=M instanceof HTMLElement,w=(ne,Se,ze)=>{let te=ze;for(let re of Se){let ie=b("span","persona-tool-char");ie.style.setProperty("--char-index",String(te)),ie.textContent=re===" "?"\xA0":re,ne.appendChild(ie),te++}return te},E=(ne,Se)=>{p.textContent="";let ze=yi(ne,""),te=0;for(let re of ze){let ie=re.styles.length>0?(()=>{let st=b("span",re.styles.map(Te=>`persona-tool-text-${Te}`).join(" "));return p.appendChild(st),st})():p;if(re.isDuration&&i)ie.appendChild(v());else{let st=re.isDuration?bi(n):re.text;Se?te=w(ie,st,te):ie.appendChild(document.createTextNode(st))}}};if(!x&&B)if(I.style.display="none",p.style.display="",i&&R!=="none"){let ne=(pe=u.loadingAnimationDuration)!=null?pe:2e3;p.setAttribute("data-preserve-animation","true"),R==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),E(B,!1)):(p.classList.add(`persona-tool-loading-${R}`),p.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),R==="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)),E(B,!0))}else E(B,!1);else if(!x&&i&&R!=="none"){p.style.display="";let ne=(G=u.loadingAnimationDuration)!=null?G:2e3;if(p.setAttribute("data-preserve-animation","true"),R==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ne}ms`);else{p.classList.add(`persona-tool-loading-${R}`),p.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),R==="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 Se=p.textContent||f;p.textContent="",w(p,Se,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 Se=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);Se?S.appendChild(Se):S.textContent=a?"Hide":"Show";let ze=b("div","persona-flex persona-items-center persona-ml-auto");ze.append(S),l.append(m,ze)}else l.append(m);let T=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(T.setAttribute("data-persona-collapsed-preview","reasoning"),T.style.display="none",T.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let ne=(ce=(ve=t==null?void 0:t.reasoning)==null?void 0:ve.renderCollapsedPreview)==null?void 0:ce.call(ve,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});mb(T,ne)||(T.textContent=d),T.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,T),o;let _=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let U=n.chunks.join(""),Y=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=U||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(Y),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let Se=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);Se?S.appendChild(Se):S.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",T.style.display=a?"none":T.textContent||T.childNodes.length?"":"none"})(),o.append(l,T,_),o};var cs=new Set,fb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),hb=(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=as(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},bb=(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=hb(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?lm(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=Ol(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ol(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},_m=(e,t,n)=>{var m;let o=cs.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=Me(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")},Jl=(e,t)=>{var U,Y,he,fe,ae,Ee,ye,Oe,we;let n=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),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=(he=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?he:{},a=s.expandable!==!1,i=a&&cs.has(e.id),{summary:d,previewText:l,isActive:m}=bb(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((fe=n.startedAt)!=null?fe:Date.now()),v=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",C),K.textContent=oa(n),K},M=(Ee=o.renderCollapsedSummary)==null?void 0:Ee.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ae=s.collapsedMode)!=null?ae:"tool-call",isActive:m,config:t!=null?t:{},elapsed:oa(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(u.textContent=M,f.appendChild(u)):M instanceof HTMLElement?f.appendChild(M):(u.textContent=d,f.appendChild(u));let I=(ye=s.loadingAnimation)!=null?ye:"none",R=o.activeTextTemplate,W=o.completeTextTemplate,D=m?R:W,B=M instanceof HTMLElement,x=(K,pe,G)=>{let ve=G;for(let ce of pe){let ne=b("span","persona-tool-char");ne.style.setProperty("--char-index",String(ve)),ne.textContent=ce===" "?"\xA0":ce,K.appendChild(ne),ve++}return ve},w=(K,pe)=>{var ne;u.textContent="";let G=((ne=n.name)==null?void 0:ne.trim())||"tool",ve=yi(K,G),ce=0;for(let Se of ve){let ze=Se.styles.length>0?(()=>{let te=b("span",Se.styles.map(re=>`persona-tool-text-${re}`).join(" "));return u.appendChild(te),te})():u;if(Se.isDuration&&m)ze.appendChild(v());else{let te=Se.isDuration?oa(n):Se.text;pe?ce=x(ze,te,ce):ze.appendChild(document.createTextNode(te))}}};if(!B)if(m&&I!=="none"){let K=(Oe=o.loadingAnimationDuration)!=null?Oe:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),D&&w(D,!1);else if(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)w(D,!0);else{let pe=u.textContent||d;u.textContent="",x(u,pe,0)}}else D&&w(D,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let K=o.toggleTextColor||o.headerTextColor||"currentColor",pe=Me(i?"chevron-up":"chevron-down",16,K,2);pe?E.appendChild(pe):E.textContent=i?"Hide":"Show";let G=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");G.append(E),p.append(f,G)}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 K=(we=o.renderCollapsedPreview)==null?void 0:we.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});fb(S,K)||(S.textContent=l),S.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,S),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 K=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?K.style.color=o.contentTextColor:o.headerTextColor&&(K.style.color=o.headerTextColor),K.textContent=n.name,T.appendChild(K)}if(n.args!==void 0){let K=b("div","persona-space-y-1"),pe=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(pe.style.color=o.labelTextColor),pe.textContent="Arguments";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(G.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(G.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(G.style.color=o.codeBlockTextColor),G.textContent=as(n.args),K.append(pe,G),T.appendChild(K)}if(n.chunks&&n.chunks.length){let K=b("div","persona-space-y-1"),pe=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(pe.style.color=o.labelTextColor),pe.textContent="Activity";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(G.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(G.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(G.style.color=o.codeBlockTextColor),G.textContent=n.chunks.join(""),K.append(pe,G),T.appendChild(K)}if(n.status==="complete"&&n.result!==void 0){let K=b("div","persona-space-y-1"),pe=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(pe.style.color=o.labelTextColor),pe.textContent="Result";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(G.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(G.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(G.style.color=o.codeBlockTextColor),G.textContent=as(n.result),K.append(pe,G),T.appendChild(K)}if(n.status==="complete"&&typeof n.duration=="number"){let K=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(K.style.color=o.contentTextColor),K.textContent=`Duration: ${n.duration}ms`,T.appendChild(K)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let K=o.toggleTextColor||o.headerTextColor||"currentColor",pe=Me(i?"chevron-up":"chevron-down",16,K,2);pe?E.appendChild(pe):E.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(p,S,T),r};var dr=require("partial-json");var yb="ask_user_question",Zl=8,ds="data-persona-ask-sheet-for",vb="Other",xb="Other\u2026",$m="Type your own answer here",Um="Send",wb="Next",Cb="Back",Sb="Submit all",Ab="Skip",Tb=3,ec="data-ask-current-index",tc="data-ask-question-count",zm="data-ask-answers",nc="data-ask-grouped",qm="data-ask-layout",kb=e=>e.layout==="pills"?"pills":"rows",Eb=e=>e.getAttribute(qm)==="pills"?"pills":"rows",Vm=!1,jm=e=>e.replace(/["\\]/g,"\\$&"),Hr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===yb,oc=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ps=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,dr.parse)(r,dr.STR|dr.OBJ|dr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},wa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Zl&&!Vm&&(Vm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Zl}.`)),t.slice(0,Zl)},Mb=e=>{var t;return(t=wa(e)[0])!=null?t:null},Lb=(e,t)=>{var n;return(n=wa(e)[t])!=null?n:null},Ib=(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))},Km=(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},Rb=(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=Km(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Pb=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},Wb=(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<Tb;u++)s.appendChild(Pb(o));return s}if(d.forEach((u,C)=>{s.appendChild(Rb(u,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?vb:xb;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"),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:$m,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:u),v.appendChild(M),C.appendChild(v);let I=Km(o,a,d.length);I&&C.appendChild(I),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},Gm=(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:$m,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:Um,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Bb=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:Um,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Hb=(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:Cb,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:Ab,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:Sb:(f=n.nextLabel)!=null?f:wb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Dr=e=>{let t=e.getAttribute(zm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Ym=(e,t)=>{e.setAttribute(zm,JSON.stringify(t))},ho=e=>{var n;let t=Number((n=e.getAttribute(ec))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Db=(e,t)=>{e.setAttribute(ec,String(Math.max(0,Math.floor(t))))},us=e=>{var n;let t=Number((n=e.getAttribute(tc))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},pr=e=>e.getAttribute(nc)==="true",Fb=(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},Ob=(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)))},Ki=(e,t)=>{let{payload:n}=ps(t),o=wa(n),r=Dr(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},Xm=e=>{let t=Dr(e),n=ho(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=""},Qm=e=>{if(!pr(e))return;let t=Dr(e),n=ho(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}},rc=(e,t,n)=>{let o=oc(n),r=Eb(e),{payload:s,complete:a}=ps(t),i=pr(e),d=ho(e),l=us(e),m=i?Lb(s,d):Mb(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 R=typeof(m==null?void 0:m.question)=="string"?m.question:"";C.textContent=R,C.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=Wb(m,o,a,r);v.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Gm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!M?e.appendChild(Bb(o)):(!p||i)&&M&&M.remove(),e.setAttribute("data-multi-select",p?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=Hb(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();Xm(e),Qm(e)},Nb=(e,t,n)=>{let o=oc(t),r=kb(o),s=e.toolCall.id,a=wa(n),i=Math.max(1,a.length),d=i>1,l=Fb(e,a),m=d?Ob(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(ds,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(tc,String(i)),p.setAttribute(ec,String(m)),p.setAttribute(nc,d?"true":"false"),p.setAttribute(qm,r),Ym(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`),Ib(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 M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),p.appendChild(M),r!=="rows"&&p.appendChild(Gm(o,r)),rc(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},_b=(e,t,n)=>{let{payload:o}=ps(t),r=Math.max(1,wa(o).length);r>us(e)&&(e.setAttribute(tc,String(r)),r>1&&!pr(e)&&e.setAttribute(nc,"true")),rc(e,t,n)};var Gi=(e,t,n)=>{if(!n||!Hr(e)||oc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ds}]`).forEach(l=>{l.getAttribute(ds)!==r&&l.remove()});let a=n.querySelector(`[${ds}="${jm(r)}"]`);if(a){_b(a,e,t);return}let{payload:i}=ps(e),d=Nb(e,t,i);n.appendChild(d)},ms=(e,t)=>{if(!e)return;let n=t?`[${ds}="${jm(t)}"]`:`[${ds}]`;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)})},sc=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),ur=(e,t)=>{let n=Dr(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Ym(e,n),Xm(e),Qm(e)},Yi=(e,t,n,o)=>{let r=us(e),s=Math.max(0,Math.min(r-1,o));Db(e,s),rc(e,t,n)};var Xi=new Map,Vb=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.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)},Jm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Zm=(e,t)=>{var o,r,s;let n=(r=(o=Jm(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Xi.get(e))!=null?s:n==="expanded"},eg=(e,t,n)=>{var a,i;let o=Jm(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=Me(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},tg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Zm(e,n);eg(o,s,n),r.style.display=s?"":"none"};var Qi=(e,t)=>{var w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we;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=(E=o==null?void 0:o.borderColor)!=null?E:"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=Me(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=(T=o==null?void 0:o.title)!=null?T:"Approval Required",f.appendChild(u),!r){let K=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");K.setAttribute("data-approval-status",n.status),n.status==="approved"?(K.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",K.style.color="var(--persona-palette-colors-success-700, #15803d)",K.textContent="Approved"):n.status==="denied"?(K.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",K.style.color="var(--persona-palette-colors-error-700, #b91c1c)",K.textContent="Denied"):n.status==="timeout"&&(K.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",K.style.color="var(--persona-palette-colors-warning-700, #b45309)",K.textContent="Timeout"),f.appendChild(K)}p.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Fl(n.toolName):void 0,M=(_=o==null?void 0:o.formatDescription)==null?void 0:_.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{}}),I=!n.toolName,R=M||(I?n.description:`The assistant wants to use \u201C${v!=null?v:Vb(n.toolName)}\u201D.`),W=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");W.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(W.style.color=o.descriptionColor),W.textContent=R,p.appendChild(W);let D=(U=o==null?void 0:o.detailsDisplay)!=null?U:"collapsed",B=!!n.description&&!I,x=B||!!n.parameters;if(D!=="hidden"&&x){let K=Zm(e.id,t),pe=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");pe.type="button",pe.setAttribute("data-expand-header","true"),pe.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(pe.style.color=o.descriptionColor);let G=b("span");G.setAttribute("data-approval-details-label","true");let ve=b("span","persona-inline-flex persona-items-center");ve.setAttribute("data-approval-details-chevron","true"),pe.append(G,ve),eg(pe,K,t),p.appendChild(pe);let ce=b("div");if(ce.setAttribute("data-approval-details","true"),ce.style.display=K?"":"none",B){let ne=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ne.style.color=o.descriptionColor),ne.textContent=n.description,ce.appendChild(ne)}if(n.parameters){let ne=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&&(ne.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ne.style.color=o.parameterTextColor),ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",ne.textContent=as(n.parameters),ce.appendChild(ne)}p.appendChild(ce)}if(r){let K=b("div","persona-flex persona-gap-2 persona-mt-2");K.setAttribute("data-approval-buttons","true");let pe=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");pe.type="button",pe.style.backgroundColor=(Y=o==null?void 0:o.approveButtonColor)!=null?Y:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(he=o==null?void 0:o.approveButtonTextColor)!=null?he:"#ffffff",pe.setAttribute("data-approval-action","approve");let G=Me("shield-check",14,(fe=o==null?void 0:o.approveButtonTextColor)!=null?fe:"#ffffff",2);G&&(G.style.marginRight="4px",pe.appendChild(G));let ve=document.createTextNode((ae=o==null?void 0:o.approveLabel)!=null?ae:"Approve");pe.appendChild(ve);let ce=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");ce.type="button",ce.style.backgroundColor=(Ee=o==null?void 0:o.denyButtonColor)!=null?Ee:"transparent",ce.style.color=(ye=o==null?void 0:o.denyButtonTextColor)!=null?ye:"var(--persona-feedback-error, #dc2626)",ce.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ce.setAttribute("data-approval-action","deny");let ne=Me("shield-x",14,(Oe=o==null?void 0:o.denyButtonTextColor)!=null?Oe:"var(--persona-feedback-error, #dc2626)",2);ne&&(ne.style.marginRight="4px",ce.appendChild(ne));let Se=document.createTextNode((we=o==null?void 0:o.denyLabel)!=null?we:"Deny");ce.appendChild(Se),K.append(pe,ce),p.appendChild(K)}return a.append(i,p),s.appendChild(a),s};var ng=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 Ca=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 Sa=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 $b=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ub=new Set(["step_start","execution_start"]),zb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),qb=new Set(["step_complete","agent_turn_complete"]),jb=new Set(["flow_complete","agent_complete"]),og=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),sg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eo=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Fr=(e,t)=>{let n=e[t];return sg(n)?n:void 0};function ac(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ji(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Kb(e,t){return typeof t.type=="string"?t.type:e}function Gb(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 Yb(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 rg(e){var o,r,s,a,i;let t=Fr(e,"result"),n=[Fr(e,"tokens"),Fr(e,"totalTokens"),t?Fr(t,"tokens"):void 0,Fr(e,"usage"),t?Fr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=eo(d.output))!=null?o:eo(d.outputTokens))!=null?r:eo(d.completionTokens);if(l!==void 0)return l}return(i=(s=eo(e.outputTokens))!=null?s:eo(e.completionTokens))!=null?i:t?(a=eo(t.outputTokens))!=null?a:eo(t.completionTokens):void 0}function Xb(e){var n,o,r,s,a;let t=Fr(e,"result");return(a=(r=(o=(n=eo(e.executionTime))!=null?n:eo(e.executionTimeMs))!=null?o:eo(e.execution_time))!=null?r:eo(e.duration))!=null?a:t?(s=eo(t.executionTime))!=null?s:eo(t.executionTimeMs):void 0}function Qb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Aa=class{constructor(t=Qb){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:Ji(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(!sg(n)){og.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Kb(t,n),r=this.now();if($b.has(o)){this.startRun(r);return}if(Ub.has(o)){this.run||this.startRun(r);return}if(zb.has(o)){if(!Yb(o,n))return;let a=Gb(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+ac(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ji(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(qb.has(o)){if(!this.run)return;let a=this.run,i=rg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+ac(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ji(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(jb.has(o)){if(!this.run)return;let a=this.run,i=rg(n),d=i!=null?i:a.exactOutputTokens+ac(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ji(d,m),outputTokens:d,durationMs:m,source:l},this.run=null;return}if(og.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=Xb(n);return s!=null?s:o-t.startedAt}};function gs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Jb={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)"}},Zb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ey=["flowName","stepName","reasoningText","text","name","tool","toolName"],ty=100;function ny(e,t){let n={...Jb,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Zb}function oy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ry(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 sy(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 ay(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 iy(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 ly(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function cy(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 dy(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 ic(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");gs(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 U,Y;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"),M=Me(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.appendChild(M);let I=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=(U=o.timestampFormat)!=null?U:"relative";I.textContent=R==="relative"?oy(e.timestamp,n):ry(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let D=ny(e.type,o.badgeColors),B=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");B.style.backgroundColor=D.bg,B.style.color=D.text,B.style.borderColor=D.text+"50",B.textContent=e.type;let x=(Y=o.descriptionFields)!=null?Y:ey,w=sy(e.payload,x),E=null;w&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=w);let S=b("div","persona-flex-1 persona-min-w-0"),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"),_=Me("clipboard","12px","currentColor",1.5);return _&&T.appendChild(_),T.addEventListener("click",async he=>{he.stopPropagation(),await ay(iy(e)),T.innerHTML="";let fe=Me("check","12px","currentColor",1.5);fe&&T.appendChild(fe),setTimeout(()=>{T.innerHTML="";let ae=Me("clipboard","12px","currentColor",1.5);ae&&T.appendChild(ae)},1500)}),C.appendChild(v),C.appendChild(I),W&&C.appendChild(W),C.appendChild(B),E&&C.appendChild(E),C.appendChild(S),C.appendChild(T),u.appendChild(C),d&&u.appendChild(dy(e,a,i)),u}}function ag(e){var C,v,M,I,R;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=(M=i==null?void 0:i.label)!=null?M:"",p=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},f=s.find(W=>W.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let W=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(W)return{element:W,update:()=>{},destroy:()=>{}}}return u();function u(){let W=p.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");gs(D,W==null?void 0:W.panel);let B=[],x="",w="",E=null,S=[],T={},_=0,U=Ii(),Y=0,he=0,fe=!1,ae=null,Ee=!1,ye=0,Oe=new Set,we=new Map,K="",pe="",G=null,ve,ce,ne,Se,ze,te=null,re=null,ie=null;function st(){let se=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ce=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");gs(Ce,W==null?void 0:W.headerBar);let kt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(kt.textContent="Events",ve=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"),ve.textContent="0",a){re=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),re.style.cursor="help";let On=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");On.textContent="Throughput",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",ie=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"),ie.style.display="none",ie.style.pointerEvents="none";let no=re,Tn=ie,Nn=()=>{if(!Tn.textContent)return;let Lo=no.getBoundingClientRect(),_n=se.getBoundingClientRect();Tn.style.left=`${Lo.left-_n.left}px`,Tn.style.top=`${Lo.bottom-_n.top+4}px`,Tn.style.display="block"},bt=()=>{Tn.style.display="none"};re.addEventListener("mouseenter",Nn),re.addEventListener("mouseleave",bt),re.appendChild(On),re.appendChild(te)}let Kt=b("div","persona-flex-1");ce=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 tn=b("option","");tn.value="",tn.textContent="All events",ce.appendChild(tn),ne=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"),ne.type="button",ne.title="Copy All";let Wt=Me("clipboard-copy","12px","currentColor",1.5);Wt&&ne.appendChild(Wt);let Mt=b("span","persona-text-xs");Mt.textContent="Copy All",ne.appendChild(Mt),Ce.appendChild(kt),Ce.appendChild(ve),re&&Ce.appendChild(re),Ce.appendChild(Kt),Ce.appendChild(ce),Ce.appendChild(ne);let wt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");gs(wt,W==null?void 0:W.searchBar);let St=Me("search","14px","var(--persona-muted, #9ca3af)",1.5),Gt=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");St&&Gt.appendChild(St),Se=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"),gs(Se,W==null?void 0:W.searchInput),Se.type="text",Se.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 ot=Me("x","12px","currentColor",2);return ot&&ze.appendChild(ot),wt.appendChild(Gt),wt.appendChild(Se),wt.appendChild(ze),se.appendChild(Ce),se.appendChild(wt),ie&&se.appendChild(ie),se}let Te,ue=s.find(se=>se.renderEventStreamToolbar);if(ue!=null&&ue.renderEventStreamToolbar&&r){let se=ue.renderEventStreamToolbar({config:r,defaultRenderer:()=>st(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Ce=>{x=Ce,Fn(),V()},onSearchChange:Ce=>{w=Ce,Fn(),V()}});Te=se!=null?se:st()}else Te=st();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 Be(){if(!a||!te||!re)return;let se=a();te.textContent=ly(se);let Ce=cy(se);ie&&(ie.textContent=Ce,Ce||(ie.style.display="none")),Ce?re.setAttribute("aria-label",Ce):re.removeAttribute("aria-label")}let me=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Q=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Q.style.height="100%";let _e=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");gs(_e,W==null?void 0:W.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ht=Me(l,"14px","currentColor",2);Ht&&_e.appendChild(Ht);let be=b("span","");be.textContent=m,_e.appendChild(be);let de=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");de.style.display="none",me.appendChild(Q),me.appendChild(de),me.appendChild(_e),D.setAttribute("tabindex","0"),D.appendChild(Te),D.appendChild(Ue),D.appendChild(me);function Pn(){let se=t.getAll(),Ce={};for(let Mt of se)Ce[Mt.type]=(Ce[Mt.type]||0)+1;let kt=Object.keys(Ce).sort(),Kt=kt.length!==S.length||!kt.every((Mt,wt)=>Mt===S[wt]),tn=!Kt&&kt.some(Mt=>Ce[Mt]!==T[Mt]),An=se.length!==Object.values(T).reduce((Mt,wt)=>Mt+wt,0);if(!Kt&&!tn&&!An||(S=kt,T=Ce,!ce))return;let Wt=ce.value;if(ce.options[0].textContent="All events",Kt){for(;ce.options.length>1;)ce.remove(1);for(let Mt of kt){let wt=b("option","");wt.value=Mt,wt.textContent=`${Mt} (${Ce[Mt]||0})`,ce.appendChild(wt)}Wt&&kt.includes(Wt)?ce.value=Wt:Wt&&(ce.value="",x="")}else for(let Mt=1;Mt<ce.options.length;Mt++){let wt=ce.options[Mt];wt.textContent=`${wt.value} (${Ce[wt.value]||0})`}}function Ut(){let se=t.getAll();if(x&&(se=se.filter(Ce=>Ce.type===x)),w){let Ce=w.toLowerCase();se=se.filter(kt=>kt.type.toLowerCase().includes(Ce)||kt.payload.toLowerCase().includes(Ce))}return se}function gn(){return x!==""||w!==""}function Fn(){_=0,Y=0,U.resume(),_e.style.display="none"}function to(se){Oe.has(se)?Oe.delete(se):Oe.add(se),G=se;let Ce=Q.scrollTop,kt=U.isFollowing();Ee=!0,U.pause(),V(),Q.scrollTop=Ce,kt&&U.resume(),Ee=!1}function qe(){return pa(Q,50)}function V(){he=Date.now(),fe=!1,Be(),Pn();let se=t.getEvictedCount();se>0?(Ue.textContent=`${se.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",B=Ut();let Ce=B.length,kt=t.getSize()>0;ve&&(ve.textContent=String(t.getSize())),Ce===0&&kt&&gn()?(de.textContent=w?`No events matching '${w}'`:"No events matching filter",de.style.display="",Q.style.display="none"):(de.style.display="none",Q.style.display=""),ne&&(ne.title=gn()?`Copy Filtered (${Ce})`:"Copy All"),d&&!U.isFollowing()&&Ce>_&&(Y+=Ce-_,be.textContent=m?`${m}${Y>0?` (${Y})`:""}`:"",_e.style.display=""),_=Ce;let Kt=t.getAll(),tn=Kt.length>0?Kt[0].timestamp:0,An=new Set(B.map(wt=>wt.id));for(let wt of Oe)An.has(wt)||Oe.delete(wt);let Wt=x!==K||w!==pe,Mt=we.size===0&&B.length>0;if(Wt||Mt||B.length===0){Q.innerHTML="",we.clear();let wt=document.createDocumentFragment();for(let St=0;St<B.length;St++){let Gt=ic(B[St],St,tn,p,Oe,to,s,r);we.set(B[St].id,Gt),wt.appendChild(Gt)}Q.appendChild(wt),K=x,pe=w,G=null}else{if(G!==null){let St=we.get(G);if(St&&St.parentNode===Q){let Gt=B.findIndex(ot=>ot.id===G);if(Gt>=0){let ot=ic(B[Gt],Gt,tn,p,Oe,to,s,r);Q.insertBefore(ot,St),St.remove(),we.set(G,ot)}}G=null}let wt=new Set(B.map(St=>St.id));for(let[St,Gt]of we)wt.has(St)||(Gt.remove(),we.delete(St));for(let St=0;St<B.length;St++){let Gt=B[St];if(!we.has(Gt.id)){let ot=ic(Gt,St,tn,p,Oe,to,s,r);we.set(Gt.id,ot),Q.appendChild(ot)}}}U.isFollowing()&&(Q.scrollTop=Q.scrollHeight)}function Le(){if(Date.now()-he>=ty){ae!==null&&(cancelAnimationFrame(ae),ae=null),V();return}fe||(fe=!0,ae=requestAnimationFrame(()=>{ae=null,V()}))}let He=(se,Ce)=>{if(!ne)return;ne.innerHTML="";let kt=Me(se,"12px","currentColor",1.5);kt&&ne.appendChild(kt);let Kt=b("span","persona-text-xs");Kt.textContent="Copy All",ne.appendChild(Kt),setTimeout(()=>{ne.innerHTML="";let tn=Me("clipboard-copy","12px","currentColor",1.5);tn&&ne.appendChild(tn);let An=b("span","persona-text-xs");An.textContent="Copy All",ne.appendChild(An),ne.disabled=!1},Ce)},De=async()=>{if(ne){ne.disabled=!0;try{let se;gn()?se=B:n?(se=await n(),se.length===0&&(se=t.getAll())):se=t.getAll();let Ce=se.map(kt=>{try{return JSON.parse(kt.payload)}catch{return kt.payload}});await navigator.clipboard.writeText(JSON.stringify(Ce,null,2)),He("check",1500)}catch{He("x",1500)}}},Ve=()=>{ce&&(x=ce.value,Fn(),V())},mt=()=>{!Se||!ze||(ze.style.display=Se.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{w=Se.value,Fn(),V()},150))},at=()=>{!Se||!ze||(Se.value="",w="",ze.style.display="none",E&&clearTimeout(E),Fn(),V())},Pt=()=>{if(Ee)return;let se=Q.scrollTop,{action:Ce,nextLastScrollTop:kt}=Ri({following:U.isFollowing(),currentScrollTop:se,lastScrollTop:ye,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=kt,Ce==="resume"?(U.resume(),Y=0,_e.style.display="none"):Ce==="pause"&&(U.pause(),d&&(be.textContent=m,_e.style.display=""))},jt=se=>{let Ce=Pi({following:U.isFollowing(),deltaY:se.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});Ce==="pause"?(U.pause(),d&&(be.textContent=m,_e.style.display="")):Ce==="resume"&&(U.resume(),Y=0,_e.style.display="none")},j=()=>{d&&(Q.scrollTop=Q.scrollHeight,U.resume(),Y=0,_e.style.display="none")},zt=se=>{let Ce=se.target;if(!Ce||Ce.closest("button"))return;let kt=Ce.closest("[data-event-id]");if(!kt)return;let Kt=kt.getAttribute("data-event-id");Kt&&to(Kt)},Ze=se=>{if((se.metaKey||se.ctrlKey)&&se.key==="f"){se.preventDefault(),Se==null||Se.focus(),Se==null||Se.select();return}se.key==="Escape"&&(Se&&document.activeElement===Se?(at(),Se.blur(),D.focus()):o&&o())};ne&&ne.addEventListener("click",De),ce&&ce.addEventListener("change",Ve),Se&&Se.addEventListener("input",mt),ze&&ze.addEventListener("click",at),Q.addEventListener("scroll",Pt),Q.addEventListener("wheel",jt,{passive:!0}),Q.addEventListener("click",zt),_e.addEventListener("click",j),D.addEventListener("keydown",Ze);function Vt(){E&&clearTimeout(E),ae!==null&&(cancelAnimationFrame(ae),ae=null),fe=!1,we.clear(),ne&&ne.removeEventListener("click",De),ce&&ce.removeEventListener("change",Ve),Se&&Se.removeEventListener("input",mt),ze&&ze.removeEventListener("click",at),Q.removeEventListener("scroll",Pt),Q.removeEventListener("wheel",jt),Q.removeEventListener("click",zt),_e.removeEventListener("click",j),D.removeEventListener("keydown",Ze)}return{element:D,update:Le,destroy:Vt}}}function ig(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 lg=(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:()=>ig(e,t)});if(m)return m}return ig(e,t)};var lc=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)})}},Or=new lc;Or.register("PersonaArtifactCard",lg);function py(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 cg(e,t){var ce,ne,Se,ze;let n=(ne=(ce=e.features)==null?void 0:ce.artifacts)==null?void 0:ne.layout,r=((Se=n==null?void 0:n.toolbarPreset)!=null?Se:"default")==="document",s=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?ui(e.markdown):null,i=mi(e.sanitize),d=te=>{let re=a?a(te):ta(te);return i?i(re):re},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.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 te;m(),(te=t.onDismiss)==null||te.call(t)});let v="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?Sn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Sn({icon:"eye",label:"Rendered view"}),R=r?Sn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Sn({icon:"code-2",label:"Source"}),W=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,x=n==null?void 0:n.documentToolbarCopyMenuItems,w=!!(B&&x&&x.length>0),E=null,S,T=null,_=null;if(r&&(D||B)&&!w){if(S=D?Kl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Sn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let te=Me("chevron-down",14,"currentColor",2);te&&S.appendChild(te)}}else r&&w?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?Kl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Sn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=Sn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),E.append(S,T)):r?S=Sn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Sn({icon:"copy",label:"Copy"});let U=r?Sn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Sn({icon:"refresh-cw",label:"Refresh"}),Y=r?Sn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Sn({icon:"x",label:"Close"}),he=()=>{var Te,ue,Ue;let te=(Te=we.find(Be=>Be.id===K))!=null?Te:we[we.length-1],re=(ue=te==null?void 0:te.id)!=null?ue:null,ie=(te==null?void 0:te.artifactType)==="markdown"&&(Ue=te.markdown)!=null?Ue:"",st=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:ie,jsonPayload:st,id:re}},fe=async()=>{var Te;let{markdown:te,jsonPayload:re}=he(),ie=(Te=we.find(ue=>ue.id===K))!=null?Te:we[we.length-1],st=(ie==null?void 0:ie.artifactType)==="markdown"?te:ie?re:"";try{await navigator.clipboard.writeText(st)}catch{}};if(S.addEventListener("click",async()=>{let te=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(te&&w){let{markdown:re,jsonPayload:ie,id:st}=he();try{await te({actionId:"primary",artifactId:st,markdown:re,jsonPayload:ie})}catch{}return}await fe()}),T&&(x!=null&&x.length)){let te=()=>{var ie;return(ie=p.closest("[data-persona-root]"))!=null?ie:document.body},re=()=>{_=is({items:x.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:st,jsonPayload:Te,id:ue}=he(),Ue=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ue?await Ue({actionId:ie,artifactId:ue,markdown:st,jsonPayload:Te}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(st):ie==="json"||ie==="source"?await navigator.clipboard.writeText(Te):await navigator.clipboard.writeText(st||Te)}catch{}},anchor:E!=null?E:T,position:"bottom-right",portal:te()})};p.isConnected?re():requestAnimationFrame(re),T.addEventListener("click",ie=>{ie.stopPropagation(),_==null||_.toggle()})}U.addEventListener("click",async()=>{var te;try{await((te=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:te.call(n))}catch{}G()}),Y.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let ae=()=>{r&&(I.setAttribute("aria-pressed",v==="rendered"?"true":"false"),R.setAttribute("aria-pressed",v==="source"?"true":"false"))};I.addEventListener("click",()=>{v="rendered",ae(),G()}),R.addEventListener("click",()=>{v="source",ae(),G()});let Ee=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(f.replaceChildren(),M.append(I,R),E?W.append(E,U,Y):W.append(S,U,Y),f.append(M,Ee,W),ae()):(f.appendChild(u),f.appendChild(C)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let ye=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&&(ye.style.paddingLeft=s,ye.style.paddingRight=s,Oe.style.padding=s),p.appendChild(f),p.appendChild(ye),p.appendChild(Oe);let we=[],K=null,pe=!1,G=()=>{var st,Te,ue,Ue;let te=r&&we.length<=1;ye.classList.toggle("persona-hidden",te),ye.replaceChildren();for(let Be of we){let me=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");me.type="button",me.textContent=Be.title||Be.id.slice(0,8),Be.id===K&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>t.onSelect(Be.id)),ye.appendChild(me)}Oe.replaceChildren();let re=K&&we.find(Be=>Be.id===K)||we[we.length-1];if(!re)return;if(r){let Be=re.artifactType==="markdown"?"MD":(st=re.component)!=null?st:"Component",Q=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ee.textContent=`${Q} \xB7 ${Be}`}else u.textContent="Artifacts";if(re.artifactType==="markdown"){if(r&&v==="source"){let me=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(Te=re.markdown)!=null?Te:"",Oe.appendChild(me);return}let Be=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Be.innerHTML=d((ue=re.markdown)!=null?ue:""),Oe.appendChild(Be);return}let ie=re.component?Or.get(re.component):void 0;if(ie){let me={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Q=ie((Ue=re.props)!=null?Ue:{},me);if(Q){Oe.appendChild(Q);return}}catch{}}Oe.appendChild(py(re))},ve=()=>{var re;let te=we.length>0;if(p.classList.toggle("persona-hidden",!te),l){let ie=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,Te=((re=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?re:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&Te&&pe?(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(te){var re,ie,st;we=te.artifacts,K=(st=(ie=te.selectedId)!=null?ie:(re=te.artifacts[te.artifacts.length-1])==null?void 0:re.id)!=null?st:null,we.length>0&&(pe=!0),G(),ve()},setMobileOpen(te){pe=te,!te&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ve()}}}function bo(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 dg(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"),!bo(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 uy(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 Zi(e,t){var d,l,m,p,f,u,C,v,M,I;if(!bo(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"),uy(e),dg(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=(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"),dg(e,t)}var pg=["panel","seamless"];function el(e,t){var i,d,l,m,p,f;for(let u of pg)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"),!bo(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=pg.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 ug(e,t){var n,o,r;return!t||!bo(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function my(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 gy(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 fy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function hy(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function mg(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 gg(e,t,n,o,r,s){let a=my(r,200),i=hy(t,n,o,200);i=Math.max(a,i);let d=gy(s);return d!==null&&(i=Math.min(i,d)),fy(e,a,i)}var fg={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"}},cc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var C,v,M;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=fg[a])!=null?v:fg.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 x,w;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let W=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");W.textContent=I.label,R.appendChild(W);let D=(x=I.type)!=null?x:"text",B;D==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=D),B.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",B.id=`${t.id}-${a}-${I.name}`,B.name=I.name,B.placeholder=(w=I.placeholder)!=null?w:"",I.required&&(B.required=!0),R.appendChild(B),m.appendChild(R)});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=(M=i.submitLabel)!=null?M:"Submit",p.appendChild(f),p.appendChild(u),m.appendChild(p),s.replaceChildren(d,m),m.addEventListener("submit",async I=>{var B,x;I.preventDefault();let R=(B=n.formEndpoint)!=null?B:"/form",W=new FormData(m),D={};W.forEach((w,E)=>{D[E]=w}),D.type=a,u.disabled=!0,f.textContent="Submitting\u2026";try{let w=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!w.ok)throw new Error(`Form submission failed (${w.status})`);let E=await w.json();f.textContent=(x=E.message)!=null?x:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(w){f.textContent=w instanceof Error?w.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var dc=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()}},pc=new dc;var hg=()=>{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 by=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yy=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},mc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=by(e),n=yy(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}},uc=e=>typeof e=="string"?e:e==null?"":String(e),Ta={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:uc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=uc(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:uc(n.text)}}},bg=e=>Array.isArray(e)?e.map(t=>String(t)):[],gc=e=>{let t=new Set(bg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(bg(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 vy=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}},xy=e=>e.map(t=>({...t,streaming:!1})),wy=e=>e.map(t=>({...t,status:"complete"})),yg=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?vy(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?xy(n.messages):void 0,artifacts:n.artifacts?wy(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var fc=require("partial-json");function vg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Or.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 xg(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 wg(e){let t=xg(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 Cg(e){let t=xg(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 Cy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Sg(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=Cy}=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 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 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,R.forEach((E,C)=>{let k=C<v;E.classList.toggle("selected",k),E.setAttribute("aria-checked",C===v-1?"true":"false")})}),R.push(x),L.appendChild(x)}g.appendChild(L);let I=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),v.appendChild(I),g.appendChild(v)}let D=document.createElement("div");D.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=i,F.addEventListener("click",()=>{n==null||n(),m.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(u===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let v=(I==null?void 0:I.value.trim())||void 0;await t(u,v),m.remove()}catch(v){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),D.appendChild(F),D.appendChild(B),g.appendChild(D),m.appendChild(g),m}function uf(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 L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=r,w.appendChild(L),p.appendChild(w);let R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-nps",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=l;let F=document.createElement("span");F.className="persona-feedback-label-high",F.textContent=m,I.appendChild(D),I.appendChild(F);let B=document.createElement("div");B.className="persona-feedback-numbers";let v=[];for(let O=0;O<=10;O++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${O} out of 10`),U.textContent=String(O),U.dataset.rating=String(O),O<=6?U.classList.add("persona-feedback-detractor"):O<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{g=O,v.forEach((K,fe)=>{K.classList.toggle("selected",fe===O),K.setAttribute("aria-checked",fe===O?"true":"false")})}),v.push(U),B.appendChild(U)}R.appendChild(I),R.appendChild(B),p.appendChild(R);let x=null;if(d){let O=document.createElement("div");O.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"),O.appendChild(x),p.appendChild(O)}let E=document.createElement("div");E.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 k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(g===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let O=(x==null?void 0:x.value.trim())||void 0;await t(g,O),u.remove()}catch(O){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),E.appendChild(C),E.appendChild(k),p.appendChild(E),u.appendChild(p),u}var cs="persona-chat-history",cy=30*1e3,dy={"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 py(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=dy[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 Qi(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 uy(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 my(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var pc=e=>!e||typeof e!="object"?{}:{...e},mf=e=>e.map(t=>({...t,streaming:!1})),ff=(e,t,n)=>{let o=e!=null&&e.markdown?di(e.markdown):null,r=pi(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=Ys(a),r?r(d):d}};function gf(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=ke(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 hf=(e,t,n)=>{var Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,fd,gd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd;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=Eu(t),r=ac.getForInstance(o.plugins);o.components&&Br.registerAll(o.components);let s=of(),i=o.persistState===!1?null:(Wc=o.storageAdapter)!=null?Wc:sf(),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=pc(h.metadata)),(Bc=h.messages)!=null&&Bc.length&&(o={...o,initialMessages:h.messages}),(Hc=h.artifacts)!=null&&Hc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Dc=h.selectedArtifactId)!=null?Dc: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:{}});(Fc=c.messages)!=null&&Fc.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:{},_r()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[lc],S=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[va.message,va.messageAndClick],L=cc({parsers:w,handlers:S,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let R=(Nc=(Oc=o.launcher)==null?void 0:Oc.enabled)!=null?Nc:!0,I=(Vc=(_c=o.launcher)==null?void 0:_c.autoExpand)!=null?Vc:!1,D=($c=o.autoFocusInput)!=null?$c:!1,F=I,B=R,v=(zc=(Uc=o.layout)==null?void 0:Uc.header)==null?void 0:zc.layout,x=!1,E=()=>pa(o),C=()=>R||E(),k=E()?!1:R?I:!0,O=!1,U=null,K=()=>{O=!0,U&&clearTimeout(U),U=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},fe=ff(o,L,K),ae=(jc=(qc=o.features)==null?void 0:qc.showReasoning)!=null?jc:!0,ge=(Gc=(Kc=o.features)==null?void 0:Kc.showToolCalls)!=null?Gc:!0,le=(Xc=(Yc=o.features)==null?void 0:Yc.showEventStreamToggle)!=null?Xc:!1,ye=(Jc=(Qc=o.features)==null?void 0:Qc.scrollToBottom)!=null?Jc:{},xe=`${(ed=typeof o.persistState=="object"?(Zc=o.persistState)==null?void 0:Zc.keyPrefix:void 0)!=null?ed:"persona-"}event-stream`,J=le?new ba(xe):null,Ie=(od=(nd=(td=o.features)==null?void 0:td.eventStream)==null?void 0:nd.maxEvents)!=null?od:2e3,X=le?new ha(Ie,J):null,we=le?new ya:null,Ae=null,pe=!1,Ce=null,qe=0;J==null||J.open().then(()=>X==null?void 0:X.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ne={onCopy:c=>{var f,h;s.emit("message:copy",c),M!=null&&M.isClientTokenMode()&&M.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),M!=null&&M.isClientTokenMode()&&M.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)}},oe=(rd=o.statusIndicator)!=null?rd:{},se=c=>{var f,h,y,W;return c==="idle"?(f=oe.idleText)!=null?f:hn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:hn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:hn.connected:c==="error"?(W=oe.errorText)!=null?W:hn.error:hn[c]};function ot(c,f,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let W=document.createElement("a");W.href=h.idleLink,W.target="_blank",W.rel="noopener noreferrer",W.textContent=f,W.style.color="inherit",W.style.textDecoration="none",c.appendChild(W)}else c.textContent=f}let{wrapper:ve,panel:ce,pillRoot:ze}=km(o),De=Em(o,C()),{container:de,body:Y,messagesWrapper:$e,suggestions:Mt,textarea:ue,sendButton:ie,sendButtonWrapper:In,composerForm:_t,statusText:cn,introTitle:Fn,introSubtitle:Zn,closeButton:je,iconHolder:V,headerTitle:Ee,headerSubtitle:Fe,header:Oe,footer:Ue,actionsRow:pt,leftActions:rt,rightActions:Tt}=De,$t=De.setSendButtonMode,j=De.micButton,Vt=De.micButtonWrapper,Je=De.attachmentButton,Ot=De.attachmentButtonWrapper,re=De.attachmentInput,he=De.attachmentPreviewsContainer;de.classList.add("persona-relative"),Y.classList.add("persona-relative");let wt=12,Ut=()=>{var c;return(c=ye.label)!=null?c:""},Zt=()=>{var c;return(c=ye.iconName)!=null?c:"arrow-down"},vn=()=>ye.enabled!==!1,kt=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");kt.type="button",kt.style.display="none",kt.setAttribute("data-persona-scroll-to-bottom","true");let Ct=b("span","persona-flex persona-items-center"),ht=b("span","");kt.append(Ct,ht),de.appendChild(kt);let yt=()=>{let f=Ue.style.display==="none"?0:Ue.offsetHeight;kt.style.bottom=`${f+wt}px`};yt();let qt=()=>{let c=!!Ut();kt.setAttribute("aria-label",Ut()||"Jump to latest"),kt.title=Ut(),kt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Ct.innerHTML="";let f=ke(Zt(),"14px","currentColor",2);f?(Ct.appendChild(f),Ct.style.display=""):Ct.style.display="none",ht.textContent=Ut(),ht.style.display=c?"":"none"};qt();let tt=null,On=null,eo=r.find(c=>c.renderHeader);if(eo!=null&&eo.renderHeader){let c=eo.renderHeader({config:o,defaultRenderer:()=>{let f=Ir({config:o,showClose:C()});return ma(de,f,o),f.header},onClose:()=>Ht(!1,"user")});if(c){let f=de.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Oe=c)}}let xn=()=>{var f,h,y,W;if(!X)return;if(pe=!0,!Ae&&X&&(Ae=Km({buffer:X,getFullHistory:()=>X.getAllFromStore(),onClose:()=>Nn(),config:o,plugins:r,getThroughput:()=>{var _;return(_=we==null?void 0:we.getMetric())!=null?_:{status:"idle"}}})),Ae&&(Y.style.display="none",(f=Ue.parentNode)==null||f.insertBefore(Ae.element,Ue),Ae.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let _=(W=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:W.toggleButtonActive;_&&_.split(/\s+/).forEach($=>$&&mt.classList.add($))}let c=()=>{if(!pe)return;let _=Date.now();_-qe>=200&&(Ae==null||Ae.update(),qe=_),Ce=requestAnimationFrame(c)};qe=0,Ce=requestAnimationFrame(c),Fo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,f,h;if(pe){if(pe=!1,Ae&&Ae.element.remove(),Y.style.display="",mt){mt.style.boxShadow="";let y=(h=(f=(c=o.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(W=>W&&mt.classList.remove(W))}Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Fo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(le){let c=(ad=(sd=o.features)==null?void 0:sd.eventStream)==null?void 0:ad.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=b("button",f),mt.style.width="28px",mt.style.height="28px",mt.style.color=Ln.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let h=ke("activity","18px","currentColor",1.5);h&&mt.appendChild(h);let y=De.clearChatButtonWrapper,W=De.closeButtonWrapper,_=y||W;_&&_.parentNode===Oe?Oe.insertBefore(mt,_):Oe.appendChild(mt),mt.addEventListener("click",()=>{pe?Nn():xn()})}let So=c=>{var y,W,_;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let $=c.querySelector("[data-persona-composer-form]");$!=null&&$.parentNode?$.parentNode.insertBefore(h,$):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let $=b("input");$.type="file",$.accept=((y=f.allowedTypes)!=null?y:$o).join(","),$.multiple=((W=f.maxFiles)!=null?W:4)>1,$.style.display="none",$.setAttribute("aria-label",(_=f.buttonTooltipText)!=null?_:"Attach files"),c.appendChild($)}},_n=r.find(c=>c.renderComposer);if(_n!=null&&_n.renderComposer){let c=o.composer,f=_n.renderComposer({config:o,defaultRenderer:()=>zi({config:o}).footer,onSubmit:h=>{var $;if(!M||M.isStreaming())return;let y=h.trim(),W=($=tt==null?void 0:tt.hasAttachments())!=null?$:!1;if(!y&&!W)return;Ss();let _;W&&(_=[],_.push(...tt.getContentParts()),y&&_.push(Bl(y))),M.sendMessage(y,{contentParts:_}),W&&tt.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:((id=o.voiceRecognition)==null?void 0:id.enabled)===!0?()=>{On==null||On()}:void 0});f&&(Ue.replaceWith(f),Ue=f)}let ur=c=>{let f=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),W=c.querySelector("[data-persona-composer-mic]"),_=c.querySelector("[data-persona-composer-status]");f&&(_t=f),h&&(ue=h),y&&(ie=y),W&&(j=W,Vt=W.parentElement),_&&(cn=_);let $=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(Mt=$);let q=c.querySelector(".persona-attachment-button");q&&(Je=q,Ot=q.parentElement),re=c.querySelector('input[type="file"]'),he=c.querySelector(".persona-attachment-previews");let N=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(pt=N)};So(Ue),ur(Ue);let Rn=(ud=(ld=o.layout)==null?void 0:ld.contentMaxWidth)!=null?ud:E()?(pd=(dd=(cd=o.launcher)==null?void 0:cd.composerBar)==null?void 0:dd.contentMaxWidth)!=null?pd:"720px":void 0;if(Rn&&($e.style.maxWidth=Rn,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),Rn&&_t&&!E()&&(_t.style.maxWidth=Rn,_t.style.marginLeft="auto",_t.style.marginRight="auto"),Rn&&Mt&&!E()&&(Mt.style.maxWidth=Rn,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),Rn&&he&&!E()&&(he.style.maxWidth=Rn,he.style.marginLeft="auto",he.style.marginRight="auto"),(md=o.attachments)!=null&&md.enabled&&re&&he){tt=oa.fromConfig(o.attachments),tt.setPreviewsContainer(he),re.addEventListener("change",h=>{let y=h.target;tt==null||tt.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,f=gf(c);de.appendChild(f)}(()=>{var y,W;let c=(W=(y=o.layout)==null?void 0:y.slots)!=null?W:{},f=_=>{switch(_){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return Mt;case"composer":return _t;case"footer-bottom":return cn;default:return null}},h=(_,$)=>{var q;switch(_){case"header-left":case"header-center":case"header-right":if(_==="header-left")Oe.insertBefore($,Oe.firstChild);else if(_==="header-right")Oe.appendChild($);else{let N=Oe.querySelector(".persona-flex-col");N?(q=N.parentNode)==null||q.insertBefore($,N.nextSibling):Oe.appendChild($)}break;case"body-top":{let N=Y.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith($):Y.insertBefore($,Y.firstChild);break}case"body-bottom":Y.appendChild($);break;case"footer-top":Mt.replaceWith($);break;case"footer-bottom":cn.replaceWith($);break;default:break}};for(let[_,$]of Object.entries(c))if($)try{let q=$({config:o,defaultContent:()=>f(_)});q&&h(_,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${_}":`,q)}})();let Uo=c=>{let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let W=y.getAttribute("data-message-id");if(!W)return;let _=h.getAttribute("data-bubble-type");_==="reasoning"?(ns.has(W)?ns.delete(W):ns.add(W),Im(W,y)):_==="tool"&&(os.has(W)?os.delete(W):os.add(W),Rm(W,y,o)),fo.delete(W)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Uo(c))}),$e.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Uo(c))});let Ro=new Map;$e.addEventListener("click",c=>{var $;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let W=y.getAttribute("data-actions-for");if(!W)return;let _=h.getAttribute("data-action");if(_==="copy"){let N=M.getMessages().find(Te=>Te.id===W);if(N&&ne.onCopy){let Te=N.content||"";navigator.clipboard.writeText(Te).then(()=>{h.classList.add("persona-message-action-success");let me=ke("check",14,"currentColor",2);me&&(h.innerHTML="",h.appendChild(me)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=ke("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ne.onCopy(N)}}else if(_==="upvote"||_==="downvote"){let N=(($=Ro.get(W))!=null?$:null)===_,Te=_==="upvote"?"thumbs-up":"thumbs-down";if(N){Ro.delete(W),h.classList.remove("persona-message-action-active");let me=ke(Te,14,"currentColor",2);me&&(h.innerHTML="",h.appendChild(me))}else{let me=_==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${me}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Qe=ke(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Qe&&(ee.innerHTML="",ee.appendChild(Qe))}Ro.set(W,_),h.classList.add("persona-message-action-active");let be=ke(Te,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let _e=M.getMessages().find(nt=>nt.id===W);_e&&ne.onFeedback&&ne.onFeedback({type:_,messageId:_e.id,message:_e})}}}),$e.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let W=y.getAttribute("data-message-id");if(!W)return;let _=h.getAttribute("data-approval-action");if(!_)return;let $=_==="approve"?"approved":"denied",N=M.getMessages().find(me=>me.id===W);if(!(N!=null&&N.approval))return;let Te=y.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?M.resolveWebMcpApproval(W,$):M.resolveApproval(N.approval,$)});let vt=null,Vn=null,$n={artifacts:[],selectedId:null},wn=!1,Rt={current:null};$e.addEventListener("click",c=>{var ee,be,Me,_e,nt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Me=(be=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Me.call(be,{type:"download",artifactId:y}))===!0)return;let _=M.getArtifactById(y),$=_==null?void 0:_.markdown,q=(_==null?void 0:_.title)||"artifact";if(!$){let Qe=h.closest("[data-open-artifact]"),it=Qe==null?void 0:Qe.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let Pe=M.getMessages().find(Ke=>Ke.id===lt);if(Pe!=null&&Pe.rawContent)try{let Ke=JSON.parse(Pe.rawContent);$=(_e=Ke==null?void 0:Ke.props)==null?void 0:_e.markdown,q=((nt=Ke==null?void 0:Ke.props)==null?void 0:nt.title)||q}catch{}}}if(!$)return;let N=new Blob([$],{type:"text/markdown"}),Te=URL.createObjectURL(N),me=document.createElement("a");me.href=Te,me.download=`${q}.md`,me.click(),URL.revokeObjectURL(Te)}),$e.addEventListener("click",c=>{var _,$,q;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((q=($=(_=o.features)==null?void 0:_.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:q.call($,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),wn=!1,M.selectArtifact(y),qn())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let to=De.composerOverlay,no=(c,f,h)=>{var q,N,Te,me;let y=f.trim();if(!y||!Rt.current)return;let W=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",_=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:W,answer:y,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?y.split(", "):[y],isFreeText:_,source:h.source},bubbles:!0,composed:!0})),is(to,W);let $=Rt.current.getMessages().find(ee=>{var be;return((be=ee.toolCall)==null?void 0:be.id)===W});(Te=$==null?void 0:$.agentMetadata)!=null&&Te.awaitingLocalTool?Rt.current.resolveAskUserQuestion($,(me=h.structured)!=null?me:y):Rt.current.sendMessage(y)},Un=c=>{var W;let f=Rt.current;if(!f)return;let h=(W=c.getAttribute("data-tool-call-id"))!=null?W:"",y=f.getMessages().find(_=>{var $;return(($=_.toolCall)==null?void 0:$.id)===h});y&&f.persistAskUserQuestionProgress(y,{answers:qi(c,y),currentIndex:co(c)})},zo=c=>Object.entries(c).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Po=c=>{var W,_,$;if(((_=(W=o.features)==null?void 0:W.askUserQuestion)==null?void 0:_.groupedAutoAdvance)===!1)return;let f=co(c),h=as(c);if(f>=h-1)return;let y=($=Rt.current)==null?void 0:$.getMessages().find(q=>{var N;return((N=q.toolCall)==null?void 0:N.id)===c.getAttribute("data-tool-call-id")});y&&(Ki(c,y,o,f+1),Un(c))};to.addEventListener("click",c=>{var _,$,q,N,Te,me,ee,be,Me,_e,nt,Qe,it,lt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let W=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),W==="dismiss"){let We=(_=y.getAttribute("data-tool-call-id"))!=null?_:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),is(to,We);let Pe=($=Rt.current)==null?void 0:$.getMessages().find(Ke=>{var P;return((P=Ke.toolCall)==null?void 0:P.id)===We});(q=Pe==null?void 0:Pe.agentMetadata)!=null&&q.awaitingLocalTool&&((N=Rt.current)==null||N.markAskUserQuestionResolved(Pe),(Te=Rt.current)==null||Te.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(W==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Pe=y.getAttribute("data-multi-select")==="true",Ke=lr(y);if(Ke&&Pe){let P=Pr(y)[co(y)],Le=new Set(Array.isArray(P)?P:[]);Le.has(We)?Le.delete(We):Le.add(We),cr(y,Array.from(Le)),Un(y);return}if(Ke){cr(y,We),Un(y),Po(y);return}if(Pe){let P=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",P?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!P);let Le=y.querySelector('[data-ask-user-action="submit-multi"]');Le&&(Le.disabled=Zl(y).length===0);return}no(y,We,{source:"pick",values:[We]});return}if(W==="submit-multi"){let We=Zl(y);if(We.length===0)return;no(y,We.join(", "),{source:"multi",values:We});return}if(W==="open-free-text"){let We=y.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Pe=We.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(W==="focus-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(W==="submit-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]'),Pe=(me=We==null?void 0:We.value)!=null?me:"";if(!Pe.trim())return;if(lr(y)){cr(y,Pe.trim()),Un(y),Po(y);return}no(y,Pe,{source:"free-text"});return}if(W==="next"||W==="back"){if(!Rt.current)return;let We=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Pe=Rt.current.getMessages().find(Ye=>{var Se;return((Se=Ye.toolCall)==null?void 0:Se.id)===We});if(!Pe)return;let Ke=y.querySelector('[data-ask-free-text-input="true"]'),P=(Me=(be=Ke==null?void 0:Ke.value)==null?void 0:be.trim())!=null?Me:"";if(P){let Ye=Pr(y)[co(y)];(typeof Ye!="string"||Ye!==P)&&cr(y,P)}let Le=W==="next"?1:-1,He=co(y)+Le;Ki(y,Pe,o,He),Un(y);return}if(W==="submit-all"){if(!Rt.current)return;let We=(_e=y.getAttribute("data-tool-call-id"))!=null?_e:"",Pe=Rt.current.getMessages().find(Ye=>{var Se;return((Se=Ye.toolCall)==null?void 0:Se.id)===We});if(!Pe)return;let Ke=y.querySelector('[data-ask-free-text-input="true"]'),P=(Qe=(nt=Ke==null?void 0:Ke.value)==null?void 0:nt.trim())!=null?Qe:"";P&&cr(y,P);let Le=qi(y,Pe);Rt.current.persistAskUserQuestionProgress(Pe,{answers:Le,currentIndex:co(y)});let He=zo(Le);no(y,He||"(submitted)",{source:"submit-all",structured:Le});return}if(W==="skip"){if(!Rt.current)return;let We=(it=y.getAttribute("data-tool-call-id"))!=null?it:"",Pe=Rt.current.getMessages().find(Se=>{var It;return((It=Se.toolCall)==null?void 0:It.id)===We});if(!Pe)return;let Ke=lr(y),P=co(y),Le=as(y),He=P>=Le-1;if(!Ke){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),is(to,We),(lt=Pe.agentMetadata)!=null&&lt.awaitingLocalTool&&(Rt.current.markAskUserQuestionResolved(Pe),Rt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}cr(y,"");let Ye=y.querySelector('[data-ask-free-text-input="true"]');if(Ye&&(Ye.value=""),He){let Se=qi(y,Pe),It=zo(Se);no(y,It||"(skipped)",{source:"submit-all",structured:Se});return}Ki(y,Pe,o,P+1),Un(y);return}}),to.addEventListener("keydown",c=>{var _;if(c.key!=="Enter")return;let h=c.target;if(!((_=h.matches)!=null&&_.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let W=h.value;if(W.trim()){if(lr(y)){cr(y,W.trim()),Un(y),Po(y);return}no(y,W,{source:"free-text"})}});let qo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=to.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),_=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];_&&(c.preventDefault(),_.click())};document.addEventListener("keydown",qo);let zn=null,Bt=null,Cn=null,oo=null,jo=()=>{};function Wo(){oo==null||oo(),oo=null}let Ko=()=>{var $;if(!zn||!Bt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let y=zn.firstElementChild;if(!y||y===Bt)return;let W=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${W}px`,Bt.style.zIndex="5";let _=y.offsetWidth-W/2;Bt.style.left=`${Math.max(0,_)}px`},Ao=()=>{},qn=()=>{var h,y,W,_,$;if(!vt||!po(o))return;Yi(e,o),Xi(e,o),Ao();let c=(_=(W=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:W.narrowHostMaxWidth)!=null?_:520,f=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),vt.update($n),wn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),($=vt.backdrop)==null||$.classList.add("persona-hidden")):$n.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),jo()};if(po(o)){ce.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(de),vt=Xm(o,{onSelect:h=>{var y;return(y=Rt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{wn=!0,qn()}}),vt.element.classList.add("persona-hidden"),zn=f,f.appendChild(c),f.appendChild(vt.element),vt.backdrop&&ce.appendChild(vt.backdrop),ce.appendChild(f),jo=()=>{var y,W,_,$;if(!zn||!vt)return;if(!(((_=(W=(y=o.features)==null?void 0:y.artifacts)==null?void 0:W.layout)==null?void 0:_.resizable)===!0)){Cn==null||Cn(),Cn=null,Wo(),Bt&&(Bt.remove(),Bt=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Bt){let q=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let N=e.ownerDocument,Te=($=N.defaultView)!=null?$:window,me=ee=>{var it,lt;if(!vt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;ee.preventDefault(),Wo();let be=ee.clientX,Me=vt.element.getBoundingClientRect().width,_e=(lt=(it=o.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,nt=We=>{let Pe=zn.getBoundingClientRect().width,Ke=e.classList.contains("persona-artifact-appearance-seamless"),P=Ke?0:ef(zn,Te),Le=Ke?0:q.getBoundingClientRect().width||6,He=Me-(We.clientX-be),Ye=tf(He,Pe,P,Le,_e==null?void 0:_e.resizableMinWidth,_e==null?void 0:_e.resizableMaxWidth);vt.element.style.width=`${Ye}px`,vt.element.style.maxWidth="none",Ko()},Qe=()=>{N.removeEventListener("pointermove",nt),N.removeEventListener("pointerup",Qe),N.removeEventListener("pointercancel",Qe),oo=null;try{q.releasePointerCapture(ee.pointerId)}catch{}};oo=Qe,N.addEventListener("pointermove",nt),N.addEventListener("pointerup",Qe),N.addEventListener("pointercancel",Qe);try{q.setPointerCapture(ee.pointerId)}catch{}};q.addEventListener("pointerdown",me),Bt=q,zn.insertBefore(q,vt.element),Cn=()=>{q.removeEventListener("pointerdown",me)}}if(Bt){let q=$n.artifacts.length>0&&!wn;Bt.classList.toggle("persona-hidden",!q),Ko()}},Ao=()=>{var Te,me,ee,be,Me,_e,nt,Qe,it,lt,We,Pe,Ke,P;if(!R||!vt||((me=(Te=o.launcher)==null?void 0:Te.sidebarMode)!=null?me:!1)||un(o)&&Lo(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,W=(Me=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?Me:!0,_=(nt=(_e=o.launcher)==null?void 0:_e.mobileBreakpoint)!=null?nt:640;if(W&&y.innerWidth<=_||!Zm(o,R))return;let $=(lt=(it=(Qe=o.launcher)==null?void 0:Qe.width)!=null?it:o.launcherWidth)!=null?lt:lo,q=(P=(Ke=(Pe=(We=o.features)==null?void 0:We.artifacts)==null?void 0:Pe.layout)==null?void 0:Ke.expandedPanelWidth)!=null?P:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!wn?(ce.style.width=q,ce.style.maxWidth=q):(ce.style.width=$,ce.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{qn()}),Vn.observe(ce))}else ce.appendChild(de),E()&&ze&&(De.peekBanner&&ze.appendChild(De.peekBanner),ze.appendChild(Ue));e.appendChild(ve),ze&&e.appendChild(ze);let uo=()=>{var Ye,Se,It,at,Qt,dn,Wt,Tn,pn,Ze,ct,kn,fn,yr,vr,xr,jr,Kr,jt,wr,or,bt,Wn,_o,En,Bn,Dt,zt;if(E()){ce.style.width="100%",ce.style.maxWidth="100%";let Ft=(Se=(Ye=o.launcher)==null?void 0:Ye.composerBar)!=null?Se:{},Kt=ve.dataset.state==="expanded",Hn=(It=Ft.expandedSize)!=null?It:"anchored";if(!(Kt&&Hn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let tn=(Qt=(at=o.theme)==null?void 0:at.components)==null?void 0:Qt.panel,Eo=Za(o),Vo=(Cr,Xa)=>{var Rs;return Cr==null||Cr===""?Xa:(Rs=Gr(Eo,Cr))!=null?Rs:Cr},Ka="1px solid var(--persona-border)",Ga="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ya="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=Vo(tn==null?void 0:tn.border,Ka),de.style.borderRadius=Vo(tn==null?void 0:tn.borderRadius,Ya),de.style.boxShadow=Vo(tn==null?void 0:tn.shadow,Ga),de.style.overflow="hidden";return}let c=un(o),f=(Wt=(dn=o.launcher)==null?void 0:dn.sidebarMode)!=null?Wt:!1,h=c||f||((pn=(Tn=o.launcher)==null?void 0:Tn.fullHeight)!=null?pn:!1),y=((Ze=o.launcher)==null?void 0:Ze.enabled)===!1,W=(kn=(ct=o.theme)==null?void 0:ct.components)==null?void 0:kn.panel,_=Za(o),$=(Ft,Kt)=>{var Hn;return Ft==null||Ft===""?Kt:(Hn=Gr(_,Ft))!=null?Hn:Ft},q=(fn=e.ownerDocument.defaultView)!=null?fn:window,N=(vr=(yr=o.launcher)==null?void 0:yr.mobileFullscreen)!=null?vr:!0,Te=(jr=(xr=o.launcher)==null?void 0:xr.mobileBreakpoint)!=null?jr:640,me=q.innerWidth<=Te,ee=N&&me&&R,be=(jt=(Kr=o.launcher)==null?void 0:Kr.position)!=null?jt:"bottom-left",Me=be==="bottom-left"||be==="top-left",_e=(or=(wr=o.launcher)==null?void 0:wr.zIndex)!=null?or:bn,nt=f||ee?"none":"1px solid var(--persona-border)",Qe=ee?"none":f?Me?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Qe="none",nt="none");let it=f||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=$(W==null?void 0:W.border,nt),We=$(W==null?void 0:W.shadow,Qe),Pe=$(W==null?void 0:W.borderRadius,it),Ke=Y.scrollTop;e.style.cssText="",ve.style.cssText="",ce.style.cssText="",de.style.cssText="",Y.style.cssText="",Ue.style.cssText="";let P=()=>{var Kt;if(Ke<=0)return;((Kt=Y.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(Y.scrollTop===Ke)return;let Hn=Y.scrollHeight-Y.clientHeight;Hn<=0||(Y.scrollTop=Math.min(Ke,Hn))})};if(ee){ve.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ve.style.cssText=`
30
+ `,w.addEventListener("click",()=>{p=x,I.forEach((E,S)=>{let T=S<x;E.classList.toggle("selected",T),E.setAttribute("aria-checked",S===x-1?"true":"false")})}),I.push(w),M.appendChild(w)}f.appendChild(M);let R=null;if(d){let x=document.createElement("div");x.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),x.appendChild(R),f.appendChild(x)}let W=document.createElement("div");W.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 B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(p===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let x=(R==null?void 0:R.value.trim())||void 0;await t(p,x),m.remove()}catch(x){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(D),W.appendChild(B),f.appendChild(W),m.appendChild(f),m}function Ag(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 M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,C.appendChild(M),u.appendChild(C);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let W=document.createElement("span");W.className="persona-feedback-label-low",W.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=m,R.appendChild(W),R.appendChild(D);let B=document.createElement("div");B.className="persona-feedback-numbers";let x=[];for(let _=0;_<=10;_++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${_} out of 10`),U.textContent=String(_),U.dataset.rating=String(_),_<=6?U.classList.add("persona-feedback-detractor"):_<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{f=_,x.forEach((Y,he)=>{Y.classList.toggle("selected",he===_),Y.setAttribute("aria-checked",he===_?"true":"false")})}),x.push(U),B.appendChild(U)}I.appendChild(R),I.appendChild(B),u.appendChild(I);let w=null;if(d){let _=document.createElement("div");_.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"),_.appendChild(w),u.appendChild(_)}let E=document.createElement("div");E.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),p.remove()});let 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(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let _=(w==null?void 0:w.value.trim())||void 0;await t(f,_),p.remove()}catch(_){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),E.appendChild(S),E.appendChild(T),u.appendChild(E),p.appendChild(u),p}var fs="persona-chat-history",Sy=30*1e3,Ay={"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 Ty(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=Ay[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 tl(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 ky(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 Ey(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var hc=e=>!e||typeof e!="object"?{}:{...e},Tg=e=>e.map(t=>({...t,streaming:!1})),kg=(e,t,n)=>{let o=e!=null&&e.markdown?ui(e.markdown):null,r=mi(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=ta(a),r?r(d):d}};function Eg(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=Me(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let p=b("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var Mg=(e,t,n)=>{var Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd;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=Wu(t),r=pc.getForInstance(o.plugins);o.components&&Or.registerAll(o.components);let s=hg(),i=o.persistState===!1?null:(Nc=o.storageAdapter)!=null?Nc:yg(),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=hc(h.metadata)),(_c=h.messages)!=null&&_c.length&&(o={...o,initialMessages:h.messages}),(Vc=h.artifacts)!=null&&Vc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:($c=h.selectedArtifactId)!=null?$c: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:{}});(Uc=c.messages)!=null&&Uc.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:{},zr()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[mc],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ta.message,Ta.messageAndClick],M=gc({parsers:C,handlers:v,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(qc=(zc=o.launcher)==null?void 0:zc.enabled)!=null?qc:!0,R=(Kc=(jc=o.launcher)==null?void 0:jc.autoExpand)!=null?Kc:!1,W=(Gc=o.autoFocusInput)!=null?Gc:!1,D=R,B=I,x=(Xc=(Yc=o.layout)==null?void 0:Yc.header)==null?void 0:Xc.layout,w=!1,E=()=>ba(o),S=()=>I||E(),T=E()?!1:I?R:!0,_=!1,U=null,Y=()=>{_=!0,U&&clearTimeout(U),U=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},he=kg(o,M,Y),fe=(Jc=(Qc=o.features)==null?void 0:Qc.showReasoning)!=null?Jc:!0,ae=(ed=(Zc=o.features)==null?void 0:Zc.showToolCalls)!=null?ed:!0,Ee=(nd=(td=o.features)==null?void 0:td.showEventStreamToggle)!=null?nd:!1,ye=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},we=`${(ad=typeof o.persistState=="object"?(sd=o.persistState)==null?void 0:sd.keyPrefix:void 0)!=null?ad:"persona-"}event-stream`,K=Ee?new Sa(we):null,pe=(cd=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.maxEvents)!=null?cd:2e3,G=Ee?new Ca(pe,K):null,ve=Ee?new Aa:null,ce=null,ne=!1,Se=null,ze=0;K==null||K.open().then(()=>G==null?void 0:G.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let te={onCopy:c=>{var g,h;s.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.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),$!=null&&$.isClientTokenMode()&&$.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)}},re=(dd=o.statusIndicator)!=null?dd:{},ie=c=>{var g,h,y,L;return c==="idle"?(g=re.idleText)!=null?g:wn.idle:c==="connecting"?(h=re.connectingText)!=null?h:wn.connecting:c==="connected"?(y=re.connectedText)!=null?y:wn.connected:c==="error"?(L=re.errorText)!=null?L:wn.error:wn[c]};function st(c,g,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let L=document.createElement("a");L.href=h.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",c.appendChild(L)}else c.textContent=g}let{wrapper:Te,panel:ue,pillRoot:Ue}=Hm(o),Be=Dm(o,S()),{container:me,body:Q,messagesWrapper:_e,suggestions:Ht,textarea:be,sendButton:de,sendButtonWrapper:Pn,composerForm:Ut,statusText:gn,introTitle:Fn,introSubtitle:to,closeButton:qe,iconHolder:V,headerTitle:Le,headerSubtitle:He,header:De,footer:Ve,actionsRow:mt,leftActions:at,rightActions:Pt}=Be,jt=Be.setSendButtonMode,j=Be.micButton,zt=Be.micButtonWrapper,Ze=Be.attachmentButton,Vt=Be.attachmentButtonWrapper,se=Be.attachmentInput,Ce=Be.attachmentPreviewsContainer;me.classList.add("persona-relative"),Q.classList.add("persona-relative");let kt=12,Kt=()=>{var c;return(c=ye.label)!=null?c:""},tn=()=>{var c;return(c=ye.iconName)!=null?c:"arrow-down"},An=()=>ye.enabled!==!1,Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let Mt=b("span","persona-flex persona-items-center"),wt=b("span","");Wt.append(Mt,wt),me.appendChild(Wt);let St=()=>{let g=Ve.style.display==="none"?0:Ve.offsetHeight;Wt.style.bottom=`${g+kt}px`};St();let Gt=()=>{let c=!!Kt();Wt.setAttribute("aria-label",Kt()||"Jump to latest"),Wt.title=Kt(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Mt.innerHTML="";let g=Me(tn(),"14px","currentColor",2);g?(Mt.appendChild(g),Mt.style.display=""):Mt.style.display="none",wt.textContent=Kt(),wt.style.display=c?"":"none"};Gt();let ot=null,On=null,no=r.find(c=>c.renderHeader);if(no!=null&&no.renderHeader){let c=no.renderHeader({config:o,defaultRenderer:()=>{let g=Br({config:o,showClose:S()});return va(me,g,o),g.header},onClose:()=>Ot(!1,"user")});if(c){let g=me.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let Tn=()=>{var g,h,y,L;if(!G)return;if(ne=!0,!ce&&G&&(ce=ag({buffer:G,getFullHistory:()=>G.getAllFromStore(),onClose:()=>Nn(),config:o,plugins:r,getThroughput:()=>{var O;return(O=ve==null?void 0:ve.getMetric())!=null?O:{status:"idle"}}})),ce&&(Q.style.display="none",(g=Ve.parentNode)==null||g.insertBefore(ce.element,Ve),ce.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Rn.actionIconColor}`;let O=(L=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:L.toggleButtonActive;O&&O.split(/\s+/).forEach(N=>N&&bt.classList.add(N))}let c=()=>{if(!ne)return;let O=Date.now();O-ze>=200&&(ce==null||ce.update(),ze=O),Se=requestAnimationFrame(c)};ze=0,Se=requestAnimationFrame(c),Vo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,g,h;if(ne){if(ne=!1,ce&&ce.element.remove(),Q.style.display="",bt){bt.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(L=>L&&bt.classList.remove(L))}Se!==null&&(cancelAnimationFrame(Se),Se=null),Vo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(Ee){let c=(ud=(pd=o.features)==null?void 0:pd.eventStream)==null?void 0:ud.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:"");bt=b("button",g),bt.style.width="28px",bt.style.height="28px",bt.style.color=Rn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=Me("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let y=Be.clearChatButtonWrapper,L=Be.closeButtonWrapper,O=y||L;O&&O.parentNode===De?De.insertBefore(bt,O):De.appendChild(bt),bt.addEventListener("click",()=>{ne?Nn():Tn()})}let Lo=c=>{var y,L,O;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 N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(h,N):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=b("input");N.type="file",N.accept=((y=g.allowedTypes)!=null?y:qo).join(","),N.multiple=((L=g.maxFiles)!=null?L:4)>1,N.style.display="none",N.setAttribute("aria-label",(O=g.buttonTooltipText)!=null?O:"Attach files"),c.appendChild(N)}},_n=r.find(c=>c.renderComposer);if(_n!=null&&_n.renderComposer){let c=o.composer,g=_n.renderComposer({config:o,defaultRenderer:()=>ji({config:o}).footer,onSubmit:h=>{var N;if(!$||$.isStreaming())return;let y=h.trim(),L=(N=ot==null?void 0:ot.hasAttachments())!=null?N:!1;if(!y&&!L)return;Ls();let O;L&&(O=[],O.push(...ot.getContentParts()),y&&O.push(_l(y))),$.sendMessage(y,{contentParts:O}),L&&ot.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{se==null||se.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:((md=o.voiceRecognition)==null?void 0:md.enabled)===!0?()=>{On==null||On()}:void 0});g&&(Ve.replaceWith(g),Ve=g)}let fr=c=>{let g=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),L=c.querySelector("[data-persona-composer-mic]"),O=c.querySelector("[data-persona-composer-status]");g&&(Ut=g),h&&(be=h),y&&(de=y),L&&(j=L,zt=L.parentElement),O&&(gn=O);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Ht=N);let q=c.querySelector(".persona-attachment-button");q&&(Ze=q,Vt=q.parentElement),se=c.querySelector('input[type="file"]'),Ce=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(mt=F)};Lo(Ve),fr(Ve);let Wn=(yd=(gd=o.layout)==null?void 0:gd.contentMaxWidth)!=null?yd:E()?(bd=(hd=(fd=o.launcher)==null?void 0:fd.composerBar)==null?void 0:hd.contentMaxWidth)!=null?bd:"720px":void 0;if(Wn&&(_e.style.maxWidth=Wn,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%"),Wn&&Ut&&!E()&&(Ut.style.maxWidth=Wn,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),Wn&&Ht&&!E()&&(Ht.style.maxWidth=Wn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Wn&&Ce&&!E()&&(Ce.style.maxWidth=Wn,Ce.style.marginLeft="auto",Ce.style.marginRight="auto"),(vd=o.attachments)!=null&&vd.enabled&&se&&Ce){ot=ca.fromConfig(o.attachments),ot.setPreviewsContainer(Ce),se.addEventListener("change",h=>{let y=h.target;ot==null||ot.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,g=Eg(c);me.appendChild(g)}(()=>{var y,L;let c=(L=(y=o.layout)==null?void 0:y.slots)!=null?L:{},g=O=>{switch(O){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return _e;case"footer-top":return Ht;case"composer":return Ut;case"footer-bottom":return gn;default:return null}},h=(O,N)=>{var q;switch(O){case"header-left":case"header-center":case"header-right":if(O==="header-left")De.insertBefore(N,De.firstChild);else if(O==="header-right")De.appendChild(N);else{let F=De.querySelector(".persona-flex-col");F?(q=F.parentNode)==null||q.insertBefore(N,F.nextSibling):De.appendChild(N)}break;case"body-top":{let F=Q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(N):Q.insertBefore(N,Q.firstChild);break}case"body-bottom":Q.appendChild(N);break;case"footer-top":Ht.replaceWith(N);break;case"footer-bottom":gn.replaceWith(N);break;default:break}};for(let[O,N]of Object.entries(c))if(N)try{let q=N({config:o,defaultContent:()=>g(O)});q&&h(O,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${O}":`,q)}})();let jo=c=>{var N,q;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 L=y.getAttribute("data-message-id");if(!L)return;let O=h.getAttribute("data-bubble-type");if(O==="reasoning")ls.has(L)?ls.delete(L):ls.add(L),Nm(L,y);else if(O==="tool")cs.has(L)?cs.delete(L):cs.add(L),_m(L,y,o);else if(O==="approval"){let F=o.approval!==!1?o.approval:void 0,ke=((N=F==null?void 0:F.detailsDisplay)!=null?N:"collapsed")==="expanded",ge=(q=Xi.get(L))!=null?q:ke;Xi.set(L,!ge),tg(L,y,o)}xe.delete(L)};_e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jo(c))}),_e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jo(c))});let Do=new Map;_e.addEventListener("click",c=>{var N;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 L=y.getAttribute("data-actions-for");if(!L)return;let O=h.getAttribute("data-action");if(O==="copy"){let F=$.getMessages().find(ke=>ke.id===L);if(F&&te.onCopy){let ke=F.content||"";navigator.clipboard.writeText(ke).then(()=>{h.classList.add("persona-message-action-success");let ge=Me("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=Me("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),te.onCopy(F)}}else if(O==="upvote"||O==="downvote"){let F=((N=Do.get(L))!=null?N:null)===O,ke=O==="upvote"?"thumbs-up":"thumbs-down";if(F){Do.delete(L),h.classList.remove("persona-message-action-active");let ge=Me(ke,14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))}else{let ge=O==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ge}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ke=Me(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ke&&(ee.innerHTML="",ee.appendChild(Ke))}Do.set(L,O),h.classList.add("persona-message-action-active");let Ae=Me(ke,14,"currentColor",2);Ae&&(Ae.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Ae)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let $e=$.getMessages().find(rt=>rt.id===L);$e&&te.onFeedback&&te.onFeedback({type:O,messageId:$e.id,message:$e})}}}),_e.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let L=y.getAttribute("data-message-id");if(!L)return;let O=h.getAttribute("data-approval-action");if(!O)return;let N=O==="approve"?"approved":"denied",F=$.getMessages().find(ge=>ge.id===L);if(!(F!=null&&F.approval))return;let ke=y.querySelector("[data-approval-buttons]");ke&&ke.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?$.resolveWebMcpApproval(L,N):$.resolveApproval(F.approval,N)});let At=null,Vn=null,$n={artifacts:[],selectedId:null},kn=!1,Lt={current:null};_e.addEventListener("click",c=>{var ee,Ae,Ie,$e,rt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ie=(Ae=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:Ae.onArtifactAction)==null?void 0:Ie.call(Ae,{type:"download",artifactId:y}))===!0)return;let O=$.getArtifactById(y),N=O==null?void 0:O.markdown,q=(O==null?void 0:O.title)||"artifact";if(!N){let Ke=h.closest("[data-open-artifact]"),gt=Ke==null?void 0:Ke.closest("[data-message-id]"),pt=gt==null?void 0:gt.getAttribute("data-message-id");if(pt){let Pe=$.getMessages().find(je=>je.id===pt);if(Pe!=null&&Pe.rawContent)try{let je=JSON.parse(Pe.rawContent);N=($e=je==null?void 0:je.props)==null?void 0:$e.markdown,q=((rt=je==null?void 0:je.props)==null?void 0:rt.title)||q}catch{}}}if(!N)return;let F=new Blob([N],{type:"text/markdown"}),ke=URL.createObjectURL(F),ge=document.createElement("a");ge.href=ke,ge.download=`${q}.md`,ge.click(),URL.revokeObjectURL(ke)}),_e.addEventListener("click",c=>{var O,N,q;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((q=(N=(O=o.features)==null?void 0:O.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:q.call(N,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),kn=!1,$.selectArtifact(y),qn())}),_e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let oo=Be.composerOverlay,ro=(c,g,h)=>{var q,F,ke,ge;let y=g.trim();if(!y||!Lt.current)return;let L=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",O=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:y,answers:h.structured,values:(F=h.values)!=null?F:h.source==="multi"?y.split(", "):[y],isFreeText:O,source:h.source},bubbles:!0,composed:!0})),ms(oo,L);let N=Lt.current.getMessages().find(ee=>{var Ae;return((Ae=ee.toolCall)==null?void 0:Ae.id)===L});(ke=N==null?void 0:N.agentMetadata)!=null&&ke.awaitingLocalTool?Lt.current.resolveAskUserQuestion(N,(ge=h.structured)!=null?ge:y):Lt.current.sendMessage(y)},Un=c=>{var L;let g=Lt.current;if(!g)return;let h=(L=c.getAttribute("data-tool-call-id"))!=null?L:"",y=g.getMessages().find(O=>{var N;return((N=O.toolCall)==null?void 0:N.id)===h});y&&g.persistAskUserQuestionProgress(y,{answers:Ki(c,y),currentIndex:ho(c)})},Ko=c=>Object.entries(c).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Fo=c=>{var L,O,N;if(((O=(L=o.features)==null?void 0:L.askUserQuestion)==null?void 0:O.groupedAutoAdvance)===!1)return;let g=ho(c),h=us(c);if(g>=h-1)return;let y=(N=Lt.current)==null?void 0:N.getMessages().find(q=>{var F;return((F=q.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});y&&(Yi(c,y,o,g+1),Un(c))};oo.addEventListener("click",c=>{var O,N,q,F,ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt;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 L=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),L==="dismiss"){let We=(O=y.getAttribute("data-tool-call-id"))!=null?O:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),ms(oo,We);let Pe=(N=Lt.current)==null?void 0:N.getMessages().find(je=>{var Je;return((Je=je.toolCall)==null?void 0:Je.id)===We});(q=Pe==null?void 0:Pe.agentMetadata)!=null&&q.awaitingLocalTool&&((F=Lt.current)==null||F.markAskUserQuestionResolved(Pe),(ke=Lt.current)==null||ke.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(L==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Pe=y.getAttribute("data-multi-select")==="true",je=pr(y);if(je&&Pe){let Je=Dr(y)[ho(y)],xt=new Set(Array.isArray(Je)?Je:[]);xt.has(We)?xt.delete(We):xt.add(We),ur(y,Array.from(xt)),Un(y);return}if(je){ur(y,We),Un(y),Fo(y);return}if(Pe){let Je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Je);let xt=y.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=sc(y).length===0);return}ro(y,We,{source:"pick",values:[We]});return}if(L==="submit-multi"){let We=sc(y);if(We.length===0)return;ro(y,We.join(", "),{source:"multi",values:We});return}if(L==="open-free-text"){let We=y.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Pe=We.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(L==="focus-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(L==="submit-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]'),Pe=(ge=We==null?void 0:We.value)!=null?ge:"";if(!Pe.trim())return;if(pr(y)){ur(y,Pe.trim()),Un(y),Fo(y);return}ro(y,Pe,{source:"free-text"});return}if(L==="next"||L==="back"){if(!Lt.current)return;let We=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Pe=Lt.current.getMessages().find(Fe=>{var oe;return((oe=Fe.toolCall)==null?void 0:oe.id)===We});if(!Pe)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Je=(Ie=(Ae=je==null?void 0:je.value)==null?void 0:Ae.trim())!=null?Ie:"";if(Je){let Fe=Dr(y)[ho(y)];(typeof Fe!="string"||Fe!==Je)&&ur(y,Je)}let xt=L==="next"?1:-1,H=ho(y)+xt;Yi(y,Pe,o,H),Un(y);return}if(L==="submit-all"){if(!Lt.current)return;let We=($e=y.getAttribute("data-tool-call-id"))!=null?$e:"",Pe=Lt.current.getMessages().find(Fe=>{var oe;return((oe=Fe.toolCall)==null?void 0:oe.id)===We});if(!Pe)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Je=(Ke=(rt=je==null?void 0:je.value)==null?void 0:rt.trim())!=null?Ke:"";Je&&ur(y,Je);let xt=Ki(y,Pe);Lt.current.persistAskUserQuestionProgress(Pe,{answers:xt,currentIndex:ho(y)});let H=Ko(xt);ro(y,H||"(submitted)",{source:"submit-all",structured:xt});return}if(L==="skip"){if(!Lt.current)return;let We=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",Pe=Lt.current.getMessages().find(oe=>{var tt;return((tt=oe.toolCall)==null?void 0:tt.id)===We});if(!Pe)return;let je=pr(y),Je=ho(y),xt=us(y),H=Je>=xt-1;if(!je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),ms(oo,We),(pt=Pe.agentMetadata)!=null&&pt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Pe),Lt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}ur(y,"");let Fe=y.querySelector('[data-ask-free-text-input="true"]');if(Fe&&(Fe.value=""),H){let oe=Ki(y,Pe),tt=Ko(oe);ro(y,tt||"(skipped)",{source:"submit-all",structured:oe});return}Yi(y,Pe,o,Je+1),Un(y);return}}),oo.addEventListener("keydown",c=>{var O;if(c.key!=="Enter")return;let h=c.target;if(!((O=h.matches)!=null&&O.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let L=h.value;if(L.trim()){if(pr(y)){ur(y,L.trim()),Un(y),Fo(y);return}ro(y,L,{source:"free-text"})}});let Go=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=oo.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),O=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];O&&(c.preventDefault(),O.click())};document.addEventListener("keydown",Go);let zn=null,Ft=null,En=null,so=null,Yo=()=>{};function Oo(){so==null||so(),so=null}let Xo=()=>{var N;if(!zn||!Ft)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let y=zn.firstElementChild;if(!y||y===Ft)return;let L=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${L}px`,Ft.style.zIndex="5";let O=y.offsetWidth-L/2;Ft.style.left=`${Math.max(0,O)}px`},Io=()=>{},qn=()=>{var h,y,L,O,N;if(!At||!bo(o))return;Zi(e,o),el(e,o),Io();let c=(O=(L=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:L.narrowHostMaxWidth)!=null?O:520,g=ue.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),At.update($n),kn?(At.setMobileOpen(!1),At.element.classList.add("persona-hidden"),(N=At.backdrop)==null||N.classList.add("persona-hidden")):$n.artifacts.length>0&&(At.element.classList.remove("persona-hidden"),At.setMobileOpen(!0)),Yo()};if(bo(o)){ue.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(me),At=cg(o,{onSelect:h=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{kn=!0,qn()}}),At.element.classList.add("persona-hidden"),zn=g,g.appendChild(c),g.appendChild(At.element),At.backdrop&&ue.appendChild(At.backdrop),ue.appendChild(g),Yo=()=>{var y,L,O,N;if(!zn||!At)return;if(!(((O=(L=(y=o.features)==null?void 0:y.artifacts)==null?void 0:L.layout)==null?void 0:O.resizable)===!0)){En==null||En(),En=null,Oo(),Ft&&(Ft.remove(),Ft=null),At.element.style.removeProperty("width"),At.element.style.removeProperty("maxWidth");return}if(!Ft){let q=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let F=e.ownerDocument,ke=(N=F.defaultView)!=null?N:window,ge=ee=>{var gt,pt;if(!At||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||ke.innerWidth<=640)return;ee.preventDefault(),Oo();let Ae=ee.clientX,Ie=At.element.getBoundingClientRect().width,$e=(pt=(gt=o.features)==null?void 0:gt.artifacts)==null?void 0:pt.layout,rt=We=>{let Pe=zn.getBoundingClientRect().width,je=e.classList.contains("persona-artifact-appearance-seamless"),Je=je?0:mg(zn,ke),xt=je?0:q.getBoundingClientRect().width||6,H=Ie-(We.clientX-Ae),Fe=gg(H,Pe,Je,xt,$e==null?void 0:$e.resizableMinWidth,$e==null?void 0:$e.resizableMaxWidth);At.element.style.width=`${Fe}px`,At.element.style.maxWidth="none",Xo()},Ke=()=>{F.removeEventListener("pointermove",rt),F.removeEventListener("pointerup",Ke),F.removeEventListener("pointercancel",Ke),so=null;try{q.releasePointerCapture(ee.pointerId)}catch{}};so=Ke,F.addEventListener("pointermove",rt),F.addEventListener("pointerup",Ke),F.addEventListener("pointercancel",Ke);try{q.setPointerCapture(ee.pointerId)}catch{}};q.addEventListener("pointerdown",ge),Ft=q,zn.insertBefore(q,At.element),En=()=>{q.removeEventListener("pointerdown",ge)}}if(Ft){let q=$n.artifacts.length>0&&!kn;Ft.classList.toggle("persona-hidden",!q),Xo()}},Io=()=>{var ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt,We,Pe,je,Je;if(!I||!At||((ge=(ke=o.launcher)==null?void 0:ke.sidebarMode)!=null?ge:!1)||bn(o)&&Bo(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,L=(Ie=(Ae=o.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Ie:!0,O=(rt=($e=o.launcher)==null?void 0:$e.mobileBreakpoint)!=null?rt:640;if(L&&y.innerWidth<=O||!ug(o,I))return;let N=(pt=(gt=(Ke=o.launcher)==null?void 0:Ke.width)!=null?gt:o.launcherWidth)!=null?pt:fo,q=(Je=(je=(Pe=(We=o.features)==null?void 0:We.artifacts)==null?void 0:Pe.layout)==null?void 0:je.expandedPanelWidth)!=null?Je:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!kn?(ue.style.width=q,ue.style.maxWidth=q):(ue.style.width=N,ue.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{qn()}),Vn.observe(ue))}else ue.appendChild(me),E()&&Ue&&(Be.peekBanner&&Ue.appendChild(Be.peekBanner),Ue.appendChild(Ve));e.appendChild(Te),Ue&&e.appendChild(Ue);let yo=()=>{var Fe,oe,tt,_t,Nt,qt,it,cn,Xn,Ge,Ct,Qn,rn,mo,Jn,wr,Qr,Jr,Yt,Cr,sr,ar,zo,Sr,nt,vn,fn,dn;if(E()){ue.style.width="100%",ue.style.maxWidth="100%";let ft=(oe=(Fe=o.launcher)==null?void 0:Fe.composerBar)!=null?oe:{},lt=Te.dataset.state==="expanded",Et=(tt=ft.expandedSize)!=null?tt:"anchored";if(!(lt&&Et!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let en=(Nt=(_t=o.theme)==null?void 0:_t.components)==null?void 0:Nt.panel,Po=ti(o),sn=(Tr,Ja)=>{var Fs;return Tr==null||Tr===""?Ja:(Fs=Zr(Po,Tr))!=null?Fs:Tr},Ln="1px solid var(--persona-border)",go="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ar="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=sn(en==null?void 0:en.border,Ln),me.style.borderRadius=sn(en==null?void 0:en.borderRadius,Ar),me.style.boxShadow=sn(en==null?void 0:en.shadow,go),me.style.overflow="hidden";return}let c=bn(o),g=(it=(qt=o.launcher)==null?void 0:qt.sidebarMode)!=null?it:!1,h=c||g||((Xn=(cn=o.launcher)==null?void 0:cn.fullHeight)!=null?Xn:!1),y=((Ge=o.launcher)==null?void 0:Ge.enabled)===!1,L=(Qn=(Ct=o.theme)==null?void 0:Ct.components)==null?void 0:Qn.panel,O=ti(o),N=(ft,lt)=>{var Et;return ft==null||ft===""?lt:(Et=Zr(O,ft))!=null?Et:ft},q=(rn=e.ownerDocument.defaultView)!=null?rn:window,F=(Jn=(mo=o.launcher)==null?void 0:mo.mobileFullscreen)!=null?Jn:!0,ke=(Qr=(wr=o.launcher)==null?void 0:wr.mobileBreakpoint)!=null?Qr:640,ge=q.innerWidth<=ke,ee=F&&ge&&I,Ae=(Yt=(Jr=o.launcher)==null?void 0:Jr.position)!=null?Yt:"bottom-left",Ie=Ae==="bottom-left"||Ae==="top-left",$e=(sr=(Cr=o.launcher)==null?void 0:Cr.zIndex)!=null?sr:Cn,rt=g||ee?"none":"1px solid var(--persona-border)",Ke=ee?"none":g?Ie?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ke="none",rt="none");let gt=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=N(L==null?void 0:L.border,rt),We=N(L==null?void 0:L.shadow,Ke),Pe=N(L==null?void 0:L.borderRadius,gt),je=Q.scrollTop;e.style.cssText="",Te.style.cssText="",ue.style.cssText="",me.style.cssText="",Q.style.cssText="",Ve.style.cssText="";let Je=()=>{var lt;if(je<=0)return;((lt=Q.ownerDocument.defaultView)!=null?lt:window).requestAnimationFrame(()=>{if(Q.scrollTop===je)return;let Et=Q.scrollHeight-Q.clientHeight;Et<=0||(Q.scrollTop=Math.min(je,Et))})};if(ee){Te.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"),Te.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 na=e=>({isError:!0,content:[{type:"text",text:e}]
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${_e} !important;
40
+ z-index: ${$e} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
- `,ce.style.cssText=`
42
+ `,ue.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 na=e=>({isError:!0,content:[{type:"text",text:e}]
52
52
  padding: 0 !important;
53
53
  box-shadow: none !important;
54
54
  border-radius: 0 !important;
55
- `,de.style.cssText=`
55
+ `,me.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 na=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
- `,Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",Ue.style.flexShrink="0",x=!0,P();return}let Le=(Wn=(bt=o==null?void 0:o.launcher)==null?void 0:bt.width)!=null?Wn:o==null?void 0:o.launcherWidth,He=Le!=null?Le:lo;if(!f&&!c)y&&h?(ce.style.width="100%",ce.style.maxWidth="100%"):(ce.style.width=He,ce.style.maxWidth=He);else if(c)if(Lo(o).reveal==="emerge"){let Kt=Lo(o).width;ce.style.width=Kt,ce.style.maxWidth=Kt}else ce.style.width="100%",ce.style.maxWidth="100%";if(Ao(),ce.style.boxShadow=We,ce.style.borderRadius=Pe,de.style.border=lt,de.style.borderRadius=Pe,c&&!ee&&(W==null?void 0:W.border)===void 0&&(de.style.border="none",Lo(o).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.height="100%",y&&(ve.style.overflow="hidden"),ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.height="100%",ce.style.overflow="hidden",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",Ue.style.flexShrink="0"),ve.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!y&&!c&&((_o=Co[be])!=null?_o:Co["bottom-right"]).split(" ").forEach(Kt=>ve.classList.add(Kt)),f){let Ft=(Bn=(En=o.launcher)==null?void 0:En.sidebarWidth)!=null?Bn:"420px";ve.style.cssText=`
66
+ `,Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",Ve.style.flexShrink="0",w=!0,Je();return}let xt=(zo=(ar=o==null?void 0:o.launcher)==null?void 0:ar.width)!=null?zo:o==null?void 0:o.launcherWidth,H=xt!=null?xt:fo;if(!g&&!c)y&&h?(ue.style.width="100%",ue.style.maxWidth="100%"):(ue.style.width=H,ue.style.maxWidth=H);else if(c)if(Bo(o).reveal==="emerge"){let lt=Bo(o).width;ue.style.width=lt,ue.style.maxWidth=lt}else ue.style.width="100%",ue.style.maxWidth="100%";if(Io(),ue.style.boxShadow=We,ue.style.borderRadius=Pe,me.style.border=pt,me.style.borderRadius=Pe,c&&!ee&&(L==null?void 0:L.border)===void 0&&(me.style.border="none",Bo(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.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%"),Te.style.display="flex",Te.style.flexDirection="column",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.maxHeight="100%",Te.style.height="100%",y&&(Te.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.height="100%",ue.style.overflow="hidden",me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.overflowY="auto",Ve.style.flexShrink="0"),Te.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&&((Sr=Mo[Ae])!=null?Sr:Mo["bottom-right"]).split(" ").forEach(lt=>Te.classList.add(lt)),g){let ft=(vn=(nt=o.launcher)==null?void 0:nt.sidebarWidth)!=null?vn:"420px";Te.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${Ft} !important;
70
+ width: ${ft} !important;
71
71
  height: 100vh !important;
72
72
  max-height: 100vh !important;
73
73
  margin: 0 !important;
74
74
  padding: 0 !important;
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
- z-index: ${_e} !important;
78
- ${Me?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
- `,ce.style.cssText=`
77
+ z-index: ${$e} !important;
78
+ ${Ie?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
+ `,ue.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 na=e=>({isError:!0,content:[{type:"text",text:e}]
89
89
  padding: 0 !important;
90
90
  box-shadow: ${We} !important;
91
91
  border-radius: ${Pe} !important;
92
- `,ce.style.setProperty("width","100%","important"),ce.style.setProperty("max-width","100%","important"),de.style.cssText=`
92
+ `,ue.style.setProperty("width","100%","important"),ue.style.setProperty("max-width","100%","important"),me.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 na=e=>({isError:!0,content:[{type:"text",text:e}]
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
101
  border-radius: ${Pe} !important;
102
- border: ${lt} !important;
103
- `,Ue.style.cssText=`
102
+ border: ${pt} !important;
103
+ `,Ve.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!y&&!c){let Ft="max-height: -moz-available !important; max-height: stretch !important;",Kt=f?"":"padding-top: 1.25em !important;",Hn=f?"":`z-index: ${(zt=(Dt=o.launcher)==null?void 0:Dt.zIndex)!=null?zt:bn} !important;`;ve.style.cssText+=Ft+Kt+Hn}P()};uo(),Yr(e,o),Yi(e,o),Xi(e,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",qo)});let Gt=null,Yt=null;gt.push(()=>{Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null}),Vn&&gt.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),gt.push(()=>{Cn==null||Cn(),Cn=null,Wo(),Bt&&(Bt.remove(),Bt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),le&&gt.push(()=>{Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ae==null||Ae.destroy(),Ae=null,X==null||X.destroy(),X=null,J=null});let jn=null,Go=()=>{jn&&(jn(),jn=null),o.colorScheme==="auto"&&(jn=Pu(()=>{Yr(e,o)}))};Go(),gt.push(()=>{jn&&(jn(),jn=null)});let ro=(fd=o.features)==null?void 0:fd.streamAnimation;if(ro!=null&&ro.type&&ro.type!=="none"){let c=ia(ro.type,ro.plugins);c&&(Ol(c,e),gt.push(()=>wm(e)))}let mo=Um(Mt),Kn=null,M,Gn=!1,fo=gm(),Bo=new Map,To=new Map,fs=0,go=Mi(),ho=0,bo=null,Ho=!1,mr=!1,Ia=4,gs=24,Ra=80,Nr=new Map,ft={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},hs=(hd=(gd=o.voiceRecognition)==null?void 0:gd.autoResume)!=null?hd:!1,so=c=>{s.emit("voice:state",{active:ft.active,source:c,timestamp:Date.now()})},Pn=()=>{p(c=>({...c,voiceState:{active:ft.active,timestamp:Date.now(),manuallyDeactivated:ft.manuallyDeactivated}}))},Pa=()=>{var y,W;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=pc(d.voiceState),f=!!c.active,h=Number((W=c.timestamp)!=null?W:0);ft.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-h<cy&&setTimeout(()=>{var _,$;ft.active||(ft.manuallyDeactivated=!1,(($=(_=o.voiceRecognition)==null?void 0:_.provider)==null?void 0:$.type)==="runtype"?M.toggleVoice().then(()=>{ft.active=M.isVoiceActive(),so("restore"),M.isVoiceActive()&&z()}):br("restore"))},1e3)},Wa=()=>M?mf(M.getMessages()).filter(c=>!c.__skipPersist):[];function _r(c){if(!(i!=null&&i.save))return;let h={messages:c?mf(c):M?Wa():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Do=null,Ba=()=>ve.querySelector("#persona-scroll-container")||Y,fr=()=>{Do!==null&&(cancelAnimationFrame(Do),Do=null),Ho=!1},bs=()=>{bo!==null&&(cancelAnimationFrame(bo),bo=null),mr=!1,fr()},Fo=()=>{if(!vn()||pe){kt.parentNode&&kt.remove(),kt.style.display="none";return}kt.parentNode!==de&&de.appendChild(kt),yt();let c=ra(Y)>0;kt.style.display=go.isFollowing()||!c?"none":""},ys=()=>{go.pause()&&(bs(),Fo())},Yo=()=>{go.resume(),Fo()},Xo=(c=!1)=>{go.isFollowing()&&(!c&&!Gn||(bo!==null&&(cancelAnimationFrame(bo),bo=null),mr=!0,bo=requestAnimationFrame(()=>{bo=null,mr=!1,go.isFollowing()&&Ha(Ba(),c?220:140)})))},Ha=(c,f=500)=>{let h=c.scrollTop,y=ra(c),W=y-h;if(Math.abs(W)<1){ho=c.scrollTop;return}if(Math.abs(W)>=Ra){fr(),Ho=!0,c.scrollTop=y,ho=c.scrollTop,Ho=!1;return}fr();let _=performance.now();Ho=!0;let $=N=>1-Math.pow(1-N,3),q=N=>{if(!go.isFollowing()){fr();return}let Te=ra(c);Te!==y&&(y=Te,W=y-h);let me=N-_,ee=Math.min(me/f,1),be=$(ee),Me=h+W*be;c.scrollTop=Me,ho=c.scrollTop,ee<1?Do=requestAnimationFrame(q):(c.scrollTop=y,ho=c.scrollTop,Do=null,Ho=!1)};Do=requestAnimationFrame(q)},Da=c=>{let f=new Map;c.forEach(h=>{let y=Nr.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}))}),Nr.clear(),f.forEach((h,y)=>{Nr.set(y,h)})},gr=(c,f,h)=>{var Qe,it,lt,We,Pe,Ke;let y=document.createElement("div"),_=(()=>{var Le;let P=r.find(He=>He.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Le=o.loadingIndicator)!=null&&Le.render)return o.loadingIndicator.render})(),$=(P,Le)=>Le==null?!1:typeof Le=="string"?(P.textContent=Le,!0):(P.appendChild(Le),!0),q=new Set,N=new Set,Te=r.some(P=>P.renderAskUserQuestion),me=[],ee=[],be=o.enableComponentStreaming!==!1;if(f.forEach(P=>{var Tn,pn,Ze,ct,kn,fn,yr,vr,xr,jr,Kr,jt,wr,or;q.add(P.id);let Le=Te&&Rr(P),He=!Le&&P.role==="assistant"&&!P.variant&&be&&cf(P);if(!He&&To.has(P.id)){let bt=c.querySelector(`#wrapper-${P.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),To.delete(P.id)}let Ye=Rr(P)?`:${(Tn=P.agentMetadata)!=null&&Tn.askUserQuestionAnswered?"a":"u"}:${(pn=P.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Se=fm(P,fs)+Ye,It=Le||He?null:hm(fo,P.id,Se);if(It){y.appendChild(It.cloneNode(!0)),Rr(P)&&((Ze=P.toolCall)!=null&&Ze.id)&&((ct=P.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((kn=P.agentMetadata)!=null&&kn.askUserQuestionAnswered)&&(N.add(P.toolCall.id),ji(P,o,De.composerOverlay));return}let at=null,Qt=r.find(bt=>!!(P.variant==="reasoning"&&bt.renderReasoning||P.variant==="tool"&&bt.renderToolCall||P.variant==="approval"&&bt.renderApproval||!P.variant&&bt.renderMessage)),dn=(fn=o.layout)==null?void 0:fn.messages;if(Rr(P)&&((yr=P.agentMetadata)==null?void 0:yr.askUserQuestionAnswered)===!0){Bo.delete(P.id);let bt=c.querySelector(`#wrapper-${P.id}`);bt==null||bt.removeAttribute("data-preserve-runtime");return}if(Rr(P)&&((xr=(vr=o.features)==null?void 0:vr.askUserQuestion)==null?void 0:xr.enabled)!==!1){let bt=r.find(Wn=>typeof Wn.renderAskUserQuestion=="function");if(bt&&Rt.current){let Wn=Bo.get(P.id),_o=Wn!==Se,En=null;if(_o){let{payload:zt,complete:Ft}=ss(P),Kt=P.id,Hn=()=>{var Xn;return(Xn=Rt.current)==null?void 0:Xn.getMessages().find(tn=>tn.id===Kt)};En=bt.renderAskUserQuestion({message:P,payload:zt,complete:Ft,resolve:Xn=>{var Eo;let tn=Hn();tn&&((Eo=Rt.current)==null||Eo.resolveAskUserQuestion(tn,Xn))},dismiss:()=>{var tn,Eo,Vo;let Xn=Hn();(tn=Xn==null?void 0:Xn.agentMetadata)!=null&&tn.awaitingLocalTool&&((Eo=Rt.current)==null||Eo.markAskUserQuestionResolved(Xn),(Vo=Rt.current)==null||Vo.resolveAskUserQuestion(Xn,"(dismissed)"))},config:o})}let Bn=Wn!=null;if(_o&&En===null&&!Bn){((jr=P.agentMetadata)==null?void 0:jr.awaitingLocalTool)===!0&&!((Kr=P.agentMetadata)!=null&&Kr.askUserQuestionAnswered)&&(N.add(P.toolCall.id),ji(P,o,De.composerOverlay));return}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${P.id}`,Dt.setAttribute("data-wrapper-id",P.id),Dt.setAttribute("data-ask-plugin-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),y.appendChild(Dt),me.push({messageId:P.id,fingerprint:Se,bubble:En});return}else{((jt=P.agentMetadata)==null?void 0:jt.awaitingLocalTool)===!0&&!((wr=P.agentMetadata)!=null&&wr.askUserQuestionAnswered)&&(N.add(P.toolCall.id),ji(P,o,De.composerOverlay));return}}else if(Qt)if(P.variant==="reasoning"&&P.reasoning&&Qt.renderReasoning){if(!ae)return;at=Qt.renderReasoning({message:P,defaultRenderer:()=>ql(P,o),config:o})}else if(P.variant==="tool"&&P.toolCall&&Qt.renderToolCall){if(!ge)return;at=Qt.renderToolCall({message:P,defaultRenderer:()=>jl(P,o),config:o})}else if(P.variant==="approval"&&P.approval&&Qt.renderApproval){if(o.approval===!1)return;at=Qt.renderApproval({message:P,defaultRenderer:()=>ec(P,o),config:o})}else Qt.renderMessage&&(at=Qt.renderMessage({message:P,defaultRenderer:()=>{let bt=zl(P,h,dn,o.messageActions,ne,{loadingIndicatorRenderer:_,widgetConfig:o});return P.role!=="user"&&rc(bt,P,o,M),bt},config:o}));if(!at&&He){let bt=df(P);if(bt){let Wn=To.get(P.id),_o=Wn!==Se,En=o.wrapComponentDirectiveInBubble!==!1,Bn=null;if(_o){let Dt=af(bt,{config:o,message:P,transform:h});if(Dt)if(En){let zt=document.createElement("div");if(zt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),zt.id=`bubble-${P.id}`,zt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let Ft=document.createElement("div");Ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ft.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),zt.appendChild(Ft)}zt.appendChild(Dt),Bn=zt}else{let zt=document.createElement("div");if(zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",zt.id=`bubble-${P.id}`,zt.setAttribute("data-message-id",P.id),zt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let Ft=document.createElement("div");Ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ft.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),zt.appendChild(Ft)}zt.appendChild(Dt),Bn=zt}}if(Bn||Wn!=null){let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${P.id}`,Dt.setAttribute("data-wrapper-id",P.id),Dt.setAttribute("data-component-directive-stub","true"),Dt.setAttribute("data-preserve-runtime","true"),En||Dt.classList.add("persona-w-full"),y.appendChild(Dt),ee.push({messageId:P.id,fingerprint:Se,bubble:Bn});return}}}if(!at)if(P.variant==="reasoning"&&P.reasoning){if(!ae)return;at=ql(P,o)}else if(P.variant==="tool"&&P.toolCall){if(!ge)return;at=jl(P,o)}else if(P.variant==="approval"&&P.approval){if(o.approval===!1)return;at=ec(P,o)}else{let bt=(or=o.layout)==null?void 0:or.messages;bt!=null&&bt.renderUserMessage&&P.role==="user"?at=bt.renderUserMessage({message:P,config:o,streaming:!!P.streaming}):bt!=null&&bt.renderAssistantMessage&&P.role==="assistant"?at=bt.renderAssistantMessage({message:P,config:o,streaming:!!P.streaming}):at=zl(P,h,bt,o.messageActions,ne,{loadingIndicatorRenderer:_,widgetConfig:o}),P.role!=="user"&&at&&rc(at,P,o,M)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${P.id}`,Wt.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Wt.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(at),bm(fo,P.id,Se,Wt),y.appendChild(Wt)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let He=Le.getAttribute("data-persona-ask-sheet-for");He&&!N.has(He)&&is(De.composerOverlay,He)}),(it=(Qe=o.features)==null?void 0:Qe.toolCallDisplay)!=null&&it.grouped){let P=[],Le=[];f.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&ge){Le.push(He);return}Le.length>1&&P.push(Le),Le=[]}),Le.length>1&&P.push(Le),P.forEach((He,Ye)=>{var pn,Ze;let Se=He.map(ct=>Array.from(y.children).find(kn=>kn instanceof HTMLElement&&kn.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(Se.length<2)return;let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-tool-group-${Ye}-${He[0].id}`,It.setAttribute("data-wrapper-id",`tool-group-${Ye}-${He[0].id}`);let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Qt=document.createElement("div");Qt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${He.length} tools`,Wt=(Ze=(pn=o.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Ze.call(pn,{messages:He,toolCalls:He.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:o});$(Qt,Wt)||(Qt.textContent=dn);let Tn=document.createElement("div");Tn.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Qt,Tn),It.appendChild(at),Se[0].before(It),Se.forEach((ct,kn)=>{let fn=document.createElement("div");fn.className="persona-tool-group-item persona-relative",fn.setAttribute("data-persona-tool-group-item","true"),kn<Se.length-1&&fn.setAttribute("data-persona-tool-group-connector","true"),fn.appendChild(ct),Tn.appendChild(fn)})})}ym(fo,q);let Me=f.some(P=>P.role==="assistant"&&P.streaming),_e=f[f.length-1],nt=(_e==null?void 0:_e.role)==="assistant"&&!_e.streaming&&_e.variant!=="approval";if(Gn&&f.some(P=>P.role==="user")&&!Me&&!nt){let P={config:o,streaming:!0,location:"standalone",defaultRenderer:fa},Le=r.find(Ye=>Ye.renderLoadingIndicator),He=null;if(Le!=null&&Le.renderLoadingIndicator&&(He=Le.renderLoadingIndicator(P)),He===null&&((lt=o.loadingIndicator)!=null&&lt.render)&&(He=o.loadingIndicator.render(P)),He===null&&(He=fa()),He){let Ye=document.createElement("div"),Se=((We=o.loadingIndicator)==null?void 0:We.showBubble)!==!1;Ye.className=Se?["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(" "),Ye.setAttribute("data-typing-indicator","true"),Ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ye.appendChild(He);let It=document.createElement("div");It.className="persona-flex",It.id="wrapper-typing-indicator",It.setAttribute("data-wrapper-id","typing-indicator"),It.appendChild(Ye),y.appendChild(It)}}if(!Gn&&f.length>0){let P=f[f.length-1],Le={config:o,lastMessage:P,messageCount:f.length},He=r.find(Se=>Se.renderIdleIndicator),Ye=null;if(He!=null&&He.renderIdleIndicator&&(Ye=He.renderIdleIndicator(Le)),Ye===null&&((Pe=o.loadingIndicator)!=null&&Pe.renderIdle)&&(Ye=o.loadingIndicator.renderIdle(Le)),Ye){let Se=document.createElement("div"),It=((Ke=o.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;Se.className=It?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Se.setAttribute("data-idle-indicator","true"),Se.appendChild(Ye);let at=document.createElement("div");at.className="persona-flex",at.id="wrapper-idle-indicator",at.setAttribute("data-wrapper-id","idle-indicator"),at.appendChild(Se),y.appendChild(at)}}if(ki(c,y),me.length>0)for(let{messageId:P,fingerprint:Le,bubble:He}of me){let Ye=c.querySelector(`#wrapper-${P}`);Ye&&He!==null&&(Ye.replaceChildren(He),Ye.setAttribute("data-bubble-fp",Le),Bo.set(P,Le))}if(Bo.size>0)for(let P of Bo.keys())q.has(P)||Bo.delete(P);if(ee.length>0)for(let{messageId:P,fingerprint:Le,bubble:He}of ee){let Ye=c.querySelector(`#wrapper-${P}`);Ye&&He!==null&&(Ye.replaceChildren(He),Ye.setAttribute("data-bubble-fp",Le),To.set(P,Le))}if(To.size>0)for(let P of To.keys())q.has(P)||To.delete(P)},Qo=null,Fa=()=>{var h;if(Qo)return;let c=y=>{let W=y.composedPath();W.includes(ve)||ze&&W.includes(ze)||Ht(!1,"user")};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},vs=()=>{var f;if(!Qo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Qo,!0),Qo=null};gt.push(()=>vs());let Jo=null,Oa=()=>{var h;if(Jo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ht(!1,"user"))};Jo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},xs=()=>{var f;if(!Jo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Jo,!0),Jo=null};gt.push(()=>xs());let Zo=!1,ws=new Set,Na=()=>{var f,h,y,W;let c=(y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((W=o.features)==null?void 0:W.streamAnimation)},Oo=()=>{var it,lt,We,Pe;if(!E())return;let c=De.peekBanner,f=De.peekTextNode;if(!c||!f)return;if(k){c.classList.remove("persona-pill-peek--visible");return}let h=(it=M==null?void 0:M.getMessages())!=null?it:[],y;for(let Ke=h.length-1;Ke>=0;Ke--){let P=h[Ke];if(P.role==="assistant"&&P.content){y=P;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let W=y.content,_=!!y.streaming,$=Na(),q=Ri($),N=q.type!=="none"?ia(q.type,$==null?void 0:$.plugins):null,Te=((lt=N==null?void 0:N.isAnimating)==null?void 0:lt.call(N,y))===!0,me=N!==null&&(_||Te);me&&N&&!ws.has(N.name)&&(Ol(N,e),ws.add(N.name));let ee=me&&(N!=null&&N.containerClass)?N.containerClass:null,be=(We=f.dataset.personaPeekStreamClass)!=null?We:null;be&&be!==ee&&(f.classList.remove(be),delete f.dataset.personaPeekStreamClass),ee&&be!==ee&&(f.classList.add(ee),f.dataset.personaPeekStreamClass=ee),me?(f.style.setProperty("--persona-stream-step",`${q.speed}ms`),f.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Me=me?Pi(W,q.buffer,N,y,_):W;if(me&&q.placeholder==="skeleton"&&_&&(!Me||!Me.trim())){let Ke=document.createElement("div"),P=ca();P.classList.add("persona-pill-peek__skeleton"),Ke.appendChild(P),ki(f,Ke)}else{let Ke=Math.max(0,Me.length-100),P=Me.length>100?Me.slice(-100):Me,Le=Ys(P);if(!me||!N){let He=Me.length>100?`\u2026${P}`:P;f.textContent!==He&&(f.textContent=He)}else{let He=Le;(N.wrap==="char"||N.wrap==="word")&&(He=la(Le,N.wrap,`peek-${y.id}`,{skipTags:N.skipTags,startIndex:Ke}));let Ye=document.createElement("div");if(Ye.innerHTML=He,N.useCaret&&P.length>0){let Se=Wi(),It=Ye.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=It[It.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(Se,at.nextSibling):Ye.appendChild(Se)}ki(f,Ye),(Pe=N.onAfterRender)==null||Pe.call(N,{container:f,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Qe=Gn||Zo;c.classList.toggle("persona-pill-peek--visible",Qe)};if(E()){let c=De.peekBanner;if(c){let y=W=>{W.preventDefault(),W.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let f=()=>{Zo||(Zo=!0,Oo())},h=()=>{Zo&&(Zo=!1,Oo())};ce.addEventListener("pointerenter",f),ce.addEventListener("pointerleave",h),gt.push(()=>{ce.removeEventListener("pointerenter",f),ce.removeEventListener("pointerleave",h)}),ze&&(ze.addEventListener("pointerenter",f),ze.addEventListener("pointerleave",h),gt.push(()=>{ze.removeEventListener("pointerenter",f),ze.removeEventListener("pointerleave",h)}))}let _a=c=>{var be,Me,_e,nt,Qe,it,lt,We;let f=(Me=(be=o.launcher)==null?void 0:be.composerBar)!=null?Me:{},h=(_e=f.expandedSize)!=null?_e:"anchored",y=(nt=f.bottomOffset)!=null?nt:"16px",W=f.collapsedMaxWidth,_=(Qe=f.expandedMaxWidth)!=null?Qe:"880px",$=(it=f.expandedTopOffset)!=null?it:"5vh",q=(lt=f.modalMaxWidth)!=null?lt:"880px",N=(We=f.modalMaxHeight)!=null?We:"min(90vh, 800px)",Te="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",ee=ve.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",ze){let Pe=ze.style;Pe.bottom=y,Pe.width=W!=null?W:""}if(c&&h!=="fullscreen"){if(h==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=q,ee.maxWidth=Te,ee.maxHeight=N,ee.height=N;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${me})`,ee.top=$,ee.width=_,ee.maxWidth=Te}},er=()=>{var N,Te,me,ee,be,Me,_e,nt;if(!C())return;if(E()){let it=(me=((Te=(N=o.launcher)==null?void 0:N.composerBar)!=null?Te:{}).expandedSize)!=null?me:"anchored",lt=k?"expanded":"collapsed";ve.dataset.state=lt,ve.dataset.expandedSize=it,ze&&(ze.dataset.state=lt,ze.dataset.expandedSize=it),ve.style.removeProperty("display"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),_a(k),de.style.display=k?"flex":"none",uo(),k?(Fa(),Oa()):(vs(),xs()),Oo();return}let c=un(o),f=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(Me=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?Me:640,y=(nt=(_e=o.launcher)==null?void 0:_e.mobileFullscreen)!=null?nt:!0,W=f.innerWidth<=h,_=y&&W&&R,$=Lo(o).reveal;k?(ve.style.removeProperty("display"),ve.style.display=c?"flex":"",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Re?Re.element.style.display="none":Xe&&(Xe.style.display="none")):(c?c&&($==="overlay"||$==="push")&&!_?(ve.style.removeProperty("display"),ve.style.display="flex",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.setProperty("display","none","important"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.display="",ve.classList.add("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Re?Re.element.style.display=c?"none":"":Xe&&(Xe.style.display=c?"none":""))},Ht=(c,f="user")=>{var _,$;if(!C()||k===c)return;let h=k;k=c,er();let y=(()=>{var _e,nt,Qe,it,lt,We,Pe,Ke,P,Le;let q=(nt=(_e=o.launcher)==null?void 0:_e.sidebarMode)!=null?nt:!1,N=(Qe=e.ownerDocument.defaultView)!=null?Qe:window,Te=(lt=(it=o.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,me=(Pe=(We=o.launcher)==null?void 0:We.mobileBreakpoint)!=null?Pe:640,ee=N.innerWidth<=me,be=un(o)&&Te&&ee,Me=E()&&((Le=(P=(Ke=o.launcher)==null?void 0:Ke.composerBar)==null?void 0:P.expandedSize)!=null?Le:"fullscreen")==="fullscreen";return q||Te&&ee&&R||be||Me})();if(k&&y){if(!Gt){let q=e.getRootNode(),N=q instanceof ShadowRoot?q.host:e.closest(".persona-host");N&&(Gt=Nl(N,($=(_=o.launcher)==null?void 0:_.zIndex)!=null?$:bn))}Yt||(Yt=_l(e.ownerDocument))}else k||(Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null);k&&(Pt(),Xo(!0));let W={open:k,source:f,timestamp:Date.now()};k&&!h?s.emit("widget:opened",W):!k&&h&&s.emit("widget:closed",W),s.emit("widget:state",{open:k,launcherEnabled:R,voiceActive:ft.active,streaming:M.isStreaming()})},Vr=c=>{$t(c?"stop":"send"),j&&(j.disabled=c),mo.buttons.forEach(f=>{f.disabled=c}),Ue.dataset.personaComposerStreaming=c?"true":"false",Ue.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},$r=()=>{ft.active||ue&&ue.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>$r(),200)});let Cs=()=>{var h,y,W,_,$,q,N,Te,me,ee,be;Fn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Zn.textContent=(_=(W=o.copy)==null?void 0:W.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",ue.placeholder=(q=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?q:"How can I help...";let c=Y.querySelector("[data-persona-intro-card]");if(c){let Me=((N=o.copy)==null?void 0:N.showWelcomeCard)!==!1;c.style.display=Me?"":"none",Me?(Y.classList.remove("persona-gap-3"),Y.classList.add("persona-gap-6")):(Y.classList.remove("persona-gap-6"),Y.classList.add("persona-gap-3"))}!((me=(Te=o.sendButton)==null?void 0:Te.useIcon)!=null&&me)&&!(M!=null&&M.isStreaming())&&(ie.textContent=(be=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?be:"Send"),ue.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ue.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 ko=null,Va=()=>{ko==null&&(ko=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(ko),ko=null;return}let f=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=fi(f-y))})},100))};if(M=new Ai(o,{onMessagesChanged(c){gr($e,c,fe),Va(),M&&(c.some(W=>W.role==="user")?mo.render([],M,ue,c):mo.render(o.suggestionChips,M,ue,c,o.suggestionChipsConfig)),Xo(!Gn),Da(c);let f=[...c].reverse().find(y=>y.role==="user"),h=ft.lastUserMessageId;f&&f.id!==h&&(ft.lastUserMessageId=f.id,s.emit("user:message",f)),ft.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),_r(c),Oo()},onStatusChanged(c){var y;let f=(y=o.statusIndicator)!=null?y:{};ot(cn,(W=>{var _,$,q,N;return W==="idle"?(_=f.idleText)!=null?_:hn.idle:W==="connecting"?($=f.connectingText)!=null?$:hn.connecting:W==="connected"?(q=f.connectedText)!=null?q:hn.connected:W==="error"?(N=f.errorText)!=null?N:hn.error:hn[W]})(c),f,c)},onStreamingChanged(c){Gn=c,Vr(c),M&&gr($e,M.getMessages(),fe),c||Xo(!0),Oo()},onVoiceStatusChanged(c){var f,h;if(((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":te(),H();break;case"speaking":te(),Z();break;default:c==="idle"&&M.isBargeInActive()?(te(),z(),j==null||j.setAttribute("aria-label","End voice session")):(ft.active=!1,te(),so("system"),Pn());break}},onArtifactsState(c){$n=c,qn(),_r()}}),Rt.current=M,((yd=(bd=o.voiceRecognition)==null?void 0:bd.provider)==null?void 0:yd.type)==="runtype")try{M.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&M.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(X||o.onSSEEvent)&&M.setSSEEventCallback((c,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,f),we==null||we.processEvent(c,f),X==null||X.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=pc(c.metadata),L.syncFromMetadata()),(f=c.messages)!=null&&f.length&&M.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&M.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Ss=()=>{var f,h,y;!E()||k||!((y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ht(!0,"auto")},As=c=>{var W;if(c.preventDefault(),M.isStreaming()){M.cancel(),we==null||we.reset(),Ae==null||Ae.update();return}let f=ue.value.trim(),h=(W=tt==null?void 0:tt.hasAttachments())!=null?W:!1;if(!f&&!h)return;Ss();let y;h&&(y=[],y.push(...tt.getContentParts()),f&&y.push(Bl(f))),ue.value="",ue.style.height="auto",hr(),M.sendMessage(f,{contentParts:y}),h&&tt.clearAttachments()},$a=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Ur={...Ei},zr=!1,hr=()=>{Ur={...Ei}},Ua=()=>M.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),za=c=>{if(!ue)return;zr=!0,ue.value=c,ue.dispatchEvent(new Event("input",{bubbles:!0})),zr=!1;let f=ue.value.length;ue.setSelectionRange(f,f)},Ts=()=>{zr||hr()},ks=c=>{if(ue){if($a()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=ue.selectionStart===0&&ue.selectionEnd===0,h=mm({direction:c.key==="ArrowUp"?"up":"down",history:Ua(),currentValue:ue.value,atStart:f,state:Ur});if(Ur=h.state,h.handled){c.preventDefault(),h.value!==void 0&&za(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(M.isStreaming()){c.preventDefault();return}hr(),c.preventDefault(),ie.click()}}},Es=c=>{c.key!=="Escape"||c.isComposing||M.isStreaming()&&c.composedPath().includes(de)&&(M.cancel(),we==null||we.reset(),Ae==null||Ae.update(),hr(),c.preventDefault(),c.stopImmediatePropagation())},Ms=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!tt)return;let f=py(c.clipboardData);f.length!==0&&(c.preventDefault(),await tt.handleFiles(f))},Sn=null,Yn=!1,No=null,st=null,Ls=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,br=(c="user")=>{var _,$,q,N,Te,me,ee;if(Yn||M.isStreaming())return;let f=Ls();if(!f)return;Sn=new f;let y=($=((_=o.voiceRecognition)!=null?_:{}).pauseDuration)!=null?$:2e3;Sn.continuous=!0,Sn.interimResults=!0,Sn.lang="en-US";let W=ue.value;Sn.onresult=be=>{let Me="",_e="";for(let Qe=0;Qe<be.results.length;Qe++){let it=be.results[Qe],lt=it[0].transcript;it.isFinal?Me+=lt+" ":_e=lt}let nt=W+Me+_e;ue.value=nt,No&&clearTimeout(No),(Me||_e)&&(No=window.setTimeout(()=>{let Qe=ue.value.trim();Qe&&Sn&&Yn&&(yo(),ue.value="",ue.style.height="auto",M.sendMessage(Qe,{viaVoice:!0}))},y))},Sn.onerror=be=>{be.error!=="no-speech"&&yo()},Sn.onend=()=>{if(Yn){let be=ue.value.trim();be&&be!==W.trim()&&(ue.value="",ue.style.height="auto",M.sendMessage(be,{viaVoice:!0})),yo()}};try{if(Sn.start(),Yn=!0,ft.active=!0,c!=="system"&&(ft.manuallyDeactivated=!1),so(c),Pn(),j){let be=(q=o.voiceRecognition)!=null?q:{};st={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(N=be.iconName)!=null?N:"mic",iconSize:parseFloat((ee=(me=be.iconSize)!=null?me:(Te=o.sendButton)==null?void 0:Te.size)!=null?ee:"40")||24};let Me=be.recordingBackgroundColor,_e=be.recordingIconColor,nt=be.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=_e!=null?_e:"var(--persona-voice-recording-indicator, #ffffff)",_e){let Qe=j.querySelector("svg");Qe&&Qe.setAttribute("stroke",_e)}nt&&(j.style.borderColor=nt),j.setAttribute("aria-label","Stop voice recognition")}}catch{yo("system")}},yo=(c="user")=>{if(Yn){if(Yn=!1,No&&(clearTimeout(No),No=null),Sn){try{Sn.stop()}catch{}Sn=null}if(ft.active=!1,so(c),Pn(),j){if(j.classList.remove("persona-voice-recording"),st){j.style.backgroundColor=st.backgroundColor,j.style.color=st.color,j.style.borderColor=st.borderColor;let f=j.querySelector("svg");f&&f.setAttribute("stroke",st.color||"currentColor"),st=null}j.setAttribute("aria-label","Start voice recognition")}}},qa=(c,f)=>{var it,lt,We,Pe,Ke,P,Le,He;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(h||y))return null;let _=b("div","persona-send-button-wrapper"),$=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button",$.setAttribute("aria-label","Start voice recognition");let q=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",N=(We=f==null?void 0:f.size)!=null?We:"40px",Te=(Pe=c==null?void 0:c.iconSize)!=null?Pe:N,me=parseFloat(Te)||24,ee=(Ke=c==null?void 0:c.backgroundColor)!=null?Ke:f==null?void 0:f.backgroundColor,be=(P=c==null?void 0:c.iconColor)!=null?P:f==null?void 0:f.textColor;$.style.width=Te,$.style.height=Te,$.style.minWidth=Te,$.style.minHeight=Te,$.style.fontSize="18px",$.style.lineHeight="1",be?$.style.color=be:$.style.color="var(--persona-text, #111827)";let _e=ke(q,me,be||"currentColor",1.5);_e?$.appendChild(_e):$.textContent="\u{1F3A4}",ee?$.style.backgroundColor=ee:$.style.backgroundColor="",c!=null&&c.borderWidth&&($.style.borderWidth=c.borderWidth,$.style.borderStyle="solid"),c!=null&&c.borderColor&&($.style.borderColor=c.borderColor),c!=null&&c.paddingX&&($.style.paddingLeft=c.paddingX,$.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&($.style.paddingTop=c.paddingY,$.style.paddingBottom=c.paddingY),_.appendChild($);let nt=(Le=c==null?void 0:c.tooltipText)!=null?Le:"Start voice recognition";if(((He=c==null?void 0:c.showTooltip)!=null?He:!1)&&nt){let Ye=b("div","persona-send-button-tooltip");Ye.textContent=nt,_.appendChild(Ye)}return{micButton:$,micButtonWrapper:_}},tr=()=>{var f,h,y,W,_;if(!j||st)return;let c=(f=o.voiceRecognition)!=null?f:{};st={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((_=(W=c.iconSize)!=null?W:(y=o.sendButton)==null?void 0:y.size)!=null?_:"40")||24}},Ge=(c,f)=>{var _,$,q,N,Te;if(!j)return;let h=j.querySelector("svg");h&&h.remove();let y=(Te=st==null?void 0:st.iconSize)!=null?Te:parseFloat((N=(q=(_=o.voiceRecognition)==null?void 0:_.iconSize)!=null?q:($=o.sendButton)==null?void 0:$.size)!=null?N:"40")||24,W=ke(c,y,f,1.5);W&&j.appendChild(W)},T=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},z=()=>{var W;if(!j)return;tr();let c=(W=o.voiceRecognition)!=null?W:{},f=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(T(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let _=j.querySelector("svg");_&&_.setAttribute("stroke",h)}y&&(j.style.borderColor=y),j.setAttribute("aria-label","Stop voice recognition")},H=()=>{var q,N,Te,me,ee,be,Me,_e;if(!j)return;tr();let c=(q=o.voiceRecognition)!=null?q:{},f=M.getVoiceInterruptionMode(),h=(N=c.processingIconName)!=null?N:"loader",y=(me=(Te=c.processingIconColor)!=null?Te:st==null?void 0:st.color)!=null?me:"",W=(be=(ee=c.processingBackgroundColor)!=null?ee:st==null?void 0:st.backgroundColor)!=null?be:"",_=(_e=(Me=c.processingBorderColor)!=null?Me:st==null?void 0:st.borderColor)!=null?_e:"";T(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=W,j.style.borderColor=_;let $=y||"currentColor";j.style.color=$,Ge(h,$),j.setAttribute("aria-label","Processing voice input"),f==="none"&&(j.style.cursor="default")},Z=()=>{var Te,me,ee,be,Me,_e,nt,Qe,it,lt,We,Pe;if(!j)return;tr();let c=(Te=o.voiceRecognition)!=null?Te:{},f=M.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",y=(me=c.speakingIconName)!=null?me:h,W=(_e=c.speakingIconColor)!=null?_e:f==="barge-in"?(be=(ee=c.recordingIconColor)!=null?ee:st==null?void 0:st.color)!=null?be:"":(Me=st==null?void 0:st.color)!=null?Me:"",_=(it=c.speakingBackgroundColor)!=null?it:f==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(Qe=st==null?void 0:st.backgroundColor)!=null?Qe:"",$=(Pe=c.speakingBorderColor)!=null?Pe:f==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(We=st==null?void 0:st.borderColor)!=null?We:"";T(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=_,j.style.borderColor=$;let q=W||"currentColor";j.style.color=q,Ge(y,q);let N=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",N),f==="none"&&(j.style.cursor="default"),f==="barge-in"&&j.classList.add("persona-voice-recording")},te=()=>{var c,f,h;j&&(T(),st&&(j.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",j.style.color=(f=st.color)!=null?f:"",j.style.borderColor=(h=st.borderColor)!=null?h:"",Ge(st.iconName,st.color||"currentColor"),st=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},G=()=>{var c,f;if(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let h=M.getVoiceStatus(),y=M.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){M.stopVoicePlayback();return}if(M.isBargeInActive()){M.stopVoicePlayback(),M.deactivateBargeIn().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Pn(),so("user"),te()});return}M.toggleVoice().then(()=>{ft.active=M.isVoiceActive(),ft.manuallyDeactivated=!M.isVoiceActive(),Pn(),so("user"),M.isVoiceActive()?z():te()});return}if(Yn){let h=ue.value.trim();ft.manuallyDeactivated=!0,Pn(),yo("user"),h&&(ue.value="",ue.style.height="auto",M.sendMessage(h))}else ft.manuallyDeactivated=!1,Pn(),br("user")};On=G,j&&(j.addEventListener("click",G),gt.push(()=>{var c,f;((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(M.isVoiceActive()&&M.toggleVoice(),te()):yo("system"),j&&j.removeEventListener("click",G)}));let Be=s.on("assistant:complete",()=>{hs&&(ft.active||ft.manuallyDeactivated||hs==="assistant"&&!ft.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!ft.active&&!ft.manuallyDeactivated&&(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?M.toggleVoice().then(()=>{ft.active=M.isVoiceActive(),so("auto"),M.isVoiceActive()&&z()}):br("auto"))},600))});gt.push(Be);let Ve=s.on("action:resubmit",()=>{setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)});gt.push(Ve);let et=()=>{Ht(!k,"user")},Re=null,Xe=null;if(R&&!E()){let c=r.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:o,defaultRenderer:()=>ua(o,et).element,onToggle:et});f&&(Xe=f)}Xe||(Re=ua(o,et))}Re?e.appendChild(Re.element):Xe&&e.appendChild(Xe),er(),mo.render(o.suggestionChips,M,ue,void 0,o.suggestionChipsConfig),Cs(),Vr(M.isStreaming()),Xo(!0),Pa(),D&&(!R||E()?setTimeout(()=>$r(),0):k&&setTimeout(()=>$r(),200));let Pt=()=>{var N,Te,me,ee,be,Me,_e,nt,Qe,it,lt,We,Pe,Ke,P,Le,He,Ye,Se,It,at,Qt;if(E()){yt(),er();return}let c=un(o),f=(Te=(N=o.launcher)==null?void 0:N.sidebarMode)!=null?Te:!1,h=c||f||((ee=(me=o.launcher)==null?void 0:me.fullHeight)!=null?ee:!1),y=(be=e.ownerDocument.defaultView)!=null?be:window,W=(_e=(Me=o.launcher)==null?void 0:Me.mobileFullscreen)!=null?_e:!0,_=(Qe=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?Qe:640,$=y.innerWidth<=_,q=W&&$&&R;try{if(q){uo(),Yr(e,o);return}if(x&&(x=!1,uo(),Yr(e,o)),!R&&!c){ce.style.height="",ce.style.width="";return}if(!f&&!c){let dn=(lt=(it=o==null?void 0:o.launcher)==null?void 0:it.width)!=null?lt:o==null?void 0:o.launcherWidth,Wt=dn!=null?dn:lo;ce.style.width=Wt,ce.style.maxWidth=Wt}if(Ao(),!h){let dn=y.innerHeight,Wt=64,Tn=(Pe=(We=o.launcher)==null?void 0:We.heightOffset)!=null?Pe:0,pn=Math.max(200,dn-Wt),Ze=Math.min(640,pn),ct=Math.max(200,Ze-Tn);ce.style.height=`${ct}px`}}finally{if(yt(),er(),k&&R){let Wt=((Ke=e.ownerDocument.defaultView)!=null?Ke:window).innerWidth<=((Le=(P=o.launcher)==null?void 0:P.mobileBreakpoint)!=null?Le:640),Tn=(Ye=(He=o.launcher)==null?void 0:He.sidebarMode)!=null?Ye:!1,pn=(It=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?It:!0,Ze=un(o)&&pn&&Wt,ct=Tn||pn&&Wt&&R||Ze;if(ct&&!Yt){let kn=e.getRootNode(),fn=kn instanceof ShadowRoot?kn.host:e.closest(".persona-host");fn&&!Gt&&(Gt=Nl(fn,(Qt=(at=o.launcher)==null?void 0:at.zIndex)!=null?Qt:bn)),Yt=_l(e.ownerDocument)}else ct||(Gt==null||Gt(),Gt=null,Yt==null||Yt(),Yt=null)}}};Pt();let on=(vd=e.ownerDocument.defaultView)!=null?vd:window;if(on.addEventListener("resize",Pt),gt.push(()=>on.removeEventListener("resize",Pt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(Ue),gt.push(()=>c.disconnect())}ho=Y.scrollTop;let St=Y.scrollHeight,Lt=()=>{let c=Y.scrollTop,f=Y.scrollHeight,h=f<St;St=f;let{action:y,nextLastScrollTop:W}=Li({following:go.isFollowing(),currentScrollTop:c,lastScrollTop:ho,nearBottom:sa(Y,gs),userScrollThreshold:Ia,isAutoScrolling:Ho||mr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ho=W,y==="resume"){Yo();return}y==="pause"&&ys()};Y.addEventListener("scroll",Lt,{passive:!0}),gt.push(()=>Y.removeEventListener("scroll",Lt));let rn=c=>{let f=Ii({following:go.isFollowing(),deltaY:c.deltaY,nearBottom:sa(Y,gs),resumeWhenNearBottom:!0});f==="pause"?ys():f==="resume"&&Yo()};Y.addEventListener("wheel",rn,{passive:!0}),gt.push(()=>Y.removeEventListener("wheel",rn)),kt.addEventListener("click",()=>{Y.scrollTop=Y.scrollHeight,ho=Y.scrollTop,Yo(),Xo(!0)}),gt.push(()=>kt.remove()),gt.push(()=>{bs()});let mn=()=>{je&&(Kn&&(je.removeEventListener("click",Kn),Kn=null),C()?(je.style.display="",Kn=()=>{Ht(!1,"user")},je.addEventListener("click",Kn)):je.style.display="none")};mn(),(()=>{let{clearChatButton:c}=De;c&&c.addEventListener("click",()=>{M.clearMessages(),fo.clear(),Yo(),is(De.composerOverlay);try{localStorage.removeItem(cs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==cs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},L.syncFromMetadata(),X==null||X.clear(),we==null||we.reset(),Ae==null||Ae.update()})})(),_t&&_t.addEventListener("submit",As),ue==null||ue.addEventListener("keydown",ks),ue==null||ue.addEventListener("input",Ts),ue==null||ue.addEventListener("paste",Ms);let Xt=(xd=e.ownerDocument)!=null?xd:document;Xt.addEventListener("keydown",Es,!0);let ao="persona-attachment-drop-active",Is=0,ul=()=>{Is=0,de.classList.remove(ao)},qr=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Ec=c=>{!Qi(c.dataTransfer)||!qr()||(Is++,Is===1&&de.classList.add(ao))},Mc=c=>{!Qi(c.dataTransfer)||!qr()||(Is--,Is<=0&&ul())},Lc=c=>{!Qi(c.dataTransfer)||!qr()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Ic=c=>{var h;if(!Qi(c.dataTransfer)||!qr())return;c.preventDefault(),c.stopPropagation(),ul();let f=Array.from((h=c.dataTransfer.files)!=null?h:[]);f.length!==0&&tt.handleFiles(f)},nr=!0;de.addEventListener("dragenter",Ec,nr),de.addEventListener("dragleave",Mc,nr),e.addEventListener("dragover",Lc,nr),e.addEventListener("drop",Ic,nr);let ja=e.ownerDocument,Rc=c=>{qr()&&c.preventDefault()},Pc=c=>{qr()&&c.preventDefault()};ja.addEventListener("dragover",Rc),ja.addEventListener("drop",Pc),gt.push(()=>{_t&&_t.removeEventListener("submit",As),ue==null||ue.removeEventListener("keydown",ks),ue==null||ue.removeEventListener("input",Ts),ue==null||ue.removeEventListener("paste",Ms),Xt.removeEventListener("keydown",Es,!0)}),gt.push(()=>{de.removeEventListener("dragenter",Ec,nr),de.removeEventListener("dragleave",Mc,nr),e.removeEventListener("dragover",Lc,nr),e.removeEventListener("drop",Ic,nr),ja.removeEventListener("dragover",Rc),ja.removeEventListener("drop",Pc),ul()}),gt.push(()=>{M.cancel()}),Re?gt.push(()=>{Re==null||Re.destroy()}):Xe&&gt.push(()=>{Xe==null||Xe.remove()});let en={update(c){var tn,Eo,Vo,Ka,Ga,Ya,Cr,Xa,Rs,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,fp,gp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Qp,Jp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,fu,gu,hu,bu,yu,vu,xu,wu,Cu;let f=o.toolCall,h=o.messageActions,y=(tn=o.layout)==null?void 0:tn.messages,W=o.colorScheme,_=o.loadingIndicator,$=o.iterationDisplay,q=(Eo=o.features)==null?void 0:Eo.showReasoning,N=(Vo=o.features)==null?void 0:Vo.showToolCalls,Te=(Ka=o.features)==null?void 0:Ka.toolCallDisplay,me=(Ga=o.features)==null?void 0:Ga.reasoningDisplay;o={...o,...c},uo(),Yr(e,o),Yi(e,o),Xi(e,o),qn(),o.colorScheme!==W&&Go();let ee=ac.getForInstance(o.plugins);r.length=0,r.push(...ee),R=(Cr=(Ya=o.launcher)==null?void 0:Ya.enabled)!=null?Cr:!0,I=(Rs=(Xa=o.launcher)==null?void 0:Xa.autoExpand)!=null?Rs:!1,ae=(Md=(Ed=o.features)==null?void 0:Ed.showReasoning)!=null?Md:!0,ge=(Id=(Ld=o.features)==null?void 0:Ld.showToolCalls)!=null?Id:!0,ye=(Pd=(Rd=o.features)==null?void 0:Rd.scrollToBottom)!=null?Pd:{},qt(),Fo();let be=le;if(le=(Bd=(Wd=o.features)==null?void 0:Wd.showEventStreamToggle)!=null?Bd:!1,le&&!be){if(X||(J=new ba(xe),X=new ha(Ie,J),we=we!=null?we:new ya,J.open().then(()=>X==null?void 0:X.restore()).catch(()=>{}),M.setSSEEventCallback((Q,xt)=>{var Nt;(Nt=o.onSSEEvent)==null||Nt.call(o,Q,xt),we==null||we.processEvent(Q,xt),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!mt&&Oe){let Q=(Dd=(Hd=o.features)==null?void 0:Hd.eventStream)==null?void 0:Dd.classNames,xt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");mt=b("button",xt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Ln.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Nt=ke("activity","18px","currentColor",1.5);Nt&&mt.appendChild(Nt);let dt=De.clearChatButtonWrapper,Et=De.closeButtonWrapper,sn=dt||Et;sn&&sn.parentNode===Oe?Oe.insertBefore(mt,sn):Oe.appendChild(mt),mt.addEventListener("click",()=>{pe?Nn():xn()})}}else!le&&be&&(Nn(),mt&&(mt.remove(),mt=null),X==null||X.clear(),J==null||J.destroy(),X=null,J=null,we==null||we.reset(),we=null);if(((Fd=o.launcher)==null?void 0:Fd.enabled)===!1&&Re&&(Re.destroy(),Re=null),((Od=o.launcher)==null?void 0:Od.enabled)===!1&&Xe&&(Xe.remove(),Xe=null),((Nd=o.launcher)==null?void 0:Nd.enabled)!==!1&&!Re&&!Xe){let Q=r.find(xt=>xt.renderLauncher);if(Q!=null&&Q.renderLauncher){let xt=Q.renderLauncher({config:o,defaultRenderer:()=>ua(o,et).element,onToggle:et});xt&&(Xe=xt,e.appendChild(Xe))}Xe||(Re=ua(o,et),e.appendChild(Re.element))}Re&&Re.update(o),Ee&&((_d=o.launcher)==null?void 0:_d.title)!==void 0&&(Ee.textContent=o.launcher.title),Fe&&((Vd=o.launcher)==null?void 0:Vd.subtitle)!==void 0&&(Fe.textContent=o.launcher.subtitle);let Me=($d=o.layout)==null?void 0:$d.header;if((Me==null?void 0:Me.layout)!==v&&Oe){let Q=Me?Fi(o,Me,{showClose:C(),onClose:()=>Ht(!1,"user")}):Ir({config:o,showClose:C(),onClose:()=>Ht(!1,"user")});Oe.replaceWith(Q.header),Oe=Q.header,V=Q.iconHolder,Ee=Q.headerTitle,Fe=Q.headerSubtitle,je=Q.closeButton,v=Me==null?void 0:Me.layout}else if(Me&&(V&&(V.style.display=Me.showIcon===!1?"none":""),Ee&&(Ee.style.display=Me.showTitle===!1?"none":""),Fe&&(Fe.style.display=Me.showSubtitle===!1?"none":""),je&&(je.style.display=Me.showCloseButton===!1?"none":""),De.clearChatButtonWrapper)){let Q=Me.showClearChat;if(Q!==void 0){De.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:xt}=De;xt&&!xt.classList.contains("persona-absolute")&&(Q?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let nt=((Ud=o.layout)==null?void 0:Ud.showHeader)!==!1;Oe&&(Oe.style.display=nt?"":"none");let Qe=((zd=o.layout)==null?void 0:zd.showFooter)!==!1;Ue&&(Ue.style.display=Qe?"":"none"),yt(),Fo(),R!==B?R?Ht(I,"auto"):(k=!0,er()):I!==F&&Ht(I,"auto"),F=I,B=R,Pt(),mn();let We=JSON.stringify(c.toolCall)!==JSON.stringify(f),Pe=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((qd=o.layout)==null?void 0:qd.messages)!==JSON.stringify(y),P=((jd=o.loadingIndicator)==null?void 0:jd.render)!==(_==null?void 0:_.render)||((Kd=o.loadingIndicator)==null?void 0:Kd.renderIdle)!==(_==null?void 0:_.renderIdle)||((Gd=o.loadingIndicator)==null?void 0:Gd.showBubble)!==(_==null?void 0:_.showBubble),Le=o.iterationDisplay!==$,He=((Xd=(Yd=o.features)==null?void 0:Yd.showReasoning)!=null?Xd:!0)!==(q!=null?q:!0)||((Jd=(Qd=o.features)==null?void 0:Qd.showToolCalls)!=null?Jd:!0)!==(N!=null?N:!0)||JSON.stringify((Zd=o.features)==null?void 0:Zd.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((ep=o.features)==null?void 0:ep.reasoningDisplay)!==JSON.stringify(me);(We||Pe||Ke||P||Le||He)&&M&&(fs++,gr($e,M.getMessages(),fe));let Se=(tp=o.launcher)!=null?tp:{},It=(np=Se.headerIconHidden)!=null?np:!1,at=(rp=(op=o.layout)==null?void 0:op.header)==null?void 0:rp.showIcon,Qt=It||at===!1,dn=Se.headerIconName,Wt=(sp=Se.headerIconSize)!=null?sp:"48px";if(V){let Q=de.querySelector(".persona-border-b-persona-divider"),xt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Qt)V.style.display="none",Q&&xt&&!Q.contains(xt)&&Q.insertBefore(xt,Q.firstChild);else{if(V.style.display="",V.style.height=Wt,V.style.width=Wt,Q&&xt&&(Q.contains(V)?V.nextSibling!==xt&&(V.remove(),Q.insertBefore(V,xt)):Q.insertBefore(V,xt)),dn){let dt=parseFloat(Wt)||24,Et=ke(dn,dt*.6,"#ffffff",2);Et?V.replaceChildren(Et):V.textContent=(ap=Se.agentIconText)!=null?ap:"\u{1F4AC}"}else if(Se.iconUrl){let dt=V.querySelector("img");if(dt)dt.src=Se.iconUrl,dt.style.height=Wt,dt.style.width=Wt;else{let Et=document.createElement("img");Et.src=Se.iconUrl,Et.alt="",Et.className="persona-rounded-xl persona-object-cover",Et.style.height=Wt,Et.style.width=Wt,V.replaceChildren(Et)}}else{let dt=V.querySelector("svg"),Et=V.querySelector("img");(dt||Et)&&V.replaceChildren(),V.textContent=(ip=Se.agentIconText)!=null?ip:"\u{1F4AC}"}let Nt=V.querySelector("img");Nt&&(Nt.style.height=Wt,Nt.style.width=Wt)}}let Tn=(cp=(lp=o.layout)==null?void 0:lp.header)==null?void 0:cp.showTitle,pn=(pp=(dp=o.layout)==null?void 0:dp.header)==null?void 0:pp.showSubtitle;if(Ee&&(Ee.style.display=Tn===!1?"none":""),Fe&&(Fe.style.display=pn===!1?"none":""),je){((mp=(up=o.layout)==null?void 0:up.header)==null?void 0:mp.showCloseButton)===!1?je.style.display="none":je.style.display="";let xt=(fp=Se.closeButtonSize)!=null?fp:"32px",Nt=(gp=Se.closeButtonPlacement)!=null?gp:"inline";je.style.height=xt,je.style.width=xt;let{closeButtonWrapper:dt}=De,Et=Nt==="top-right",sn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Et!==sn)if(dt.remove(),Et)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let ut=(bp=(hp=Se.clearChat)==null?void 0:hp.placement)!=null?bp:"inline",an=(vp=(yp=Se.clearChat)==null?void 0:yp.enabled)!=null?vp:!0;dt.className=an&&ut==="inline"?"":"persona-ml-auto";let Dn=de.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(dt)}if(je.style.color=Se.closeButtonColor||Ln.actionIconColor,Se.closeButtonBackgroundColor?(je.style.backgroundColor=Se.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),Se.closeButtonBorderWidth||Se.closeButtonBorderColor){let ut=Se.closeButtonBorderWidth||"0px",an=Se.closeButtonBorderColor||"transparent";je.style.border=`${ut} solid ${an}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");Se.closeButtonBorderRadius?(je.style.borderRadius=Se.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),Se.closeButtonPaddingX?(je.style.paddingLeft=Se.closeButtonPaddingX,je.style.paddingRight=Se.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Se.closeButtonPaddingY?(je.style.paddingTop=Se.closeButtonPaddingY,je.style.paddingBottom=Se.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom="");let gn=(xp=Se.closeButtonIconName)!=null?xp:"x",vo=(wp=Se.closeButtonIconText)!=null?wp:"\xD7";je.innerHTML="";let Mn=ke(gn,"28px","currentColor",1);Mn?je.appendChild(Mn):je.textContent=vo;let Jt=(Cp=Se.closeButtonTooltipText)!=null?Cp:"Close chat",Qn=(Sp=Se.closeButtonShowTooltip)!=null?Sp:!0;if(je.setAttribute("aria-label",Jt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Qn&&Jt)){let ut=null,an=()=>{if(ut||!je)return;let Sr=je.ownerDocument,Ps=Sr.body;if(!Ps)return;ut=Mo(Sr,"div","persona-clear-chat-tooltip"),ut.textContent=Jt;let Ws=Mo(Sr,"div");Ws.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Ws);let Ar=je.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(sr),ut.style.left=`${Ar.left+Ar.width/2}px`,ut.style.top=`${Ar.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ps.appendChild(ut)},Dn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",an),dt.addEventListener("mouseleave",Dn),je.addEventListener("focus",an),je.addEventListener("blur",Dn),dt._cleanupTooltip=()=>{Dn(),dt&&(dt.removeEventListener("mouseenter",an),dt.removeEventListener("mouseleave",Dn)),je&&(je.removeEventListener("focus",an),je.removeEventListener("blur",Dn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:ct}=De;if(Ze){let Q=(Ap=Se.clearChat)!=null?Ap:{},xt=(Tp=Q.enabled)!=null?Tp:!0,Nt=(Ep=(kp=o.layout)==null?void 0:kp.header)==null?void 0:Ep.showClearChat,dt=Nt!==void 0?Nt:xt,Et=(Mp=Q.placement)!=null?Mp:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:sn}=De;!E()&&sn&&!sn.classList.contains("persona-absolute")&&(dt?sn.classList.remove("persona-ml-auto"):sn.classList.add("persona-ml-auto"));let gn=Et==="top-right",vo=ct.classList.contains("persona-absolute");if(!E()&&gn!==vo&&dt){if(ct.remove(),gn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Jt=de.querySelector(".persona-border-b-persona-divider"),Qn=De.closeButtonWrapper;Jt&&Qn&&Qn.parentElement===Jt?Jt.insertBefore(ct,Qn):Jt&&Jt.appendChild(ct)}let Mn=De.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(gn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(dt){if(!E()){let ut=(Lp=Q.size)!=null?Lp:"32px";Ze.style.height=ut,Ze.style.width=ut}let sn=(Ip=Q.iconName)!=null?Ip:"refresh-cw",gn=(Rp=Q.iconColor)!=null?Rp:"";Ze.style.color=gn||Ln.actionIconColor,Ze.innerHTML="";let vo=E()?"14px":"20px",Mn=ke(sn,vo,"currentColor",2);if(Mn&&Ze.appendChild(Mn),Q.backgroundColor?(Ze.style.backgroundColor=Q.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ut=Q.borderWidth||"0px",an=Q.borderColor||"transparent";Ze.style.border=`${ut} solid ${an}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");Q.borderRadius?(Ze.style.borderRadius=Q.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),Q.paddingX?(Ze.style.paddingLeft=Q.paddingX,Ze.style.paddingRight=Q.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),Q.paddingY?(Ze.style.paddingTop=Q.paddingY,Ze.style.paddingBottom=Q.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let Jt=(Pp=Q.tooltipText)!=null?Pp:"Clear chat",Qn=(Wp=Q.showTooltip)!=null?Wp:!0;if(Ze.setAttribute("aria-label",Jt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Qn&&Jt)){let ut=null,an=()=>{if(ut||!Ze)return;let Sr=Ze.ownerDocument,Ps=Sr.body;if(!Ps)return;ut=Mo(Sr,"div","persona-clear-chat-tooltip"),ut.textContent=Jt;let Ws=Mo(Sr,"div");Ws.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Ws);let Ar=Ze.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(sr),ut.style.left=`${Ar.left+Ar.width/2}px`,ut.style.top=`${Ar.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ps.appendChild(ut)},Dn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};ct.addEventListener("mouseenter",an),ct.addEventListener("mouseleave",Dn),Ze.addEventListener("focus",an),Ze.addEventListener("blur",Dn),ct._cleanupTooltip=()=>{Dn(),ct&&(ct.removeEventListener("mouseenter",an),ct.removeEventListener("mouseleave",Dn)),Ze&&(Ze.removeEventListener("focus",an),Ze.removeEventListener("blur",Dn))}}}}let kn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[lc],fn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[va.message,va.messageAndClick];L=cc({parsers:kn,handlers:fn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),fe=ff(o,L,K),M.updateConfig(o),gr($e,M.getMessages(),fe),mo.render(o.suggestionChips,M,ue,void 0,o.suggestionChipsConfig),Cs(),Vr(M.isStreaming());let yr=((Bp=o.voiceRecognition)==null?void 0:Bp.enabled)===!0,vr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),xr=((Dp=(Hp=o.voiceRecognition)==null?void 0:Hp.provider)==null?void 0:Dp.type)==="runtype";if(yr&&(vr||xr))if(!j||!Vt){let Q=qa(o.voiceRecognition,o.sendButton);Q&&(j=Q.micButton,Vt=Q.micButtonWrapper,Tt.insertBefore(Vt,In),j.addEventListener("click",G),j.disabled=M.isStreaming())}else{let Q=(Fp=o.voiceRecognition)!=null?Fp:{},xt=(Op=o.sendButton)!=null?Op:{},Nt=(Np=Q.iconName)!=null?Np:"mic",dt=(_p=xt.size)!=null?_p:"40px",Et=(Vp=Q.iconSize)!=null?Vp:dt,sn=parseFloat(Et)||24;j.style.width=Et,j.style.height=Et,j.style.minWidth=Et,j.style.minHeight=Et;let gn=(Up=($p=Q.iconColor)!=null?$p:xt.textColor)!=null?Up:"currentColor";j.innerHTML="";let vo=ke(Nt,sn,gn,2);vo?j.appendChild(vo):j.textContent="\u{1F3A4}";let Mn=(zp=Q.backgroundColor)!=null?zp:xt.backgroundColor;Mn?j.style.backgroundColor=Mn:j.style.backgroundColor="",gn?j.style.color=gn:j.style.color="var(--persona-text, #111827)",Q.borderWidth?(j.style.borderWidth=Q.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),Q.borderColor?j.style.borderColor=Q.borderColor:j.style.borderColor="",Q.paddingX?(j.style.paddingLeft=Q.paddingX,j.style.paddingRight=Q.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),Q.paddingY?(j.style.paddingTop=Q.paddingY,j.style.paddingBottom=Q.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Jt=Vt==null?void 0:Vt.querySelector(".persona-send-button-tooltip"),Qn=(qp=Q.tooltipText)!=null?qp:"Start voice recognition";if(((jp=Q.showTooltip)!=null?jp:!1)&&Qn)if(Jt)Jt.textContent=Qn,Jt.style.display="";else{let an=document.createElement("div");an.className="persona-send-button-tooltip",an.textContent=Qn,Vt==null||Vt.insertBefore(an,j)}else Jt&&(Jt.style.display="none");Vt.style.display="",j.disabled=M.isStreaming()}else j&&Vt&&(Vt.style.display="none",((Gp=(Kp=o.voiceRecognition)==null?void 0:Kp.provider)==null?void 0:Gp.type)==="runtype"?M.isVoiceActive()&&M.toggleVoice():Yn&&yo());if(((Yp=o.attachments)==null?void 0:Yp.enabled)===!0)if(!Ot||!Je){let Q=(Xp=o.attachments)!=null?Xp:{},Nt=(Jp=((Qp=o.sendButton)!=null?Qp:{}).size)!=null?Jp:"40px";he||(he=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",_t.insertBefore(he,ue)),re||(re=document.createElement("input"),re.type="file",re.accept=((Zp=Q.allowedTypes)!=null?Zp:$o).join(","),re.multiple=((eu=Q.maxFiles)!=null?eu:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),_t.insertBefore(re,ue)),Ot=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",(tu=Q.buttonTooltipText)!=null?tu:"Attach file");let dt=(nu=Q.buttonIconName)!=null?nu:"paperclip",Et=Nt,sn=parseFloat(Et)||40,gn=Math.round(sn*.6);Je.style.width=Et,Je.style.height=Et,Je.style.minWidth=Et,Je.style.minHeight=Et,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 vo=ke(dt,gn,"currentColor",1.5);vo?Je.appendChild(vo):Je.textContent="\u{1F4CE}",Je.addEventListener("click",Qn=>{Qn.preventDefault(),re==null||re.click()}),Ot.appendChild(Je);let Mn=(ou=Q.buttonTooltipText)!=null?ou:"Attach file",Jt=b("div","persona-send-button-tooltip");Jt.textContent=Mn,Ot.appendChild(Jt),rt.append(Ot),!tt&&re&&he&&(tt=oa.fromConfig(Q),tt.setPreviewsContainer(he),re.addEventListener("change",async()=>{tt&&(re!=null&&re.files)&&(await tt.handleFileSelect(re.files),re.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(gf(Q.dropOverlay))}else{Ot.style.display="";let Q=(ru=o.attachments)!=null?ru:{};re&&(re.accept=((su=Q.allowedTypes)!=null?su:$o).join(","),re.multiple=((au=Q.maxFiles)!=null?au:4)>1),tt&&tt.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ot&&(Ot.style.display="none"),tt&&tt.clearAttachments(),(iu=de.querySelector(".persona-attachment-drop-overlay"))==null||iu.remove();let jt=(lu=o.sendButton)!=null?lu:{},wr=(cu=jt.useIcon)!=null?cu:!1,or=(du=jt.iconText)!=null?du:"\u2191",bt=jt.iconName,Wn=(pu=jt.tooltipText)!=null?pu:"Send message",_o=(uu=jt.showTooltip)!=null?uu:!1,En=(mu=jt.size)!=null?mu:"40px",Bn=jt.backgroundColor,Dt=jt.textColor;if(wr){if(ie.style.width=En,ie.style.height=En,ie.style.minWidth=En,ie.style.minHeight=En,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.innerHTML="",Dt?ie.style.color=Dt:ie.style.color="var(--persona-button-primary-fg, #ffffff)",bt){let Q=parseFloat(En)||24,xt=(Dt==null?void 0:Dt.trim())||"currentColor",Nt=ke(bt,Q,xt,2);Nt?ie.appendChild(Nt):ie.textContent=or}else ie.textContent=or;ie.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Bn?(ie.style.backgroundColor=Bn,ie.classList.remove("persona-bg-persona-primary")):(ie.style.backgroundColor="",ie.classList.add("persona-bg-persona-primary"))}else ie.textContent=(gu=(fu=o.copy)==null?void 0:fu.sendButtonLabel)!=null?gu:"Send",ie.style.width="",ie.style.height="",ie.style.minWidth="",ie.style.minHeight="",ie.style.fontSize="",ie.style.lineHeight="",ie.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Bn?(ie.style.backgroundColor=Bn,ie.classList.remove("persona-bg-persona-accent")):ie.classList.add("persona-bg-persona-accent"),Dt?ie.style.color=Dt:ie.classList.add("persona-text-white");jt.borderWidth?(ie.style.borderWidth=jt.borderWidth,ie.style.borderStyle="solid"):(ie.style.borderWidth="",ie.style.borderStyle=""),jt.borderColor?ie.style.borderColor=jt.borderColor:ie.style.borderColor="",jt.paddingX?(ie.style.paddingLeft=jt.paddingX,ie.style.paddingRight=jt.paddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),jt.paddingY?(ie.style.paddingTop=jt.paddingY,ie.style.paddingBottom=jt.paddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let zt=In==null?void 0:In.querySelector(".persona-send-button-tooltip");if(_o&&Wn)if(zt)zt.textContent=Wn,zt.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Wn,In==null||In.insertBefore(Q,ie)}else zt&&(zt.style.display="none");let Ft=(xu=(hu=o.layout)==null?void 0:hu.contentMaxWidth)!=null?xu:E()?(vu=(yu=(bu=o.launcher)==null?void 0:bu.composerBar)==null?void 0:yu.contentMaxWidth)!=null?vu:"720px":void 0;Ft?($e.style.maxWidth=Ft,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",_t&&(_t.style.maxWidth=Ft,_t.style.marginLeft="auto",_t.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=Ft,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",_t&&(_t.style.maxWidth="",_t.style.marginLeft="",_t.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let Kt=(wu=o.statusIndicator)!=null?wu:{},Hn=(Cu=Kt.visible)!=null?Cu:!0;if(cn.style.display=Hn?"":"none",M){let Q=M.getStatus();ot(cn,(Nt=>{var dt,Et,sn,gn;return Nt==="idle"?(dt=Kt.idleText)!=null?dt:hn.idle:Nt==="connecting"?(Et=Kt.connectingText)!=null?Et:hn.connecting:Nt==="connected"?(sn=Kt.connectedText)!=null?sn:hn.connected:Nt==="error"?(gn=Kt.errorText)!=null?gn:hn.error:hn[Nt]})(Q),Kt,Q)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Xn=Kt.align==="left"?"persona-text-left":Kt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Xn)},open(){C()&&Ht(!0,"api")},close(){C()&&Ht(!1,"api")},toggle(){C()&&Ht(!k,"api")},clearChat(){wn=!1,M.clearMessages(),fo.clear(),Yo();try{localStorage.removeItem(cs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==cs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},L.syncFromMetadata(),X==null||X.clear(),we==null||we.reset(),Ae==null||Ae.update()},setMessage(c){return!ue||M.isStreaming()?!1:(!k&&C()&&Ht(!0,"system"),ue.value=c,ue.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(M.isStreaming())return!1;let f=(c==null?void 0:c.trim())||ue.value.trim();return f?(!k&&C()&&Ht(!0,"system"),ue.value="",ue.style.height="auto",M.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return M.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(M.isVoiceActive()||(!k&&C()&&Ht(!0,"system"),ft.manuallyDeactivated=!1,Pn(),M.toggleVoice().then(()=>{ft.active=M.isVoiceActive(),so("user"),M.isVoiceActive()&&z()})),!0):Yn?!0:Ls()?(!k&&C()&&Ht(!0,"system"),ft.manuallyDeactivated=!1,Pn(),br("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?M.isVoiceActive()?(M.toggleVoice().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Pn(),so("user"),te()}),!0):!1:Yn?(ft.manuallyDeactivated=!0,Pn(),yo("user"),!0):!1},injectMessage(c){return!k&&C()&&Ht(!0,"system"),M.injectMessage(c)},injectAssistantMessage(c){!k&&C()&&Ht(!0,"system");let f=M.injectAssistantMessage(c);return O&&(O=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)),f},injectUserMessage(c){return!k&&C()&&Ht(!0,"system"),M.injectUserMessage(c)},injectSystemMessage(c){return!k&&C()&&Ht(!0,"system"),M.injectSystemMessage(c)},injectMessageBatch(c){return!k&&C()&&Ht(!0,"system"),M.injectMessageBatch(c)},injectComponentDirective(c){return!k&&C()&&Ht(!0,"system"),M.injectComponentDirective(c)},injectTestMessage(c){!k&&C()&&Ht(!0,"system"),M.injectTestEvent(c)},async connectStream(c,f){return M.connectStream(c,f)},__pushEventStreamEvent(c){X&&(we==null||we.processEvent(c.type,c.payload),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!le||!X||xn()},hideEventStream(){pe&&Nn()},isEventStreamVisible(){return pe},showArtifacts(){po(o)&&(wn=!1,qn(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){po(o)&&(wn=!0,qn())},upsertArtifact(c){return po(o)?(wn=!1,M.upsertArtifact(c)):null},selectArtifact(c){po(o)&&M.selectArtifact(c)},clearArtifacts(){po(o)&&M.clearArtifacts()},getArtifacts(){var c;return(c=M==null?void 0:M.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=M==null?void 0:M.getSelectedArtifactId())!=null?c:null},focusInput(){return R&&!k&&!E()||!ue?!1:(ue.focus(),!0)},async resolveApproval(c,f){let y=M.getMessages().find(W=>{var _;return W.variant==="approval"&&((_=W.approval)==null?void 0:_.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){M.resolveWebMcpApproval(y.id,f);return}return M.resolveApproval(y.approval,f)},getMessages(){return M.getMessages()},getStatus(){return M.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()&&k},isVoiceActive(){return ft.active},getState(){return{open:C()&&k,launcherEnabled:R,voiceActive:ft.active,streaming:M.isStreaming()}},showCSATFeedback(c){!k&&C()&&Ht(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let h=pf({onSubmit:async(y,W)=>{var _;M.isClientTokenMode()&&await M.submitCSATFeedback(y,W),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,W)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!k&&C()&&Ht(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let h=uf({onSubmit:async(y,W)=>{var _;M.isClientTokenMode()&&await M.submitNPSFeedback(y,W),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,W)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return M.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return M.submitNPSFeedback(c,f)},destroy(){ko!=null&&(clearInterval(ko),ko=null),gt.forEach(c=>c()),ve.remove(),ze==null||ze.remove(),Re==null||Re.destroy(),Xe==null||Xe.remove(),Kn&&je.removeEventListener("click",Kn)}};if((((wd=n==null?void 0:n.debugTools)!=null?wd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:h=>h?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=f,gt.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",f),gt.push(()=>{window.removeEventListener("persona:focusInput",f)}),le){let q=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&en.showEventStream()},N=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",N),gt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",N)})}let h=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&en.showArtifacts()},y=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&en.hideArtifacts()},W=q=>{let N=q.detail;N!=null&&N.instanceId&&N.instanceId!==c||N!=null&&N.artifact&&en.upsertArtifact(N.artifact)},_=q=>{let N=q.detail;N!=null&&N.instanceId&&N.instanceId!==c||typeof(N==null?void 0:N.id)=="string"&&en.selectArtifact(N.id)},$=q=>{let N=q.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",_),window.addEventListener("persona:clearArtifacts",$),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",_),window.removeEventListener("persona:clearArtifacts",$)})}let io=uy(o.persistState);if(io&&C()){let c=my(io.storage),f=`${io.keyPrefix}widget-open`,h=`${io.keyPrefix}widget-voice`,y=`${io.keyPrefix}widget-voice-mode`;if(c){let W=((Cd=io.persist)==null?void 0:Cd.openState)&&c.getItem(f)==="true",_=((Sd=io.persist)==null?void 0:Sd.voiceState)&&c.getItem(h)==="true",$=((Ad=io.persist)==null?void 0:Ad.voiceState)&&c.getItem(y)==="true";if(W&&setTimeout(()=>{en.open(),setTimeout(()=>{var q;if(_||$)en.startVoiceRecognition();else if((q=io.persist)!=null&&q.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(Td=io.persist)!=null&&Td.openState&&(s.on("widget:opened",()=>{c.setItem(f,"true")}),s.on("widget:closed",()=>{c.setItem(f,"false")})),(kd=io.persist)!=null&&kd.voiceState&&(s.on("voice:state",q=>{c.setItem(h,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),io.clearOnChatClear){let q=()=>{c.removeItem(f),c.removeItem(h),c.removeItem(y)},N=()=>q();window.addEventListener("persona:clear-chat",N),gt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return m&&C()&&setTimeout(()=>{en.open()},0),Oo(),en};var fy=(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},bf=(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"},gc=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=""},yf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",gc(e)},uc=e=>{e.style.transition=""},mc=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=""},fc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ji=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},gy=(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))},hy=(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)},vf=(e,t,n,o,r,s,a)=>{var w,S,L,R,I,D;let i=Lo(s),d=i.reveal==="push";gy(e,t,n,o,d),hy(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=(R=(L=s==null?void 0:s.launcher)==null?void 0:L.mobileBreakpoint)!=null?R:640,g=l!=null?l.innerWidth<=u:!1;if(m&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),mc(t),uc(o),yf(o),fc(n),Ji(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((D=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?D:bn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),yf(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",mc(t),uc(o),fc(n),Ji(r,o);let F=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=F,o.style.transform=v,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",uc(o),gc(o),Ji(r,o);let F=fy(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${F}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${F}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+F}px`,t.style.transition=v,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",mc(t),gc(o),fc(n),Ji(r,o);let F=i.reveal==="emerge";F?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=F||x?"hidden":"visible",o.style.transition=v,F&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},by=(e,t)=>{let n=e.ownerDocument.createElement("div");return bf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){bf(n,o)},destroy(){n.remove()}}},yy=(e,t)=>{var I,D,F,B;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),m=n.createElement("div"),u=(D=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||D?(B=(F=t==null?void 0:t.launcher)==null?void 0:F.autoExpand)!=null?B:!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(),Lo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{vf(a,i,d,l,m,t,u)}),g.observe(a))},S=()=>{vf(a,i,d,l,m,t,u),w()},L=a.ownerDocument.defaultView,R=()=>{S()};return L==null||L.addEventListener("resize",R),Lo(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,E;t=v,((E=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?E:!0)===!1&&(u=!0),S()},destroy(){L==null||L.removeEventListener("resize",R),p(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},xf=(e,t)=>un(t)?yy(e,t):by(e,t);var Hr={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Zi=.15,el=1.5,xa="persona-preview-shell-theme",hc={load:()=>null,save:()=>{},clear:()=>{}},bc=["How do I get started?","Pricing & plans","Talk to support"];function wa(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function yc(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 tl(e){let t=yc(e);return`* { box-sizing: border-box; }
107
+ `}if(!y&&!c){let ft="max-height: -moz-available !important; max-height: stretch !important;",lt=g?"":"padding-top: 1.25em !important;",Et=g?"":`z-index: ${(dn=(fn=o.launcher)==null?void 0:fn.zIndex)!=null?dn:Cn} !important;`;Te.style.cssText+=ft+lt+Et}Je()};yo(),es(e,o),Zi(e,o),el(e,o);let vt=[];vt.push(()=>{document.removeEventListener("keydown",Go)});let Xt=null,Qt=null;vt.push(()=>{Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null}),Vn&&vt.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),vt.push(()=>{En==null||En(),En=null,Oo(),Ft&&(Ft.remove(),Ft=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),Ee&&vt.push(()=>{Se!==null&&(cancelAnimationFrame(Se),Se=null),ce==null||ce.destroy(),ce=null,G==null||G.destroy(),G=null,K=null});let jn=null,Qo=()=>{jn&&(jn(),jn=null),o.colorScheme==="auto"&&(jn=Ou(()=>{es(e,o)}))};Qo(),vt.push(()=>{jn&&(jn(),jn=null)});let ao=(xd=o.features)==null?void 0:xd.streamAnimation;if(ao!=null&&ao.type&&ao.type!=="none"){let c=ma(ao.type,ao.plugins);c&&(zl(c,e),vt.push(()=>Im(e)))}let vo=ng(Ht),Kn=null,$,io=!1,xe=Am(),Gn=new Map,lo=new Map,xo=new Map,xs=0,wo=Ii(),Co=0,So=null,No=!1,hr=!1,Da=4,ws=24,Fa=80,Ur=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Cs=(Cd=(wd=o.voiceRecognition)==null?void 0:wd.autoResume)!=null?Cd:!1,co=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},Bn=()=>{u(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Oa=()=>{var y,L;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=hc(d.voiceState),g=!!c.active,h=Number((L=c.timestamp)!=null?L:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-h<Sy&&setTimeout(()=>{var O,N;yt.active||(yt.manuallyDeactivated=!1,((N=(O=o.voiceRecognition)==null?void 0:O.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),co("restore"),$.isVoiceActive()&&P()}):xr("restore"))},1e3)},Na=()=>$?Tg($.getMessages()).filter(c=>!c.__skipPersist):[];function zr(c){if(!(i!=null&&i.save))return;let h={messages:c?Tg(c):$?Na():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let _o=null,_a=()=>Te.querySelector("#persona-scroll-container")||Q,br=()=>{_o!==null&&(cancelAnimationFrame(_o),_o=null),No=!1},Ss=()=>{So!==null&&(cancelAnimationFrame(So),So=null),hr=!1,br()},Vo=()=>{if(!An()||ne){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==me&&me.appendChild(Wt),St();let c=da(Q)>0;Wt.style.display=wo.isFollowing()||!c?"none":""},As=()=>{wo.pause()&&(Ss(),Vo())},Jo=()=>{wo.resume(),Vo()},Zo=(c=!1)=>{wo.isFollowing()&&(!c&&!io||(So!==null&&(cancelAnimationFrame(So),So=null),hr=!0,So=requestAnimationFrame(()=>{So=null,hr=!1,wo.isFollowing()&&Va(_a(),c?220:140)})))},Va=(c,g=500)=>{let h=c.scrollTop,y=da(c),L=y-h;if(Math.abs(L)<1){Co=c.scrollTop;return}if(Math.abs(L)>=Fa){br(),No=!0,c.scrollTop=y,Co=c.scrollTop,No=!1;return}br();let O=performance.now();No=!0;let N=F=>1-Math.pow(1-F,3),q=F=>{if(!wo.isFollowing()){br();return}let ke=da(c);ke!==y&&(y=ke,L=y-h);let ge=F-O,ee=Math.min(ge/g,1),Ae=N(ee),Ie=h+L*Ae;c.scrollTop=Ie,Co=c.scrollTop,ee<1?_o=requestAnimationFrame(q):(c.scrollTop=y,Co=c.scrollTop,_o=null,No=!1)};_o=requestAnimationFrame(q)},$a=c=>{let g=new Map;c.forEach(h=>{let y=Ur.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}))}),Ur.clear(),g.forEach((h,y)=>{Ur.set(y,h)})},yr=(c,g,h)=>{var pt,We,Pe,je,Je,xt;let y=document.createElement("div"),O=(()=>{var Fe;let H=r.find(oe=>oe.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Fe=o.loadingIndicator)!=null&&Fe.render)return o.loadingIndicator.render})(),N=(H,Fe)=>Fe==null?!1:typeof Fe=="string"?(H.textContent=Fe,!0):(H.appendChild(Fe),!0),q=new Set,F=new Set,ke=r.some(H=>H.renderAskUserQuestion),ge=[],ee=[],Ae=o.enableComponentStreaming!==!1,Ie=r.some(H=>H.renderApproval)&&o.approval!==!1,$e=[];if(g.forEach(H=>{var Ct,Qn,rn,mo,Jn,wr,Qr,Jr,Yt,Cr,sr,ar,zo,Sr;q.add(H.id);let Fe=ke&&Hr(H),oe=Ie&&H.variant==="approval"&&!!H.approval,tt=!Fe&&H.role==="assistant"&&!H.variant&&Ae&&wg(H);if(!oe&&xo.has(H.id)){let nt=c.querySelector(`#wrapper-${H.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),xo.delete(H.id)}if(!tt&&lo.has(H.id)){let nt=c.querySelector(`#wrapper-${H.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),lo.delete(H.id)}let _t=Hr(H)?`:${(Ct=H.agentMetadata)!=null&&Ct.askUserQuestionAnswered?"a":"u"}:${(Qn=H.agentMetadata)!=null&&Qn.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt=Sm(H,xs)+_t,qt=Fe||oe||tt?null:Tm(xe,H.id,Nt);if(qt){y.appendChild(qt.cloneNode(!0)),Hr(H)&&((rn=H.toolCall)!=null&&rn.id)&&((mo=H.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((Jn=H.agentMetadata)!=null&&Jn.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Gi(H,o,Be.composerOverlay));return}let it=null,cn=r.find(nt=>!!(H.variant==="reasoning"&&nt.renderReasoning||H.variant==="tool"&&nt.renderToolCall||!H.variant&&nt.renderMessage)),Xn=(wr=o.layout)==null?void 0:wr.messages;if(Hr(H)&&((Qr=H.agentMetadata)==null?void 0:Qr.askUserQuestionAnswered)===!0){Gn.delete(H.id);let nt=c.querySelector(`#wrapper-${H.id}`);nt==null||nt.removeAttribute("data-preserve-runtime");return}if(Hr(H)&&((Yt=(Jr=o.features)==null?void 0:Jr.askUserQuestion)==null?void 0:Yt.enabled)!==!1){let nt=r.find(vn=>typeof vn.renderAskUserQuestion=="function");if(nt&&Lt.current){let vn=Gn.get(H.id),fn=vn!==Nt,dn=null;if(fn){let{payload:Et,complete:Hn}=ps(H),en=H.id,Po=()=>{var sn;return(sn=Lt.current)==null?void 0:sn.getMessages().find(Ln=>Ln.id===en)};dn=nt.renderAskUserQuestion({message:H,payload:Et,complete:Hn,resolve:sn=>{var go;let Ln=Po();Ln&&((go=Lt.current)==null||go.resolveAskUserQuestion(Ln,sn))},dismiss:()=>{var Ln,go,Ar;let sn=Po();(Ln=sn==null?void 0:sn.agentMetadata)!=null&&Ln.awaitingLocalTool&&((go=Lt.current)==null||go.markAskUserQuestionResolved(sn),(Ar=Lt.current)==null||Ar.resolveAskUserQuestion(sn,"(dismissed)"))},config:o})}let ft=vn!=null;if(fn&&dn===null&&!ft){((Cr=H.agentMetadata)==null?void 0:Cr.awaitingLocalTool)===!0&&!((sr=H.agentMetadata)!=null&&sr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Gi(H,o,Be.composerOverlay));return}let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${H.id}`,lt.setAttribute("data-wrapper-id",H.id),lt.setAttribute("data-ask-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),y.appendChild(lt),ge.push({messageId:H.id,fingerprint:Nt,bubble:dn});return}else{((ar=H.agentMetadata)==null?void 0:ar.awaitingLocalTool)===!0&&!((zo=H.agentMetadata)!=null&&zo.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Gi(H,o,Be.composerOverlay));return}}else if(oe){let nt=r.find(ft=>typeof ft.renderApproval=="function"),fn=xo.get(H.id)!==Nt,dn=null;if(fn&&(nt!=null&&nt.renderApproval)){let ft=H.id,lt=(Et,Hn)=>{var Po,sn,Ln;let en=(Po=Lt.current)==null?void 0:Po.getMessages().find(go=>go.id===ft);en!=null&&en.approval&&(en.approval.toolType==="webmcp"?(sn=Lt.current)==null||sn.resolveWebMcpApproval(en.id,Et):(Ln=Lt.current)==null||Ln.resolveApproval(en.approval,Et,Hn))};dn=nt.renderApproval({message:H,defaultRenderer:()=>Qi(H,o),config:o,approve:Et=>lt("approved",Et),deny:Et=>lt("denied",Et)})}if(fn&&dn===null){let ft=c.querySelector(`#wrapper-${H.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),xo.delete(H.id),it=Qi(H,o)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${H.id}`,ft.setAttribute("data-wrapper-id",H.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),$e.push({messageId:H.id,fingerprint:Nt,bubble:dn});return}}else if(cn)if(H.variant==="reasoning"&&H.reasoning&&cn.renderReasoning){if(!fe)return;it=cn.renderReasoning({message:H,defaultRenderer:()=>Ql(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&cn.renderToolCall){if(!ae)return;it=cn.renderToolCall({message:H,defaultRenderer:()=>Jl(H,o),config:o})}else cn.renderMessage&&(it=cn.renderMessage({message:H,defaultRenderer:()=>{let nt=Xl(H,h,Xn,o.messageActions,te,{loadingIndicatorRenderer:O,widgetConfig:o});return H.role!=="user"&&cc(nt,H,o,$),nt},config:o}));if(!it&&tt){let nt=Cg(H);if(nt){let vn=lo.get(H.id),fn=vn!==Nt,dn=o.wrapComponentDirectiveInBubble!==!1,ft=null;if(fn){let lt=vg(nt,{config:o,message:H,transform:h});if(lt)if(dn){let Et=document.createElement("div");if(Et.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(" "),Et.id=`bubble-${H.id}`,Et.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Hn=document.createElement("div");Hn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Hn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Et.appendChild(Hn)}Et.appendChild(lt),ft=Et}else{let Et=document.createElement("div");if(Et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Et.id=`bubble-${H.id}`,Et.setAttribute("data-message-id",H.id),Et.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Hn=document.createElement("div");Hn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Hn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Et.appendChild(Hn)}Et.appendChild(lt),ft=Et}}if(ft||vn!=null){let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${H.id}`,lt.setAttribute("data-wrapper-id",H.id),lt.setAttribute("data-component-directive-stub","true"),lt.setAttribute("data-preserve-runtime","true"),dn||lt.classList.add("persona-w-full"),y.appendChild(lt),ee.push({messageId:H.id,fingerprint:Nt,bubble:ft});return}}}if(!it)if(H.variant==="reasoning"&&H.reasoning){if(!fe)return;it=Ql(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!ae)return;it=Jl(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;it=Qi(H,o)}else{let nt=(Sr=o.layout)==null?void 0:Sr.messages;nt!=null&&nt.renderUserMessage&&H.role==="user"?it=nt.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):nt!=null&&nt.renderAssistantMessage&&H.role==="assistant"?it=nt.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):it=Xl(H,h,nt,o.messageActions,te,{loadingIndicatorRenderer:O,widgetConfig:o}),H.role!=="user"&&it&&cc(it,H,o,$)}let Ge=document.createElement("div");Ge.className="persona-flex",Ge.id=`wrapper-${H.id}`,Ge.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Ge.classList.add("persona-justify-end"),(it==null?void 0:it.getAttribute("data-persona-component-directive"))==="true"&&Ge.classList.add("persona-w-full"),Ge.appendChild(it),km(xe,H.id,Nt,Ge),y.appendChild(Ge)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let oe=Fe.getAttribute("data-persona-ask-sheet-for");oe&&!F.has(oe)&&ms(Be.composerOverlay,oe)}),(We=(pt=o.features)==null?void 0:pt.toolCallDisplay)!=null&&We.grouped){let H=[],Fe=[];g.forEach(oe=>{if(oe.variant==="tool"&&oe.toolCall&&ae){Fe.push(oe);return}Fe.length>1&&H.push(Fe),Fe=[]}),Fe.length>1&&H.push(Fe),H.forEach((oe,tt)=>{var Ct,Qn;let _t=oe.map(rn=>Array.from(y.children).find(mo=>mo instanceof HTMLElement&&mo.getAttribute("data-wrapper-id")===rn.id)).filter(rn=>!!rn);if(_t.length<2)return;let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id=`wrapper-tool-group-${tt}-${oe[0].id}`,Nt.setAttribute("data-wrapper-id",`tool-group-${tt}-${oe[0].id}`);let qt=document.createElement("div");qt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",qt.setAttribute("data-persona-tool-group","true");let it=document.createElement("div");it.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${oe.length} tools`,Xn=(Qn=(Ct=o.toolCall)==null?void 0:Ct.renderGroupedSummary)==null?void 0:Qn.call(Ct,{messages:oe,toolCalls:oe.map(rn=>rn.toolCall).filter(rn=>!!rn),defaultSummary:cn,config:o});N(it,Xn)||(it.textContent=cn);let Ge=document.createElement("div");Ge.className="persona-tool-group-stack persona-flex persona-flex-col",qt.append(it,Ge),Nt.appendChild(qt),_t[0].before(Nt),_t.forEach((rn,mo)=>{let Jn=document.createElement("div");Jn.className="persona-tool-group-item persona-relative",Jn.setAttribute("data-persona-tool-group-item","true"),mo<_t.length-1&&Jn.setAttribute("data-persona-tool-group-connector","true"),Jn.appendChild(rn),Ge.appendChild(Jn)})})}Em(xe,q);let rt=g.some(H=>H.role==="assistant"&&H.streaming),Ke=g[g.length-1],gt=(Ke==null?void 0:Ke.role)==="assistant"&&!Ke.streaming&&Ke.variant!=="approval";if(io&&g.some(H=>H.role==="user")&&!rt&&!gt){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:xa},Fe=r.find(tt=>tt.renderLoadingIndicator),oe=null;if(Fe!=null&&Fe.renderLoadingIndicator&&(oe=Fe.renderLoadingIndicator(H)),oe===null&&((Pe=o.loadingIndicator)!=null&&Pe.render)&&(oe=o.loadingIndicator.render(H)),oe===null&&(oe=xa()),oe){let tt=document.createElement("div"),_t=((je=o.loadingIndicator)==null?void 0:je.showBubble)!==!1;tt.className=_t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),tt.setAttribute("data-typing-indicator","true"),tt.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",tt.appendChild(oe);let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id="wrapper-typing-indicator",Nt.setAttribute("data-wrapper-id","typing-indicator"),Nt.appendChild(tt),y.appendChild(Nt)}}if(!io&&g.length>0){let H=g[g.length-1],Fe={config:o,lastMessage:H,messageCount:g.length},oe=r.find(_t=>_t.renderIdleIndicator),tt=null;if(oe!=null&&oe.renderIdleIndicator&&(tt=oe.renderIdleIndicator(Fe)),tt===null&&((Je=o.loadingIndicator)!=null&&Je.renderIdle)&&(tt=o.loadingIndicator.renderIdle(Fe)),tt){let _t=document.createElement("div"),Nt=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;_t.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-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_t.setAttribute("data-idle-indicator","true"),_t.appendChild(tt);let qt=document.createElement("div");qt.className="persona-flex",qt.id="wrapper-idle-indicator",qt.setAttribute("data-wrapper-id","idle-indicator"),qt.appendChild(_t),y.appendChild(qt)}}if(Mi(c,y),ge.length>0)for(let{messageId:H,fingerprint:Fe,bubble:oe}of ge){let tt=c.querySelector(`#wrapper-${H}`);tt&&oe!==null&&(tt.replaceChildren(oe),tt.setAttribute("data-bubble-fp",Fe),Gn.set(H,Fe))}if(Gn.size>0)for(let H of Gn.keys())q.has(H)||Gn.delete(H);if(ee.length>0)for(let{messageId:H,fingerprint:Fe,bubble:oe}of ee){let tt=c.querySelector(`#wrapper-${H}`);tt&&oe!==null&&(tt.replaceChildren(oe),tt.setAttribute("data-bubble-fp",Fe),lo.set(H,Fe))}if(lo.size>0)for(let H of lo.keys())q.has(H)||lo.delete(H);if($e.length>0)for(let{messageId:H,fingerprint:Fe,bubble:oe}of $e){let tt=c.querySelector(`#wrapper-${H}`);tt&&oe!==null&&(tt.replaceChildren(oe),tt.setAttribute("data-bubble-fp",Fe),xo.set(H,Fe))}if(xo.size>0)for(let H of xo.keys())q.has(H)||xo.delete(H)},er=null,Ua=()=>{var h;if(er)return;let c=y=>{let L=y.composedPath();L.includes(Te)||Ue&&L.includes(Ue)||Ot(!1,"user")};er=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Ts=()=>{var g;if(!er)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",er,!0),er=null};vt.push(()=>Ts());let tr=null,za=()=>{var h;if(tr)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ot(!1,"user"))};tr=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ks=()=>{var g;if(!tr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",tr,!0),tr=null};vt.push(()=>ks());let nr=!1,Es=new Set,qa=()=>{var g,h,y,L;let c=(y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((L=o.features)==null?void 0:L.streamAnimation)},$o=()=>{var gt,pt,We,Pe;if(!E())return;let c=Be.peekBanner,g=Be.peekTextNode;if(!c||!g)return;if(T){c.classList.remove("persona-pill-peek--visible");return}let h=(gt=$==null?void 0:$.getMessages())!=null?gt:[],y;for(let je=h.length-1;je>=0;je--){let Je=h[je];if(Je.role==="assistant"&&Je.content){y=Je;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let L=y.content,O=!!y.streaming,N=qa(),q=Wi(N),F=q.type!=="none"?ma(q.type,N==null?void 0:N.plugins):null,ke=((pt=F==null?void 0:F.isAnimating)==null?void 0:pt.call(F,y))===!0,ge=F!==null&&(O||ke);ge&&F&&!Es.has(F.name)&&(zl(F,e),Es.add(F.name));let ee=ge&&(F!=null&&F.containerClass)?F.containerClass:null,Ae=(We=g.dataset.personaPeekStreamClass)!=null?We:null;Ae&&Ae!==ee&&(g.classList.remove(Ae),delete g.dataset.personaPeekStreamClass),ee&&Ae!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),ge?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ie=ge?Bi(L,q.buffer,F,y,O):L;if(ge&&q.placeholder==="skeleton"&&O&&(!Ie||!Ie.trim())){let je=document.createElement("div"),Je=fa();Je.classList.add("persona-pill-peek__skeleton"),je.appendChild(Je),Mi(g,je)}else{let je=Math.max(0,Ie.length-100),Je=Ie.length>100?Ie.slice(-100):Ie,xt=ta(Je);if(!ge||!F){let H=Ie.length>100?`\u2026${Je}`:Je;g.textContent!==H&&(g.textContent=H)}else{let H=xt;(F.wrap==="char"||F.wrap==="word")&&(H=ga(xt,F.wrap,`peek-${y.id}`,{skipTags:F.skipTags,startIndex:je}));let Fe=document.createElement("div");if(Fe.innerHTML=H,F.useCaret&&Je.length>0){let oe=Hi(),tt=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),_t=tt[tt.length-1];_t!=null&&_t.parentNode?_t.parentNode.insertBefore(oe,_t.nextSibling):Fe.appendChild(oe)}Mi(g,Fe),(Pe=F.onAfterRender)==null||Pe.call(F,{container:g,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Ke=io||nr;c.classList.toggle("persona-pill-peek--visible",Ke)};if(E()){let c=Be.peekBanner;if(c){let y=L=>{L.preventDefault(),L.stopPropagation(),Ot(!0,"user")};c.addEventListener("pointerdown",y),vt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{nr||(nr=!0,$o())},h=()=>{nr&&(nr=!1,$o())};ue.addEventListener("pointerenter",g),ue.addEventListener("pointerleave",h),vt.push(()=>{ue.removeEventListener("pointerenter",g),ue.removeEventListener("pointerleave",h)}),Ue&&(Ue.addEventListener("pointerenter",g),Ue.addEventListener("pointerleave",h),vt.push(()=>{Ue.removeEventListener("pointerenter",g),Ue.removeEventListener("pointerleave",h)}))}let ja=c=>{var Ae,Ie,$e,rt,Ke,gt,pt,We;let g=(Ie=(Ae=o.launcher)==null?void 0:Ae.composerBar)!=null?Ie:{},h=($e=g.expandedSize)!=null?$e:"anchored",y=(rt=g.bottomOffset)!=null?rt:"16px",L=g.collapsedMaxWidth,O=(Ke=g.expandedMaxWidth)!=null?Ke:"880px",N=(gt=g.expandedTopOffset)!=null?gt:"5vh",q=(pt=g.modalMaxWidth)!=null?pt:"880px",F=(We=g.modalMaxHeight)!=null?We:"min(90vh, 800px)",ke="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ee=Te.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ue){let Pe=Ue.style;Pe.bottom=y,Pe.width=L!=null?L:""}if(c&&h!=="fullscreen"){if(h==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=q,ee.maxWidth=ke,ee.maxHeight=F,ee.height=F;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ge})`,ee.top=N,ee.width=O,ee.maxWidth=ke}},or=()=>{var F,ke,ge,ee,Ae,Ie,$e,rt;if(!S())return;if(E()){let gt=(ge=((ke=(F=o.launcher)==null?void 0:F.composerBar)!=null?ke:{}).expandedSize)!=null?ge:"anchored",pt=T?"expanded":"collapsed";Te.dataset.state=pt,Te.dataset.expandedSize=gt,Ue&&(Ue.dataset.state=pt,Ue.dataset.expandedSize=gt),Te.style.removeProperty("display"),Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ja(T),me.style.display=T?"flex":"none",yo(),T?(Ua(),za()):(Ts(),ks()),$o();return}let c=bn(o),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(Ie=(Ae=o.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?Ie:640,y=(rt=($e=o.launcher)==null?void 0:$e.mobileFullscreen)!=null?rt:!0,L=g.innerWidth<=h,O=y&&L&&I,N=Bo(o).reveal;T?(Te.style.removeProperty("display"),Te.style.display=c?"flex":"",Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0"),ue.classList.add("persona-scale-100","persona-opacity-100"),Qe?Qe.element.style.display="none":et&&(et.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!O?(Te.style.removeProperty("display"),Te.style.display="flex",Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Te.style.setProperty("display","none","important"),Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Te.style.display="",Te.classList.add("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100"),ue.classList.add("persona-scale-95","persona-opacity-0")),Qe?Qe.element.style.display=c?"none":"":et&&(et.style.display=c?"none":""))},Ot=(c,g="user")=>{var O,N;if(!S()||T===c)return;let h=T;T=c,or();let y=(()=>{var $e,rt,Ke,gt,pt,We,Pe,je,Je,xt;let q=(rt=($e=o.launcher)==null?void 0:$e.sidebarMode)!=null?rt:!1,F=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,ke=(pt=(gt=o.launcher)==null?void 0:gt.mobileFullscreen)!=null?pt:!0,ge=(Pe=(We=o.launcher)==null?void 0:We.mobileBreakpoint)!=null?Pe:640,ee=F.innerWidth<=ge,Ae=bn(o)&&ke&&ee,Ie=E()&&((xt=(Je=(je=o.launcher)==null?void 0:je.composerBar)==null?void 0:Je.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return q||ke&&ee&&I||Ae||Ie})();if(T&&y){if(!Xt){let q=e.getRootNode(),F=q instanceof ShadowRoot?q.host:e.closest(".persona-host");F&&(Xt=ql(F,(N=(O=o.launcher)==null?void 0:O.zIndex)!=null?N:Cn))}Qt||(Qt=jl(e.ownerDocument))}else T||(Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null);T&&(Jt(),Zo(!0));let L={open:T,source:g,timestamp:Date.now()};T&&!h?s.emit("widget:opened",L):!T&&h&&s.emit("widget:closed",L),s.emit("widget:state",{open:T,launcherEnabled:I,voiceActive:yt.active,streaming:$.isStreaming()})},qr=c=>{jt(c?"stop":"send"),j&&(j.disabled=c),vo.buttons.forEach(g=>{g.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},jr=()=>{yt.active||be&&be.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>jr(),200)});let Ms=()=>{var h,y,L,O,N,q,F,ke,ge,ee,Ae;Fn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",to.textContent=(O=(L=o.copy)==null?void 0:L.welcomeSubtitle)!=null?O:"Ask anything about your account or products.",be.placeholder=(q=(N=o.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=Q.querySelector("[data-persona-intro-card]");if(c){let Ie=((F=o.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=Ie?"":"none",Ie?(Q.classList.remove("persona-gap-3"),Q.classList.add("persona-gap-6")):(Q.classList.remove("persona-gap-6"),Q.classList.add("persona-gap-3"))}!((ge=(ke=o.sendButton)==null?void 0:ke.useIcon)!=null&&ge)&&!($!=null&&$.isStreaming())&&(de.textContent=(Ae=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?Ae:"Send"),be.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',be.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 Ro=null,Ka=()=>{Ro==null&&(Ro=setInterval(()=>{let c=_e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ro),Ro=null;return}let g=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=hi(g-y))})},100))};if($=new ki(o,{onMessagesChanged(c){yr(_e,c,he),Ka(),$&&(c.some(L=>L.role==="user")?vo.render([],$,be,c):vo.render(o.suggestionChips,$,be,c,o.suggestionChipsConfig)),Zo(!io),$a(c);let g=[...c].reverse().find(y=>y.role==="user"),h=yt.lastUserMessageId;g&&g.id!==h&&(yt.lastUserMessageId=g.id,s.emit("user:message",g)),yt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),zr(c),$o()},onStatusChanged(c){var y;let g=(y=o.statusIndicator)!=null?y:{};st(gn,(L=>{var O,N,q,F;return L==="idle"?(O=g.idleText)!=null?O:wn.idle:L==="connecting"?(N=g.connectingText)!=null?N:wn.connecting:L==="connected"?(q=g.connectedText)!=null?q:wn.connected:L==="error"?(F=g.errorText)!=null?F:wn.error:wn[L]})(c),g,c)},onStreamingChanged(c){io=c,qr(c),$&&yr(_e,$.getMessages(),he),c||Zo(!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":X(),Z();break;case"speaking":X(),le();break;default:c==="idle"&&$.isBargeInActive()?(X(),P(),j==null||j.setAttribute("aria-label","End voice session")):(yt.active=!1,X(),co("system"),Bn());break}},onArtifactsState(c){$n=c,qn(),zr()}}),Lt.current=$,((Ad=(Sd=o.voiceRecognition)==null?void 0:Sd.provider)==null?void 0:Ad.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&$.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(G||o.onSSEEvent)&&$.setSSEEventCallback((c,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,g),ve==null||ve.processEvent(c,g),G==null||G.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=hc(c.metadata),M.syncFromMetadata()),(g=c.messages)!=null&&g.length&&$.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&$.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Ls=()=>{var g,h,y;!E()||T||!((y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ot(!0,"auto")},Is=c=>{var L;if(c.preventDefault(),$.isStreaming()){$.cancel(),ve==null||ve.reset(),ce==null||ce.update();return}let g=be.value.trim(),h=(L=ot==null?void 0:ot.hasAttachments())!=null?L:!1;if(!g&&!h)return;Ls();let y;h&&(y=[],y.push(...ot.getContentParts()),g&&y.push(_l(g))),be.value="",be.style.height="auto",vr(),$.sendMessage(g,{contentParts:y}),h&&ot.clearAttachments()},Ga=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Kr={...Li},Gr=!1,vr=()=>{Kr={...Li}},Ya=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Xa=c=>{if(!be)return;Gr=!0,be.value=c,be.dispatchEvent(new Event("input",{bubbles:!0})),Gr=!1;let g=be.value.length;be.setSelectionRange(g,g)},Rs=()=>{Gr||vr()},Ps=c=>{if(be){if(Ga()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=be.selectionStart===0&&be.selectionEnd===0,h=Cm({direction:c.key==="ArrowUp"?"up":"down",history:Ya(),currentValue:be.value,atStart:g,state:Kr});if(Kr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Xa(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}vr(),c.preventDefault(),de.click()}}},Ws=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(me)&&($.cancel(),ve==null||ve.reset(),ce==null||ce.update(),vr(),c.preventDefault(),c.stopImmediatePropagation())},Bs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!ot)return;let g=Ty(c.clipboardData);g.length!==0&&(c.preventDefault(),await ot.handleFiles(g))},Mn=null,Yn=!1,Uo=null,ct=null,Hs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,xr=(c="user")=>{var O,N,q,F,ke,ge,ee;if(Yn||$.isStreaming())return;let g=Hs();if(!g)return;Mn=new g;let y=(N=((O=o.voiceRecognition)!=null?O:{}).pauseDuration)!=null?N:2e3;Mn.continuous=!0,Mn.interimResults=!0,Mn.lang="en-US";let L=be.value;Mn.onresult=Ae=>{let Ie="",$e="";for(let Ke=0;Ke<Ae.results.length;Ke++){let gt=Ae.results[Ke],pt=gt[0].transcript;gt.isFinal?Ie+=pt+" ":$e=pt}let rt=L+Ie+$e;be.value=rt,Uo&&clearTimeout(Uo),(Ie||$e)&&(Uo=window.setTimeout(()=>{let Ke=be.value.trim();Ke&&Mn&&Yn&&(Ao(),be.value="",be.style.height="auto",$.sendMessage(Ke,{viaVoice:!0}))},y))},Mn.onerror=Ae=>{Ae.error!=="no-speech"&&Ao()},Mn.onend=()=>{if(Yn){let Ae=be.value.trim();Ae&&Ae!==L.trim()&&(be.value="",be.style.height="auto",$.sendMessage(Ae,{viaVoice:!0})),Ao()}};try{if(Mn.start(),Yn=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),co(c),Bn(),j){let Ae=(q=o.voiceRecognition)!=null?q:{};ct={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(F=Ae.iconName)!=null?F:"mic",iconSize:parseFloat((ee=(ge=Ae.iconSize)!=null?ge:(ke=o.sendButton)==null?void 0:ke.size)!=null?ee:"40")||24};let Ie=Ae.recordingBackgroundColor,$e=Ae.recordingIconColor,rt=Ae.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Ie!=null?Ie:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=$e!=null?$e:"var(--persona-voice-recording-indicator, #ffffff)",$e){let Ke=j.querySelector("svg");Ke&&Ke.setAttribute("stroke",$e)}rt&&(j.style.borderColor=rt),j.setAttribute("aria-label","Stop voice recognition")}}catch{Ao("system")}},Ao=(c="user")=>{if(Yn){if(Yn=!1,Uo&&(clearTimeout(Uo),Uo=null),Mn){try{Mn.stop()}catch{}Mn=null}if(yt.active=!1,co(c),Bn(),j){if(j.classList.remove("persona-voice-recording"),ct){j.style.backgroundColor=ct.backgroundColor,j.style.color=ct.color,j.style.borderColor=ct.borderColor;let g=j.querySelector("svg");g&&g.setAttribute("stroke",ct.color||"currentColor"),ct=null}j.setAttribute("aria-label","Start voice recognition")}}},Yr=(c,g)=>{var gt,pt,We,Pe,je,Je,xt,H;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((gt=c==null?void 0:c.provider)==null?void 0:gt.type)==="runtype";if(!(h||y))return null;let O=b("div","persona-send-button-wrapper"),N=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",F=(We=g==null?void 0:g.size)!=null?We:"40px",ke=(Pe=c==null?void 0:c.iconSize)!=null?Pe:F,ge=parseFloat(ke)||24,ee=(je=c==null?void 0:c.backgroundColor)!=null?je:g==null?void 0:g.backgroundColor,Ae=(Je=c==null?void 0:c.iconColor)!=null?Je:g==null?void 0:g.textColor;N.style.width=ke,N.style.height=ke,N.style.minWidth=ke,N.style.minHeight=ke,N.style.fontSize="18px",N.style.lineHeight="1",Ae?N.style.color=Ae:N.style.color="var(--persona-text, #111827)";let $e=Me(q,ge,Ae||"currentColor",1.5);$e?N.appendChild($e):N.textContent="\u{1F3A4}",ee?N.style.backgroundColor=ee:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),O.appendChild(N);let rt=(xt=c==null?void 0:c.tooltipText)!=null?xt:"Start voice recognition";if(((H=c==null?void 0:c.showTooltip)!=null?H:!1)&&rt){let Fe=b("div","persona-send-button-tooltip");Fe.textContent=rt,O.appendChild(Fe)}return{micButton:N,micButtonWrapper:O}},Ye=()=>{var g,h,y,L,O;if(!j||ct)return;let c=(g=o.voiceRecognition)!=null?g:{};ct={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((O=(L=c.iconSize)!=null?L:(y=o.sendButton)==null?void 0:y.size)!=null?O:"40")||24}},k=(c,g)=>{var O,N,q,F,ke;if(!j)return;let h=j.querySelector("svg");h&&h.remove();let y=(ke=ct==null?void 0:ct.iconSize)!=null?ke:parseFloat((F=(q=(O=o.voiceRecognition)==null?void 0:O.iconSize)!=null?q:(N=o.sendButton)==null?void 0:N.size)!=null?F:"40")||24,L=Me(c,y,g,1.5);L&&j.appendChild(L)},z=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},P=()=>{var L;if(!j)return;Ye();let c=(L=o.voiceRecognition)!=null?L:{},g=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(z(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let O=j.querySelector("svg");O&&O.setAttribute("stroke",h)}y&&(j.style.borderColor=y),j.setAttribute("aria-label","Stop voice recognition")},Z=()=>{var q,F,ke,ge,ee,Ae,Ie,$e;if(!j)return;Ye();let c=(q=o.voiceRecognition)!=null?q:{},g=$.getVoiceInterruptionMode(),h=(F=c.processingIconName)!=null?F:"loader",y=(ge=(ke=c.processingIconColor)!=null?ke:ct==null?void 0:ct.color)!=null?ge:"",L=(Ae=(ee=c.processingBackgroundColor)!=null?ee:ct==null?void 0:ct.backgroundColor)!=null?Ae:"",O=($e=(Ie=c.processingBorderColor)!=null?Ie:ct==null?void 0:ct.borderColor)!=null?$e:"";z(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=L,j.style.borderColor=O;let N=y||"currentColor";j.style.color=N,k(h,N),j.setAttribute("aria-label","Processing voice input"),g==="none"&&(j.style.cursor="default")},le=()=>{var ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt,We,Pe;if(!j)return;Ye();let c=(ke=o.voiceRecognition)!=null?ke:{},g=$.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:h,L=($e=c.speakingIconColor)!=null?$e:g==="barge-in"?(Ae=(ee=c.recordingIconColor)!=null?ee:ct==null?void 0:ct.color)!=null?Ae:"":(Ie=ct==null?void 0:ct.color)!=null?Ie:"",O=(gt=c.speakingBackgroundColor)!=null?gt:g==="barge-in"?(rt=c.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(Ke=ct==null?void 0:ct.backgroundColor)!=null?Ke:"",N=(Pe=c.speakingBorderColor)!=null?Pe:g==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(We=ct==null?void 0:ct.borderColor)!=null?We:"";z(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=O,j.style.borderColor=N;let q=L||"currentColor";j.style.color=q,k(y,q);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",F),g==="none"&&(j.style.cursor="default"),g==="barge-in"&&j.classList.add("persona-voice-recording")},X=()=>{var c,g,h;j&&(z(),ct&&(j.style.backgroundColor=(c=ct.backgroundColor)!=null?c:"",j.style.color=(g=ct.color)!=null?g:"",j.style.borderColor=(h=ct.borderColor)!=null?h:"",k(ct.iconName,ct.color||"currentColor"),ct=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},Re=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let h=$.getVoiceStatus(),y=$.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Bn(),co("user"),X()});return}$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),yt.manuallyDeactivated=!$.isVoiceActive(),Bn(),co("user"),$.isVoiceActive()?P():X()});return}if(Yn){let h=be.value.trim();yt.manuallyDeactivated=!0,Bn(),Ao("user"),h&&(be.value="",be.style.height="auto",$.sendMessage(h))}else yt.manuallyDeactivated=!1,Bn(),xr("user")};On=Re,j&&(j.addEventListener("click",Re),vt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),X()):Ao("system"),j&&j.removeEventListener("click",Re)}));let Ne=s.on("assistant:complete",()=>{Cs&&(yt.active||yt.manuallyDeactivated||Cs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!yt.active&&!yt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),co("auto"),$.isVoiceActive()&&P()}):xr("auto"))},600))});vt.push(Ne);let dt=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});vt.push(dt);let Xe=()=>{Ot(!T,"user")},Qe=null,et=null;if(I&&!E()){let c=r.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>ya(o,Xe).element,onToggle:Xe});g&&(et=g)}et||(Qe=ya(o,Xe))}Qe?e.appendChild(Qe.element):et&&e.appendChild(et),or(),vo.render(o.suggestionChips,$,be,void 0,o.suggestionChipsConfig),Ms(),qr($.isStreaming()),Zo(!0),Oa(),W&&(!I||E()?setTimeout(()=>jr(),0):T&&setTimeout(()=>jr(),200));let Jt=()=>{var F,ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt,We,Pe,je,Je,xt,H,Fe,oe,tt,_t,Nt;if(E()){St(),or();return}let c=bn(o),g=(ke=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?ke:!1,h=c||g||((ee=(ge=o.launcher)==null?void 0:ge.fullHeight)!=null?ee:!1),y=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,L=($e=(Ie=o.launcher)==null?void 0:Ie.mobileFullscreen)!=null?$e:!0,O=(Ke=(rt=o.launcher)==null?void 0:rt.mobileBreakpoint)!=null?Ke:640,N=y.innerWidth<=O,q=L&&N&&I;try{if(q){yo(),es(e,o);return}if(w&&(w=!1,yo(),es(e,o)),!I&&!c){ue.style.height="",ue.style.width="";return}if(!g&&!c){let qt=(pt=(gt=o==null?void 0:o.launcher)==null?void 0:gt.width)!=null?pt:o==null?void 0:o.launcherWidth,it=qt!=null?qt:fo;ue.style.width=it,ue.style.maxWidth=it}if(Io(),!h){let qt=y.innerHeight,it=64,cn=(Pe=(We=o.launcher)==null?void 0:We.heightOffset)!=null?Pe:0,Xn=Math.max(200,qt-it),Ge=Math.min(640,Xn),Ct=Math.max(200,Ge-cn);ue.style.height=`${Ct}px`}}finally{if(St(),or(),T&&I){let it=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((xt=(Je=o.launcher)==null?void 0:Je.mobileBreakpoint)!=null?xt:640),cn=(Fe=(H=o.launcher)==null?void 0:H.sidebarMode)!=null?Fe:!1,Xn=(tt=(oe=o.launcher)==null?void 0:oe.mobileFullscreen)!=null?tt:!0,Ge=bn(o)&&Xn&&it,Ct=cn||Xn&&it&&I||Ge;if(Ct&&!Qt){let Qn=e.getRootNode(),rn=Qn instanceof ShadowRoot?Qn.host:e.closest(".persona-host");rn&&!Xt&&(Xt=ql(rn,(Nt=(_t=o.launcher)==null?void 0:_t.zIndex)!=null?Nt:Cn)),Qt=jl(e.ownerDocument)}else Ct||(Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null)}}};Jt();let It=(Td=e.ownerDocument.defaultView)!=null?Td:window;if(It.addEventListener("resize",Jt),vt.push(()=>It.removeEventListener("resize",Jt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{St()});c.observe(Ve),vt.push(()=>c.disconnect())}Co=Q.scrollTop;let Dt=Q.scrollHeight,ln=()=>{let c=Q.scrollTop,g=Q.scrollHeight,h=g<Dt;Dt=g;let{action:y,nextLastScrollTop:L}=Ri({following:wo.isFollowing(),currentScrollTop:c,lastScrollTop:Co,nearBottom:pa(Q,ws),userScrollThreshold:Da,isAutoScrolling:No||hr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Co=L,y==="resume"){Jo();return}y==="pause"&&As()};Q.addEventListener("scroll",ln,{passive:!0}),vt.push(()=>Q.removeEventListener("scroll",ln));let yn=c=>{let g=Pi({following:wo.isFollowing(),deltaY:c.deltaY,nearBottom:pa(Q,ws),resumeWhenNearBottom:!0});g==="pause"?As():g==="resume"&&Jo()};Q.addEventListener("wheel",yn,{passive:!0}),vt.push(()=>Q.removeEventListener("wheel",yn)),Wt.addEventListener("click",()=>{Q.scrollTop=Q.scrollHeight,Co=Q.scrollTop,Jo(),Zo(!0)}),vt.push(()=>Wt.remove()),vt.push(()=>{Ss()});let hn=()=>{qe&&(Kn&&(qe.removeEventListener("click",Kn),Kn=null),S()?(qe.style.display="",Kn=()=>{Ot(!1,"user")},qe.addEventListener("click",Kn)):qe.style.display="none")};hn(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{$.clearMessages(),xe.clear(),Jo(),ms(Be.composerOverlay);try{localStorage.removeItem(fs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),G==null||G.clear(),ve==null||ve.reset(),ce==null||ce.update()})})(),Ut&&Ut.addEventListener("submit",Is),be==null||be.addEventListener("keydown",Ps),be==null||be.addEventListener("input",Rs),be==null||be.addEventListener("paste",Bs);let po=(kd=e.ownerDocument)!=null?kd:document;po.addEventListener("keydown",Ws,!0);let Pc="persona-attachment-drop-active",Ds=0,hl=()=>{Ds=0,me.classList.remove(Pc)},Xr=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&ot!==null},Wc=c=>{!tl(c.dataTransfer)||!Xr()||(Ds++,Ds===1&&me.classList.add(Pc))},Bc=c=>{!tl(c.dataTransfer)||!Xr()||(Ds--,Ds<=0&&hl())},Hc=c=>{!tl(c.dataTransfer)||!Xr()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Dc=c=>{var h;if(!tl(c.dataTransfer)||!Xr())return;c.preventDefault(),c.stopPropagation(),hl();let g=Array.from((h=c.dataTransfer.files)!=null?h:[]);g.length!==0&&ot.handleFiles(g)},rr=!0;me.addEventListener("dragenter",Wc,rr),me.addEventListener("dragleave",Bc,rr),e.addEventListener("dragover",Hc,rr),e.addEventListener("drop",Dc,rr);let Qa=e.ownerDocument,Fc=c=>{Xr()&&c.preventDefault()},Oc=c=>{Xr()&&c.preventDefault()};Qa.addEventListener("dragover",Fc),Qa.addEventListener("drop",Oc),vt.push(()=>{Ut&&Ut.removeEventListener("submit",Is),be==null||be.removeEventListener("keydown",Ps),be==null||be.removeEventListener("input",Rs),be==null||be.removeEventListener("paste",Bs),po.removeEventListener("keydown",Ws,!0)}),vt.push(()=>{me.removeEventListener("dragenter",Wc,rr),me.removeEventListener("dragleave",Bc,rr),e.removeEventListener("dragover",Hc,rr),e.removeEventListener("drop",Dc,rr),Qa.removeEventListener("dragover",Fc),Qa.removeEventListener("drop",Oc),hl()}),vt.push(()=>{$.cancel()}),Qe?vt.push(()=>{Qe==null||Qe.destroy()}):et&&vt.push(()=>{et==null||et.remove()});let on={update(c){var en,Po,sn,Ln,go,Ar,Tr,Ja,Fs,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Qp,Jp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,vu,xu,wu,Cu,Su,Au,Tu,ku,Eu,Mu;let g=o.toolCall,h=o.messageActions,y=(en=o.layout)==null?void 0:en.messages,L=o.colorScheme,O=o.loadingIndicator,N=o.iterationDisplay,q=(Po=o.features)==null?void 0:Po.showReasoning,F=(sn=o.features)==null?void 0:sn.showToolCalls,ke=(Ln=o.features)==null?void 0:Ln.toolCallDisplay,ge=(go=o.features)==null?void 0:go.reasoningDisplay;o={...o,...c},yo(),es(e,o),Zi(e,o),el(e,o),qn(),o.colorScheme!==L&&Qo();let ee=pc.getForInstance(o.plugins);r.length=0,r.push(...ee),I=(Tr=(Ar=o.launcher)==null?void 0:Ar.enabled)!=null?Tr:!0,R=(Fs=(Ja=o.launcher)==null?void 0:Ja.autoExpand)!=null?Fs:!1,fe=(Bd=(Wd=o.features)==null?void 0:Wd.showReasoning)!=null?Bd:!0,ae=(Dd=(Hd=o.features)==null?void 0:Hd.showToolCalls)!=null?Dd:!0,ye=(Od=(Fd=o.features)==null?void 0:Fd.scrollToBottom)!=null?Od:{},Gt(),Vo();let Ae=Ee;if(Ee=(_d=(Nd=o.features)==null?void 0:Nd.showEventStreamToggle)!=null?_d:!1,Ee&&!Ae){if(G||(K=new Sa(we),G=new Ca(pe,K),ve=ve!=null?ve:new Aa,K.open().then(()=>G==null?void 0:G.restore()).catch(()=>{}),$.setSSEEventCallback((J,Tt)=>{var $t;($t=o.onSSEEvent)==null||$t.call(o,J,Tt),ve==null||ve.processEvent(J,Tt),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!bt&&De){let J=($d=(Vd=o.features)==null?void 0:Vd.eventStream)==null?void 0:$d.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");bt=b("button",Tt),bt.style.width="28px",bt.style.height="28px",bt.style.color=Rn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let $t=Me("activity","18px","currentColor",1.5);$t&&bt.appendChild($t);let ut=Be.clearChatButtonWrapper,Bt=Be.closeButtonWrapper,pn=ut||Bt;pn&&pn.parentNode===De?De.insertBefore(bt,pn):De.appendChild(bt),bt.addEventListener("click",()=>{ne?Nn():Tn()})}}else!Ee&&Ae&&(Nn(),bt&&(bt.remove(),bt=null),G==null||G.clear(),K==null||K.destroy(),G=null,K=null,ve==null||ve.reset(),ve=null);if(((Ud=o.launcher)==null?void 0:Ud.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((zd=o.launcher)==null?void 0:zd.enabled)===!1&&et&&(et.remove(),et=null),((qd=o.launcher)==null?void 0:qd.enabled)!==!1&&!Qe&&!et){let J=r.find(Tt=>Tt.renderLauncher);if(J!=null&&J.renderLauncher){let Tt=J.renderLauncher({config:o,defaultRenderer:()=>ya(o,Xe).element,onToggle:Xe});Tt&&(et=Tt,e.appendChild(et))}et||(Qe=ya(o,Xe),e.appendChild(Qe.element))}Qe&&Qe.update(o),Le&&((jd=o.launcher)==null?void 0:jd.title)!==void 0&&(Le.textContent=o.launcher.title),He&&((Kd=o.launcher)==null?void 0:Kd.subtitle)!==void 0&&(He.textContent=o.launcher.subtitle);let Ie=(Gd=o.layout)==null?void 0:Gd.header;if((Ie==null?void 0:Ie.layout)!==x&&De){let J=Ie?Ni(o,Ie,{showClose:S(),onClose:()=>Ot(!1,"user")}):Br({config:o,showClose:S(),onClose:()=>Ot(!1,"user")});De.replaceWith(J.header),De=J.header,V=J.iconHolder,Le=J.headerTitle,He=J.headerSubtitle,qe=J.closeButton,x=Ie==null?void 0:Ie.layout}else if(Ie&&(V&&(V.style.display=Ie.showIcon===!1?"none":""),Le&&(Le.style.display=Ie.showTitle===!1?"none":""),He&&(He.style.display=Ie.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ie.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let J=Ie.showClearChat;if(J!==void 0){Be.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Tt}=Be;Tt&&!Tt.classList.contains("persona-absolute")&&(J?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let rt=((Yd=o.layout)==null?void 0:Yd.showHeader)!==!1;De&&(De.style.display=rt?"":"none");let Ke=((Xd=o.layout)==null?void 0:Xd.showFooter)!==!1;Ve&&(Ve.style.display=Ke?"":"none"),St(),Vo(),I!==B?I?Ot(R,"auto"):(T=!0,or()):R!==D&&Ot(R,"auto"),D=R,B=I,Jt(),hn();let We=JSON.stringify(c.toolCall)!==JSON.stringify(g),Pe=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((Qd=o.layout)==null?void 0:Qd.messages)!==JSON.stringify(y),Je=((Jd=o.loadingIndicator)==null?void 0:Jd.render)!==(O==null?void 0:O.render)||((Zd=o.loadingIndicator)==null?void 0:Zd.renderIdle)!==(O==null?void 0:O.renderIdle)||((ep=o.loadingIndicator)==null?void 0:ep.showBubble)!==(O==null?void 0:O.showBubble),xt=o.iterationDisplay!==N,H=((np=(tp=o.features)==null?void 0:tp.showReasoning)!=null?np:!0)!==(q!=null?q:!0)||((rp=(op=o.features)==null?void 0:op.showToolCalls)!=null?rp:!0)!==(F!=null?F:!0)||JSON.stringify((sp=o.features)==null?void 0:sp.toolCallDisplay)!==JSON.stringify(ke)||JSON.stringify((ap=o.features)==null?void 0:ap.reasoningDisplay)!==JSON.stringify(ge);(We||Pe||je||Je||xt||H)&&$&&(xs++,yr(_e,$.getMessages(),he));let oe=(ip=o.launcher)!=null?ip:{},tt=(lp=oe.headerIconHidden)!=null?lp:!1,_t=(dp=(cp=o.layout)==null?void 0:cp.header)==null?void 0:dp.showIcon,Nt=tt||_t===!1,qt=oe.headerIconName,it=(pp=oe.headerIconSize)!=null?pp:"48px";if(V){let J=me.querySelector(".persona-border-b-persona-divider"),Tt=J==null?void 0:J.querySelector(".persona-flex-col");if(Nt)V.style.display="none",J&&Tt&&!J.contains(Tt)&&J.insertBefore(Tt,J.firstChild);else{if(V.style.display="",V.style.height=it,V.style.width=it,J&&Tt&&(J.contains(V)?V.nextSibling!==Tt&&(V.remove(),J.insertBefore(V,Tt)):J.insertBefore(V,Tt)),qt){let ut=parseFloat(it)||24,Bt=Me(qt,ut*.6,"#ffffff",2);Bt?V.replaceChildren(Bt):V.textContent=(up=oe.agentIconText)!=null?up:"\u{1F4AC}"}else if(oe.iconUrl){let ut=V.querySelector("img");if(ut)ut.src=oe.iconUrl,ut.style.height=it,ut.style.width=it;else{let Bt=document.createElement("img");Bt.src=oe.iconUrl,Bt.alt="",Bt.className="persona-rounded-xl persona-object-cover",Bt.style.height=it,Bt.style.width=it,V.replaceChildren(Bt)}}else{let ut=V.querySelector("svg"),Bt=V.querySelector("img");(ut||Bt)&&V.replaceChildren(),V.textContent=(mp=oe.agentIconText)!=null?mp:"\u{1F4AC}"}let $t=V.querySelector("img");$t&&($t.style.height=it,$t.style.width=it)}}let cn=(fp=(gp=o.layout)==null?void 0:gp.header)==null?void 0:fp.showTitle,Xn=(bp=(hp=o.layout)==null?void 0:hp.header)==null?void 0:bp.showSubtitle;if(Le&&(Le.style.display=cn===!1?"none":""),He&&(He.style.display=Xn===!1?"none":""),qe){((vp=(yp=o.layout)==null?void 0:yp.header)==null?void 0:vp.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let Tt=(xp=oe.closeButtonSize)!=null?xp:"32px",$t=(wp=oe.closeButtonPlacement)!=null?wp:"inline";qe.style.height=Tt,qe.style.width=Tt;let{closeButtonWrapper:ut}=Be,Bt=$t==="top-right",pn=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Bt!==pn)if(ut.remove(),Bt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(ut);else{let ht=(Sp=(Cp=oe.clearChat)==null?void 0:Cp.placement)!=null?Sp:"inline",un=(Tp=(Ap=oe.clearChat)==null?void 0:Ap.enabled)!=null?Tp:!0;ut.className=un&&ht==="inline"?"":"persona-ml-auto";let Dn=me.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(ut)}if(qe.style.color=oe.closeButtonColor||Rn.actionIconColor,oe.closeButtonBackgroundColor?(qe.style.backgroundColor=oe.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),oe.closeButtonBorderWidth||oe.closeButtonBorderColor){let ht=oe.closeButtonBorderWidth||"0px",un=oe.closeButtonBorderColor||"transparent";qe.style.border=`${ht} solid ${un}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");oe.closeButtonBorderRadius?(qe.style.borderRadius=oe.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),oe.closeButtonPaddingX?(qe.style.paddingLeft=oe.closeButtonPaddingX,qe.style.paddingRight=oe.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),oe.closeButtonPaddingY?(qe.style.paddingTop=oe.closeButtonPaddingY,qe.style.paddingBottom=oe.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let xn=(kp=oe.closeButtonIconName)!=null?kp:"x",To=(Ep=oe.closeButtonIconText)!=null?Ep:"\xD7";qe.innerHTML="";let In=Me(xn,"28px","currentColor",1);In?qe.appendChild(In):qe.textContent=To;let Zt=(Mp=oe.closeButtonTooltipText)!=null?Mp:"Close chat",Zn=(Lp=oe.closeButtonShowTooltip)!=null?Lp:!0;if(qe.setAttribute("aria-label",Zt),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),Zn&&Zt)){let ht=null,un=()=>{if(ht||!qe)return;let kr=qe.ownerDocument,Os=kr.body;if(!Os)return;ht=Wo(kr,"div","persona-clear-chat-tooltip"),ht.textContent=Zt;let Ns=Wo(kr,"div");Ns.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ns);let Er=qe.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(lr),ht.style.left=`${Er.left+Er.width/2}px`,ht.style.top=`${Er.top-8}px`,ht.style.transform="translate(-50%, -100%)",Os.appendChild(ht)},Dn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ut.addEventListener("mouseenter",un),ut.addEventListener("mouseleave",Dn),qe.addEventListener("focus",un),qe.addEventListener("blur",Dn),ut._cleanupTooltip=()=>{Dn(),ut&&(ut.removeEventListener("mouseenter",un),ut.removeEventListener("mouseleave",Dn)),qe&&(qe.removeEventListener("focus",un),qe.removeEventListener("blur",Dn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:Ct}=Be;if(Ge){let J=(Ip=oe.clearChat)!=null?Ip:{},Tt=(Rp=J.enabled)!=null?Rp:!0,$t=(Wp=(Pp=o.layout)==null?void 0:Pp.header)==null?void 0:Wp.showClearChat,ut=$t!==void 0?$t:Tt,Bt=(Bp=J.placement)!=null?Bp:"inline";if(Ct){Ct.style.display=ut?"":"none";let{closeButtonWrapper:pn}=Be;!E()&&pn&&!pn.classList.contains("persona-absolute")&&(ut?pn.classList.remove("persona-ml-auto"):pn.classList.add("persona-ml-auto"));let xn=Bt==="top-right",To=Ct.classList.contains("persona-absolute");if(!E()&&xn!==To&&ut){if(Ct.remove(),xn)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",me.style.position="relative",me.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let Zt=me.querySelector(".persona-border-b-persona-divider"),Zn=Be.closeButtonWrapper;Zt&&Zn&&Zn.parentElement===Zt?Zt.insertBefore(Ct,Zn):Zt&&Zt.appendChild(Ct)}let In=Be.closeButtonWrapper;In&&!In.classList.contains("persona-absolute")&&(xn?In.classList.add("persona-ml-auto"):In.classList.remove("persona-ml-auto"))}}if(ut){if(!E()){let ht=(Hp=J.size)!=null?Hp:"32px";Ge.style.height=ht,Ge.style.width=ht}let pn=(Dp=J.iconName)!=null?Dp:"refresh-cw",xn=(Fp=J.iconColor)!=null?Fp:"";Ge.style.color=xn||Rn.actionIconColor,Ge.innerHTML="";let To=E()?"14px":"20px",In=Me(pn,To,"currentColor",2);if(In&&Ge.appendChild(In),J.backgroundColor?(Ge.style.backgroundColor=J.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let ht=J.borderWidth||"0px",un=J.borderColor||"transparent";Ge.style.border=`${ht} solid ${un}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");J.borderRadius?(Ge.style.borderRadius=J.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),J.paddingX?(Ge.style.paddingLeft=J.paddingX,Ge.style.paddingRight=J.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),J.paddingY?(Ge.style.paddingTop=J.paddingY,Ge.style.paddingBottom=J.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Zt=(Op=J.tooltipText)!=null?Op:"Clear chat",Zn=(Np=J.showTooltip)!=null?Np:!0;if(Ge.setAttribute("aria-label",Zt),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),Zn&&Zt)){let ht=null,un=()=>{if(ht||!Ge)return;let kr=Ge.ownerDocument,Os=kr.body;if(!Os)return;ht=Wo(kr,"div","persona-clear-chat-tooltip"),ht.textContent=Zt;let Ns=Wo(kr,"div");Ns.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ns);let Er=Ge.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(lr),ht.style.left=`${Er.left+Er.width/2}px`,ht.style.top=`${Er.top-8}px`,ht.style.transform="translate(-50%, -100%)",Os.appendChild(ht)},Dn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Ct.addEventListener("mouseenter",un),Ct.addEventListener("mouseleave",Dn),Ge.addEventListener("focus",un),Ge.addEventListener("blur",Dn),Ct._cleanupTooltip=()=>{Dn(),Ct&&(Ct.removeEventListener("mouseenter",un),Ct.removeEventListener("mouseleave",Dn)),Ge&&(Ge.removeEventListener("focus",un),Ge.removeEventListener("blur",Dn))}}}}let Qn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[mc],rn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ta.message,Ta.messageAndClick];M=gc({parsers:Qn,handlers:rn,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),he=kg(o,M,Y),$.updateConfig(o),yr(_e,$.getMessages(),he),vo.render(o.suggestionChips,$,be,void 0,o.suggestionChipsConfig),Ms(),qr($.isStreaming());let mo=((_p=o.voiceRecognition)==null?void 0:_p.enabled)===!0,Jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),wr=(($p=(Vp=o.voiceRecognition)==null?void 0:Vp.provider)==null?void 0:$p.type)==="runtype";if(mo&&(Jn||wr))if(!j||!zt){let J=Yr(o.voiceRecognition,o.sendButton);J&&(j=J.micButton,zt=J.micButtonWrapper,Pt.insertBefore(zt,Pn),j.addEventListener("click",Re),j.disabled=$.isStreaming())}else{let J=(Up=o.voiceRecognition)!=null?Up:{},Tt=(zp=o.sendButton)!=null?zp:{},$t=(qp=J.iconName)!=null?qp:"mic",ut=(jp=Tt.size)!=null?jp:"40px",Bt=(Kp=J.iconSize)!=null?Kp:ut,pn=parseFloat(Bt)||24;j.style.width=Bt,j.style.height=Bt,j.style.minWidth=Bt,j.style.minHeight=Bt;let xn=(Yp=(Gp=J.iconColor)!=null?Gp:Tt.textColor)!=null?Yp:"currentColor";j.innerHTML="";let To=Me($t,pn,xn,2);To?j.appendChild(To):j.textContent="\u{1F3A4}";let In=(Xp=J.backgroundColor)!=null?Xp:Tt.backgroundColor;In?j.style.backgroundColor=In:j.style.backgroundColor="",xn?j.style.color=xn:j.style.color="var(--persona-text, #111827)",J.borderWidth?(j.style.borderWidth=J.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),J.borderColor?j.style.borderColor=J.borderColor:j.style.borderColor="",J.paddingX?(j.style.paddingLeft=J.paddingX,j.style.paddingRight=J.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),J.paddingY?(j.style.paddingTop=J.paddingY,j.style.paddingBottom=J.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Zt=zt==null?void 0:zt.querySelector(".persona-send-button-tooltip"),Zn=(Qp=J.tooltipText)!=null?Qp:"Start voice recognition";if(((Jp=J.showTooltip)!=null?Jp:!1)&&Zn)if(Zt)Zt.textContent=Zn,Zt.style.display="";else{let un=document.createElement("div");un.className="persona-send-button-tooltip",un.textContent=Zn,zt==null||zt.insertBefore(un,j)}else Zt&&(Zt.style.display="none");zt.style.display="",j.disabled=$.isStreaming()}else j&&zt&&(zt.style.display="none",((eu=(Zp=o.voiceRecognition)==null?void 0:Zp.provider)==null?void 0:eu.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Yn&&Ao());if(((tu=o.attachments)==null?void 0:tu.enabled)===!0)if(!Vt||!Ze){let J=(nu=o.attachments)!=null?nu:{},$t=(ru=((ou=o.sendButton)!=null?ou:{}).size)!=null?ru:"40px";Ce||(Ce=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ce.style.display="none",Ut.insertBefore(Ce,be)),se||(se=document.createElement("input"),se.type="file",se.accept=((su=J.allowedTypes)!=null?su:qo).join(","),se.multiple=((au=J.maxFiles)!=null?au:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),Ut.insertBefore(se,be)),Vt=b("div","persona-send-button-wrapper"),Ze=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ze.type="button",Ze.setAttribute("aria-label",(iu=J.buttonTooltipText)!=null?iu:"Attach file");let ut=(lu=J.buttonIconName)!=null?lu:"paperclip",Bt=$t,pn=parseFloat(Bt)||40,xn=Math.round(pn*.6);Ze.style.width=Bt,Ze.style.height=Bt,Ze.style.minWidth=Bt,Ze.style.minHeight=Bt,Ze.style.fontSize="18px",Ze.style.lineHeight="1",Ze.style.backgroundColor="transparent",Ze.style.color="var(--persona-primary, #111827)",Ze.style.border="none",Ze.style.borderRadius="6px",Ze.style.transition="background-color 0.15s ease",Ze.addEventListener("mouseenter",()=>{Ze.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ze.addEventListener("mouseleave",()=>{Ze.style.backgroundColor="transparent"});let To=Me(ut,xn,"currentColor",1.5);To?Ze.appendChild(To):Ze.textContent="\u{1F4CE}",Ze.addEventListener("click",Zn=>{Zn.preventDefault(),se==null||se.click()}),Vt.appendChild(Ze);let In=(cu=J.buttonTooltipText)!=null?cu:"Attach file",Zt=b("div","persona-send-button-tooltip");Zt.textContent=In,Vt.appendChild(Zt),at.append(Vt),!ot&&se&&Ce&&(ot=ca.fromConfig(J),ot.setPreviewsContainer(Ce),se.addEventListener("change",async()=>{ot&&(se!=null&&se.files)&&(await ot.handleFileSelect(se.files),se.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(Eg(J.dropOverlay))}else{Vt.style.display="";let J=(du=o.attachments)!=null?du:{};se&&(se.accept=((pu=J.allowedTypes)!=null?pu:qo).join(","),se.multiple=((uu=J.maxFiles)!=null?uu:4)>1),ot&&ot.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else Vt&&(Vt.style.display="none"),ot&&ot.clearAttachments(),(mu=me.querySelector(".persona-attachment-drop-overlay"))==null||mu.remove();let Yt=(gu=o.sendButton)!=null?gu:{},Cr=(fu=Yt.useIcon)!=null?fu:!1,sr=(hu=Yt.iconText)!=null?hu:"\u2191",ar=Yt.iconName,zo=(bu=Yt.tooltipText)!=null?bu:"Send message",Sr=(yu=Yt.showTooltip)!=null?yu:!1,nt=(vu=Yt.size)!=null?vu:"40px",vn=Yt.backgroundColor,fn=Yt.textColor;if(Cr){if(de.style.width=nt,de.style.height=nt,de.style.minWidth=nt,de.style.minHeight=nt,de.style.fontSize="18px",de.style.lineHeight="1",de.innerHTML="",fn?de.style.color=fn:de.style.color="var(--persona-button-primary-fg, #ffffff)",ar){let J=parseFloat(nt)||24,Tt=(fn==null?void 0:fn.trim())||"currentColor",$t=Me(ar,J,Tt,2);$t?de.appendChild($t):de.textContent=sr}else de.textContent=sr;de.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",vn?(de.style.backgroundColor=vn,de.classList.remove("persona-bg-persona-primary")):(de.style.backgroundColor="",de.classList.add("persona-bg-persona-primary"))}else de.textContent=(wu=(xu=o.copy)==null?void 0:xu.sendButtonLabel)!=null?wu:"Send",de.style.width="",de.style.height="",de.style.minWidth="",de.style.minHeight="",de.style.fontSize="",de.style.lineHeight="",de.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",vn?(de.style.backgroundColor=vn,de.classList.remove("persona-bg-persona-accent")):de.classList.add("persona-bg-persona-accent"),fn?de.style.color=fn:de.classList.add("persona-text-white");Yt.borderWidth?(de.style.borderWidth=Yt.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Yt.borderColor?de.style.borderColor=Yt.borderColor:de.style.borderColor="",Yt.paddingX?(de.style.paddingLeft=Yt.paddingX,de.style.paddingRight=Yt.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Yt.paddingY?(de.style.paddingTop=Yt.paddingY,de.style.paddingBottom=Yt.paddingY):(de.style.paddingTop="",de.style.paddingBottom="");let dn=Pn==null?void 0:Pn.querySelector(".persona-send-button-tooltip");if(Sr&&zo)if(dn)dn.textContent=zo,dn.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=zo,Pn==null||Pn.insertBefore(J,de)}else dn&&(dn.style.display="none");let ft=(ku=(Cu=o.layout)==null?void 0:Cu.contentMaxWidth)!=null?ku:E()?(Tu=(Au=(Su=o.launcher)==null?void 0:Su.composerBar)==null?void 0:Au.contentMaxWidth)!=null?Tu:"720px":void 0;ft?(_e.style.maxWidth=ft,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%",Ut&&(Ut.style.maxWidth=ft,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),Ht&&(Ht.style.maxWidth=ft,Ht.style.marginLeft="auto",Ht.style.marginRight="auto")):(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight="",_e.style.width="",Ut&&(Ut.style.maxWidth="",Ut.style.marginLeft="",Ut.style.marginRight=""),Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""));let lt=(Eu=o.statusIndicator)!=null?Eu:{},Et=(Mu=lt.visible)!=null?Mu:!0;if(gn.style.display=Et?"":"none",$){let J=$.getStatus();st(gn,($t=>{var ut,Bt,pn,xn;return $t==="idle"?(ut=lt.idleText)!=null?ut:wn.idle:$t==="connecting"?(Bt=lt.connectingText)!=null?Bt:wn.connecting:$t==="connected"?(pn=lt.connectedText)!=null?pn:wn.connected:$t==="error"?(xn=lt.errorText)!=null?xn:wn.error:wn[$t]})(J),lt,J)}gn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Hn=lt.align==="left"?"persona-text-left":lt.align==="center"?"persona-text-center":"persona-text-right";gn.classList.add(Hn)},open(){S()&&Ot(!0,"api")},close(){S()&&Ot(!1,"api")},toggle(){S()&&Ot(!T,"api")},clearChat(){kn=!1,$.clearMessages(),xe.clear(),Jo();try{localStorage.removeItem(fs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},M.syncFromMetadata(),G==null||G.clear(),ve==null||ve.reset(),ce==null||ce.update()},setMessage(c){return!be||$.isStreaming()?!1:(!T&&S()&&Ot(!0,"system"),be.value=c,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let g=(c==null?void 0:c.trim())||be.value.trim();return g?(!T&&S()&&Ot(!0,"system"),be.value="",be.style.height="auto",$.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return $.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!T&&S()&&Ot(!0,"system"),yt.manuallyDeactivated=!1,Bn(),$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),co("user"),$.isVoiceActive()&&P()})),!0):Yn?!0:Hs()?(!T&&S()&&Ot(!0,"system"),yt.manuallyDeactivated=!1,Bn(),xr("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Bn(),co("user"),X()}),!0):!1:Yn?(yt.manuallyDeactivated=!0,Bn(),Ao("user"),!0):!1},injectMessage(c){return!T&&S()&&Ot(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!T&&S()&&Ot(!0,"system");let g=$.injectAssistantMessage(c);return _&&(_=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),g},injectUserMessage(c){return!T&&S()&&Ot(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!T&&S()&&Ot(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!T&&S()&&Ot(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!T&&S()&&Ot(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!T&&S()&&Ot(!0,"system"),$.injectTestEvent(c)},async connectStream(c,g){return $.connectStream(c,g)},__pushEventStreamEvent(c){G&&(ve==null||ve.processEvent(c.type,c.payload),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Ee||!G||Tn()},hideEventStream(){ne&&Nn()},isEventStreamVisible(){return ne},showArtifacts(){bo(o)&&(kn=!1,qn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){bo(o)&&(kn=!0,qn())},upsertArtifact(c){return bo(o)?(kn=!1,$.upsertArtifact(c)):null},selectArtifact(c){bo(o)&&$.selectArtifact(c)},clearArtifacts(){bo(o)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!T&&!E()||!be?!1:(be.focus(),!0)},async resolveApproval(c,g,h){let L=$.getMessages().find(O=>{var N;return O.variant==="approval"&&((N=O.approval)==null?void 0:N.id)===c});if(!(L!=null&&L.approval))throw new Error(`Approval not found: ${c}`);if(L.approval.toolType==="webmcp"){$.resolveWebMcpApproval(L.id,g);return}return $.resolveApproval(L.approval,g,h)},getMessages(){return $.getMessages()},getStatus(){return $.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()&&T},isVoiceActive(){return yt.active},getState(){return{open:S()&&T,launcherEnabled:I,voiceActive:yt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!T&&S()&&Ot(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Sg({onSubmit:async(y,L)=>{var O;$.isClientTokenMode()&&await $.submitCSATFeedback(y,L),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!T&&S()&&Ot(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Ag({onSubmit:async(y,L)=>{var O;$.isClientTokenMode()&&await $.submitNPSFeedback(y,L),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return $.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return $.submitNPSFeedback(c,g)},destroy(){Ro!=null&&(clearInterval(Ro),Ro=null),vt.forEach(c=>c()),Te.remove(),Ue==null||Ue.remove(),Qe==null||Qe.destroy(),et==null||et.remove(),Kn&&qe.removeEventListener("click",Kn)}};if((((Ed=n==null?void 0:n.debugTools)!=null?Ed:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:on,getMessages:on.getMessages,getStatus:on.getStatus,getMetadata:on.getPersistentMetadata,updateMetadata:on.updatePersistentMetadata,clearHistory:()=>on.clearChat(),setVoiceActive:h=>h?on.startVoiceRecognition():on.stopVoiceRecognition()};window.AgentWidgetBrowser=g,vt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.focusInput()};if(window.addEventListener("persona:focusInput",g),vt.push(()=>{window.removeEventListener("persona:focusInput",g)}),Ee){let q=ke=>{let ge=ke.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.showEventStream()},F=ke=>{let ge=ke.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",F),vt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",F)})}let h=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.showArtifacts()},y=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.hideArtifacts()},L=q=>{let F=q.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&on.upsertArtifact(F.artifact)},O=q=>{let F=q.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&on.selectArtifact(F.id)},N=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",O),window.addEventListener("persona:clearArtifacts",N),vt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",O),window.removeEventListener("persona:clearArtifacts",N)})}let uo=ky(o.persistState);if(uo&&S()){let c=Ey(uo.storage),g=`${uo.keyPrefix}widget-open`,h=`${uo.keyPrefix}widget-voice`,y=`${uo.keyPrefix}widget-voice-mode`;if(c){let L=((Md=uo.persist)==null?void 0:Md.openState)&&c.getItem(g)==="true",O=((Ld=uo.persist)==null?void 0:Ld.voiceState)&&c.getItem(h)==="true",N=((Id=uo.persist)==null?void 0:Id.voiceState)&&c.getItem(y)==="true";if(L&&setTimeout(()=>{on.open(),setTimeout(()=>{var q;if(O||N)on.startVoiceRecognition();else if((q=uo.persist)!=null&&q.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Rd=uo.persist)!=null&&Rd.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Pd=uo.persist)!=null&&Pd.voiceState&&(s.on("voice:state",q=>{c.setItem(h,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),uo.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(h),c.removeItem(y)},F=()=>q();window.addEventListener("persona:clear-chat",F),vt.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return m&&S()&&setTimeout(()=>{on.open()},0),$o(),on};var My=(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},Lg=(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"},xc=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=""},Ig=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",xc(e)},bc=e=>{e.style.transition=""},yc=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=""},vc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},nl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ly=(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))},Iy=(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)},Rg=(e,t,n,o,r,s,a)=>{var C,v,M,I,R,W;let i=Bo(s),d=i.reveal==="push";Ly(e,t,n,o,d),Iy(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=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,f=l!=null?l.innerWidth<=p:!1;if(m&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),yc(t),bc(o),Ig(o),vc(n),nl(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((W=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?W:Cn),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"),Ig(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",yc(t),bc(o),vc(n),nl(r,o);let D=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",x=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=D,o.style.transform=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",bc(o),xc(o),nl(r,o);let D=My(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),x=i.animate?"transform 180ms ease":"none",w=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+D}px`,t.style.transition=x,t.style.transform=w,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",yc(t),xc(o),vc(n),nl(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=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 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||w?"hidden":"visible",o.style.transition=x,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")}},Ry=(e,t)=>{let n=e.ownerDocument.createElement("div");return Lg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Lg(n,o)},destroy(){n.remove()}}},Py=(e,t)=>{var R,W,D,B;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),m=n.createElement("div"),p=(W=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||W?(B=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?B:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",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(),Bo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Rg(a,i,d,l,m,t,p)}),f.observe(a))},v=()=>{Rg(a,i,d,l,m,t,p),C()},M=a.ownerDocument.defaultView,I=()=>{v()};return M==null||M.addEventListener("resize",I),Bo(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,E;t=x,((E=(w=t==null?void 0:t.launcher)==null?void 0:w.enabled)!=null?E:!0)===!1&&(p=!0),v()},destroy(){M==null||M.removeEventListener("resize",I),u(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Pg=(e,t)=>bn(t)?Py(e,t):Ry(e,t);var Nr={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ol=.15,rl=1.5,ka="persona-preview-shell-theme",wc={load:()=>null,save:()=>{},clear:()=>{}},Cc=["How do I get started?","Pricing & plans","Talk to support"];function Ea(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Sc(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 sl(e){let t=Sc(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 na=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 nl(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(xa);o||(o=n.createElement("style"),o.id=xa,n.head.appendChild(o)),o.textContent=tl(t)}var vc=`
131
+ .preview-workspace-card.short { height: 96px; }`}function al(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(ka);o||(o=n.createElement("style"),o.id=ka,n.head.appendChild(o)),o.textContent=sl(t)}var Ac=`
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 na=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>`,xc=`
150
+ </div>`,Tc=`
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 na=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 ol(e,t,n,o){let r=`
164
- ${vc}
163
+ </div>`;function il(e,t,n,o){let r=`
164
+ ${Ac}
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 na=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
- ${xc}
176
+ ${Tc}
177
177
  </div>
178
178
  </div>
179
179
  </div>`;return`<!DOCTYPE html>
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var na=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="${wa(o)}">
185
- <style id="${xa}">${tl(t)}</style>
184
+ <link rel="stylesheet" href="${Ea(o)}">
185
+ <style id="${ka}">${sl(t)}</style>
186
186
  </head>
187
187
  <body>
188
188
  ${n?s:r}
189
189
  </body>
190
- </html>`}var vy={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)"};function wf(e){return vy[e]}function rl(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
190
+ </html>`}var Wy={"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 Wg(e){return Wy[e]}function ll(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
191
191
  `),createdAt:n};case"assistant-markdown-table":return{id:`preview-seq-assistant-table-${o}`,role:"assistant",content:["Here are the built-in streaming animations at a glance:","","| Preset | Wrap unit | Best for |","| ------------ | --------- | --------------------------- |","| Typewriter | Character | Classic terminal feel |","| Letter rise | Character | Soft, staggered entrance |","| Word fade | Word | Longer-form assistant replies |","| Pop bubble | Bubble | Short, punchy affirmations |"].join(`
192
192
  `),createdAt:n};case"assistant-image":return{id:`preview-seq-assistant-image-${o}`,role:"assistant",content:["Here's the reference diagram you asked for \u2014 let me know if you'd like a different view:","","![Stream animation reference](https://placehold.co/320x200/png?text=Stream+Animation)","","The gradient shows how per-unit delays stagger across the reply."].join(`
193
- `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function Cf(e,t){return[...e,rl(t,e.length)]}function wc(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function Sf(e,t,n){var d,l;let o=rl(e,t);if(!wc(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 xy=()=>[{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()}],wy=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 Cc(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"&&wy(t)?[...xy(),...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 sl(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:bc:e.suggestionChips,initialMessages:Cc(t,e,n),storageAdapter:hc};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function dr(e,t){var s,a,i,d;let n=e.theme?nn(e.theme,{validate:!1}):nn(),o=(s=e.scene)!=null?s:"conversation",r={...At,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return sl(r,o,(d=e.appendedMessages)!=null?d:[])}function Af(e,t,n){var a,i,d;let o=e.theme?nn(e.theme,{validate:!1}):nn(),r=(a=e.scene)!=null?a:"conversation",s={...At,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return sl(s,r,t)}function Tf(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:dr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:dr(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:dr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:dr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:dr(e,n),shellMode:n}]}function kf(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 u(){var I;return(I=n.zoom)!=null?I:i}function g(){var k,O;let I=getComputedStyle(e),D=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),F=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),B=40,v=((k=n.compareMode)!=null?k:"off")!=="off",x=(e.clientWidth-D-B)/(v?2:1),E=e.clientHeight-F-B;if(x<=0||E<=0)return 1;let C=(O=Hr[m()])!=null?O:Hr.desktop;return Math.min(x/C.w,E/C.h,1)}function p(){var F,B,v;i=g();let I=Math.max(Zi,Math.min(el,u()));d=I;let D=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of D){let E=(F=x.dataset.device)!=null?F:"desktop",C=(B=Hr[E])!=null?B:Hr.desktop;x.style.width=`${C.w*I}px`,x.style.height=`${C.h*I}px`,E==="mobile"&&(x.style.borderRadius=`${32*I}px`);let k=x.querySelector("iframe");k&&(k.style.width=`${C.w}px`,k.style.height=`${C.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${I})`)}(v=n.onScaleChange)==null||v.call(n,I)}function w(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let D of o)D.destroy();for(let D of r)D();o=[],r=[]}function S(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function L(){var ge,le,ye,Ne;if(a)return;w();let I=++l,D=Tf(n),F=m(),B=((ge=n.compareMode)!=null?ge:"off")!=="off",v=((le=n.scene)!=null?le:"conversation")==="minimized",x=(ye=n.widgetCssPath)!=null?ye:"/widget-dist/widget.css",E=(Ne=n.buildSrcdoc)!=null?Ne:ol,C=F==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=xe=>`<div class="${C}" data-mount-id="${xe.mountId}" data-device="${F}" data-shell-mode="${xe.shellMode}">
194
- ${B?`<div class="preview-frame-meta"><span class="preview-frame-label">${wa(xe.label)}</span></div>`:""}
195
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${xe.mountId}"></iframe>
196
- </div>`,O=B?`<div class="preview-compare-grid">${D.map(xe=>`<div class="preview-compare-cell">${k(xe)}</div>`).join("")}</div>`:`<div class="preview-single">${k(D[0])}</div>`;n.morphContainer?n.morphContainer(e,O):e.innerHTML=O,p();let U=S(),K=0,fe=U.length,ae=()=>{var J,Ie,X,we,Ae;if(a||I!==l)return;for(let pe of U){let Ce=pe.dataset.mountId;if(!Ce||!pe.contentDocument)continue;let qe=D.find(ve=>ve.mountId===Ce);if(!qe)continue;let ne=()=>{},oe=un(qe.config),se=oe?(()=>{var Y;let ve=(Y=pe.contentDocument)==null?void 0:Y.getElementById(`preview-content-${Ce}`);if(!ve)return null;let ce=xf(ve,qe.config),ze=pe.contentDocument.createElement("div");ze.id=Ce,ze.style.height="100%",ze.style.display="flex",ze.style.flexDirection="column",ze.style.flex="1",ze.style.minHeight="0",ce.host.appendChild(ze);let De=()=>ce.syncWidgetState(ot.getState()),de=ne;return ne=()=>{ce.destroy(),de()},ze.__syncDock=De,ze.__hostLayout=ce,ze})():pe.contentDocument.getElementById(Ce);if(!se)continue;let ot=hf(se,qe.config);if(o.push(ot),oe&&se.__syncDock){let ve=se.__syncDock,ce=ot.on("widget:opened",ve),ze=ot.on("widget:closed",ve),De=ne;ne=()=>{ce(),ze(),De()},ve()}r.push(ne),v&&ot.close()}if(((J=n.scene)!=null?J:"conversation")==="artifact"||(we=(X=(Ie=n.config)==null?void 0:Ie.features)==null?void 0:X.artifacts)!=null&&we.enabled)for(let pe of o)pe.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
193
+ `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"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 Bg(e,t){return[...e,ll(t,e.length)]}function kc(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function Hg(e,t,n){var d,l;let o=ll(e,t);if(!kc(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 By=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Hy=e=>{var t,n,o,r,s,a,i,d;return!!((n=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&n.activePreview||(r=(o=e==null?void 0:e.features)==null?void 0:o.toolCallDisplay)!=null&&r.grouped||(a=(s=e==null?void 0:e.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Ec(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&Hy(t)?[...By(),...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 cl(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:Cc:e.suggestionChips,initialMessages:Ec(t,e,n),storageAdapter:wc};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function mr(e,t){var s,a,i,d;let n=e.theme?an(e.theme,{validate:!1}):an(),o=(s=e.scene)!=null?s:"conversation",r={...Rt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return cl(r,o,(d=e.appendedMessages)!=null?d:[])}function Dg(e,t,n){var a,i,d;let o=e.theme?an(e.theme,{validate:!1}):an(),r=(a=e.scene)!=null?a:"conversation",s={...Rt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return cl(s,r,t)}function Fg(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:mr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:mr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:mr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:mr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:mr(e,n),shellMode:n}]}function Og(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function m(){var R;return(R=n.device)!=null?R:"desktop"}function p(){var R;return(R=n.zoom)!=null?R:i}function f(){var T,_;let R=getComputedStyle(e),W=parseFloat(R.paddingLeft)+parseFloat(R.paddingRight),D=parseFloat(R.paddingTop)+parseFloat(R.paddingBottom),B=40,x=((T=n.compareMode)!=null?T:"off")!=="off",w=(e.clientWidth-W-B)/(x?2:1),E=e.clientHeight-D-B;if(w<=0||E<=0)return 1;let S=(_=Nr[m()])!=null?_:Nr.desktop;return Math.min(w/S.w,E/S.h,1)}function u(){var D,B,x;i=f();let R=Math.max(ol,Math.min(rl,p()));d=R;let W=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let w of W){let E=(D=w.dataset.device)!=null?D:"desktop",S=(B=Nr[E])!=null?B:Nr.desktop;w.style.width=`${S.w*R}px`,w.style.height=`${S.h*R}px`,E==="mobile"&&(w.style.borderRadius=`${32*R}px`);let T=w.querySelector("iframe");T&&(T.style.width=`${S.w}px`,T.style.height=`${S.h}px`,T.style.transformOrigin="top left",T.style.transition="none",T.style.transform=`scale(${R})`)}(x=n.onScaleChange)==null||x.call(n,R)}function C(){var R;(R=n.onBeforeDestroy)==null||R.call(n);for(let W of o)W.destroy();for(let W of r)W();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var ae,Ee,ye,Oe;if(a)return;C();let R=++l,W=Fg(n),D=m(),B=((ae=n.compareMode)!=null?ae:"off")!=="off",x=((Ee=n.scene)!=null?Ee:"conversation")==="minimized",w=(ye=n.widgetCssPath)!=null?ye:"/widget-dist/widget.css",E=(Oe=n.buildSrcdoc)!=null?Oe:il,S=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",T=we=>`<div class="${S}" data-mount-id="${we.mountId}" data-device="${D}" data-shell-mode="${we.shellMode}">
194
+ ${B?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ea(we.label)}</span></div>`:""}
195
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${we.mountId}"></iframe>
196
+ </div>`,_=B?`<div class="preview-compare-grid">${W.map(we=>`<div class="preview-compare-cell">${T(we)}</div>`).join("")}</div>`:`<div class="preview-single">${T(W[0])}</div>`;n.morphContainer?n.morphContainer(e,_):e.innerHTML=_,u();let U=v(),Y=0,he=U.length,fe=()=>{var K,pe,G,ve,ce;if(a||R!==l)return;for(let ne of U){let Se=ne.dataset.mountId;if(!Se||!ne.contentDocument)continue;let ze=W.find(Te=>Te.mountId===Se);if(!ze)continue;let te=()=>{},re=bn(ze.config),ie=re?(()=>{var Q;let Te=(Q=ne.contentDocument)==null?void 0:Q.getElementById(`preview-content-${Se}`);if(!Te)return null;let ue=Pg(Te,ze.config),Ue=ne.contentDocument.createElement("div");Ue.id=Se,Ue.style.height="100%",Ue.style.display="flex",Ue.style.flexDirection="column",Ue.style.flex="1",Ue.style.minHeight="0",ue.host.appendChild(Ue);let Be=()=>ue.syncWidgetState(st.getState()),me=te;return te=()=>{ue.destroy(),me()},Ue.__syncDock=Be,Ue.__hostLayout=ue,Ue})():ne.contentDocument.getElementById(Se);if(!ie)continue;let st=Mg(ie,ze.config);if(o.push(st),re&&ie.__syncDock){let Te=ie.__syncDock,ue=st.on("widget:opened",Te),Ue=st.on("widget:closed",Te),Be=te;te=()=>{ue(),Ue(),Be()},Te()}r.push(te),x&&st.close()}if(((K=n.scene)!=null?K:"conversation")==="artifact"||(ve=(G=(pe=n.config)==null?void 0:pe.features)==null?void 0:G.artifacts)!=null&&ve.enabled)for(let ne of o)ne.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`});(Ae=n.onAfterMount)==null||Ae.call(n,{iframes:U,controllers:[...o]})};for(let xe of U){let J=xe.dataset.mountId;if(!J)continue;let Ie=D.find(X=>X.mountId===J);Ie&&(xe.addEventListener("load",()=>{K++,K>=fe&&ae()},{once:!0}),xe.srcdoc=E(J,Ie.shellMode,un(Ie.config),x))}fe===0&&ae()}function R(){var F;if(a)return;let I=Tf(n);if(o.length!==I.length){L();return}if(I.some(B=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!v||v.dataset.shellMode!==B.shellMode})){L();return}o.forEach((B,v)=>{var x;B.update(I[v].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&B.close()});for(let B of I){let v=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);v&&nl(v,B.shellMode)}(F=n.onAfterUpdate)==null||F.call(n,{iframes:S(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||p()}),s.observe(e)),L(),{update(I){if(a)return;let D=I.device!==void 0&&I.device!==n.device||I.scene!==void 0&&I.scene!==n.scene||I.compareMode!==void 0&&I.compareMode!==n.compareMode||I.widgetCssPath!==void 0&&I.widgetCssPath!==n.widgetCssPath;n={...n,...I},D?L():R()},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(I){a||(n={...n,zoom:I},p())}}}function Io(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Aa={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"},Cy=/^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 Sy(e){return Cy.test(e)}function Dr(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=Aa[t];if(n)return n;let o=Xr(t);if(oi(o)||o==="transparent"||Sy(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(Aa).slice(0,6).join(", ")}).`)}var il=Ds.map(e=>e==="gray"?"neutral":e),Ay={...Object.fromEntries(il.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Ta(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Ay[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 ka(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 Ea(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 Ty={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ma(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Ty[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function La(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=ti(t);return ni(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function ll(e){for(let t of Er){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 Ef=ll("typo-font-family"),Ca=ll("typo-font-size"),Sa=ll("typo-font-weight"),al=ll("typo-line-height"),Mf={...Ef,monospace:Ef.mono},Lf={...Ca,small:Ca.sm,md:Ca.base,medium:Ca.base,large:Ca.lg},If={...Sa,400:Sa.normal,500:Sa.medium,600:Sa.semibold,700:Sa.bold},Rf={...al,"1.25":al.tight,"1.5":al.normal,"1.625":al.relaxed};function Pf(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 Wf="theme.palette.radius.";function ky(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Er)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(Wf)&&typeof i=="string"&&(s[a.slice(Wf.length)]=i);e[r[1]]=s}return e}var ps=ky(),Bf=["sm","md","lg","xl","full"];function dl(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?dl(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?dl(e,r,n,o+1):null}function cl(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 us(e){return e.replace(/^role-/,"")}function Ey(e){for(let[t,n]of Object.entries(ps))if(Bf.every(o=>e[o]===n[o]))return t;return"custom"}function pr(e){var o,r;let t={};for(let s of Bf)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of rr)n[us(s.roleId)]=ii(a=>e.get(`theme.${a}`),s);return{brand:{primary:Sc(e.get("theme.palette.colors.primary.500")),secondary:Sc(e.get("theme.palette.colors.secondary.500")),accent:Sc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:cl(e,"theme.semantic.typography.fontFamily"),fontSize:cl(e,"theme.semantic.typography.fontSize"),fontWeight:cl(e,"theme.semantic.typography.fontWeight"),lineHeight:cl(e,"theme.semantic.typography.lineHeight")},roundness:{style:Ey(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Sc(e){return typeof e=="string"&&e!==""?e:null}var ds=[{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 Hf(e){let t=new Set(e.targets.map(n=>n.path));return ds.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var My={AA:4.5,AAA:7};function Ly(e){return Math.round(e*100)/100}function Iy(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=kr.indexOf(a[2]),l=null,m=1/0;return kr.forEach((u,g)=>{let p=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof p!="string"||!(p.startsWith("#")||p.startsWith("rgb")))&&Hs(p,n)>=o){let w=d>=0?Math.abs(g-d):g;w<m&&(m=w,l=`palette.colors.${i}.${u}`)}}),l}function ms(e,t="AA",n="both",o){let r=My[t],s=n==="both"?["light","dark"]:[n],a=o?ds.filter(d=>o.includes(d.key)):ds,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let u=dl(e,m.fg,l),g=dl(e,m.bg,l);if(!u||!g)continue;let p=Ly(Hs(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 L=Iy(e,m.fg,g,r,l);L&&(S.suggestion=L)}i.push(S)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Fr(e,t,n="light",o="AA"){return t.length===0?[]:ms(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var ln={};for(let e of rr){let t=us(e.roleId);ln[t]=e,ln[e.roleId]=e}Object.assign(ln,{surface:ln.surfaces,background:ln.surfaces,backgrounds:ln.surfaces,user:ln["user-messages"],"user-message":ln["user-messages"],assistant:ln["assistant-messages"],"assistant-message":ln["assistant-messages"],actions:ln["primary-actions"],buttons:ln["primary-actions"],composer:ln.input,links:ln["links-focus"],focus:ln["links-focus"],border:ln.borders,dividers:ln.borders,scroll:ln["scroll-to-bottom"]});function Ry(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=ln[t];if(!n){let o=rr.map(r=>us(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Df(){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 li)t(n.sections);for(let n of Gs)t(n.sections);return e}var Py={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Wy={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Ac=["bottom-right","bottom-left","top-right","top-left"],Tc=["bubble","flat","minimal"],By={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function kc(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,x,E=n)=>{let C={};return(E==="light"||E==="both")&&(C[`theme.${v}`]=x),(E==="dark"||E==="both")&&(C[`darkTheme.${v}`]=x),C},a=v=>{if(n==="both")return v;let x={};for(let[E,C]of Object.entries(v))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(x[E]=C);return x},i=()=>n==="dark"?"dark":"light",d=(v,x=[])=>Io({ok:!0,summary:pr(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),E={summary:pr(e),availableRoles:rr.map(C=>({role:us(C.roleId),helper:C.helper})),availableFamilies:il,presets:Qr.map(C=>{var k;return{id:C.id,name:C.name,description:C.description,tags:(k=C.tags)!=null?k:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=Df()),E.fieldIndex=Array.from(o.values()).map(C=>{var k;return{id:C.id,path:C.path,type:C.type,label:C.label,options:(k=C.options)==null?void 0:k.map(O=>O.value)}})),Io(E)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let x=r(v),E=["primary","secondary","accent"],C={},k={};for(let U of E){if(x[U]===void 0)continue;let K=Dr(x[U]);k[U]=K;let fe=si(K);for(let ae of kr){let ge=fe[ae];ge!==void 0&&Object.assign(C,s(`palette.colors.${U}.${ae}`,ge))}}if(Object.keys(k).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(C);let O=Fr(e,["primary-button","user-message"],i());return d(k,O)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:il},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let x=r(v),E=Ry(x.role),C=Ta(x.family,!0),k=ka(x.intensity),O=a(js(C,k,E)),U=Object.keys(O).length;e.setBatch(O);let K=Fr(e,Hf(E),i());return d({role:us(E.roleId),family:C,intensity:k,tokensWritten:U},K)}},{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),E={},C={},k=(O,U)=>{var fe;if(x[O]===void 0)return;let K=Pf(x[O],U,O);C[O]=(fe=K.split(".").pop())!=null?fe:K,Object.assign(E,s(`semantic.typography.${O}`,K))};if(k("fontFamily",Mf),k("fontSize",Lf),k("fontWeight",If),k("lineHeight",Rf),Object.keys(C).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),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),E={},C={};if(x.style!==void 0){let k=Ma(x.style);C.style=k;for(let[O,U]of Object.entries(ps[k]))Object.assign(E,s(`palette.radius.${O}`,U))}if(x.radius!==void 0){let k=r(x.radius),O={};for(let U of["sm","md","lg","xl","full"]){if(k[U]===void 0)continue;let K=La(k[U]);O[U]=K,Object.assign(E,s(`palette.radius.${U}`,K))}C.radius=O}if(Object.keys(E).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(E),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),E={};if(x.scheme!==void 0){let C=Ea(x.scheme);e.set("colorScheme",C),E.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,E.editTarget=C}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Io({ok:!0,summary:pr(e),warnings:[],applied:E,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:x}=r(v),E=ci(String(x!=null?x:""));if(!E){let U=Qr.map(K=>K.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${U}.`)}let C=nn(E.theme,{validate:!1}),k={...e.getConfig()};E.darkTheme&&(k.darkTheme=nn(E.darkTheme,{validate:!1})),E.toolCall&&(k.toolCall=E.toolCall),e.setFullConfig(k,C);let O=Fr(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.name}},O)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Ac},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:Tc}},additionalProperties:!1}},additionalProperties:!1},execute(v){var U,K,fe;let x=r(v),E={},C={};if(x.launcherPosition!==void 0){let ae=String(x.launcherPosition);if(!Ac.includes(ae))throw new Error(`Unknown launcherPosition "${ae}". Valid: ${Ac.join(", ")}.`);E["launcher.position"]=ae,C.launcherPosition=ae}let k=r(x.features);for(let[ae,ge]of Object.entries(Py))k[ae]!==void 0&&(E[ge]=!!k[ae],(U=C.features)!=null||(C.features={}),C.features[ae]=!!k[ae]);let O=r(x.layout);for(let[ae,ge]of Object.entries(Wy))if(O[ae]!==void 0)if(ae==="messageStyle"){let le=String(O[ae]);if(!Tc.includes(le))throw new Error(`Unknown messageStyle "${le}". Valid: ${Tc.join(", ")}.`);E[ge]=le,(K=C.layout)!=null||(C.layout={}),C.layout[ae]=le}else E[ge]=!!O[ae],(fe=C.layout)!=null||(C.layout={}),C.layout[ae]=!!O[ae];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),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),E={},C={};for(let[k,O]of Object.entries(By))x[k]!==void 0&&(E[O]=String(x[k]),C[k]=String(x[k]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let k=x.suggestions.filter(O=>typeof O=="string");E.suggestionChips=k,C.suggestions=k}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(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 O;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=Df());let E={},C=[];for(let U of x){let K=r(U),fe=String((O=K.field)!=null?O:"");try{let ae=o.get(fe),ge=ae?ae.path:fe;if(!ae&&!/^(theme|darkTheme)\.|\./.test(ge))throw new Error(`Unknown field "${fe}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let le=Hy(ae,K.value);if(ae&&ge.startsWith("theme.")){let ye=s(ge.slice(6),le);Object.assign(E,ye),C.push({field:fe,resolvedPath:Object.keys(ye),ok:!0})}else E[ge]=le,C.push({field:fe,resolvedPath:ge,ok:!0})}catch(ae){C.push({field:fe,ok:!1,error:ae.message})}}let k=C.filter(U=>U.ok);return Object.keys(E).length>0&&e.setBatch(E),Io({ok:k.length>0,summary:pr(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),E=x.level==="AAA"?"AAA":"AA",C=x.variant==="light"||x.variant==="dark"?x.variant:"both",k=ms(e,E,C);return Io({level:k.level,passing:k.checks.length-k.failures.length,total:k.checks.length,checks:k.checks,failures:k.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action: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 Io({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Hy(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(Dr(t)):Dr(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}0&&(module.exports={ADVANCED_TOKENS_SECTION,ALL_ROLES,ALL_TABS,BRAND_PALETTE_SECTION,BUILT_IN_PRESETS,COLORS_SECTIONS,COLOR_FAMILIES,COMPONENTS_SECTIONS,COMPONENT_COLOR_SECTIONS,COMPONENT_SHAPE_SECTIONS,CONFIGURE_SECTIONS,CONFIGURE_SUB_GROUPS,CONTRAST_PAIRS,CSS_NAMED_COLORS,DEVICE_DIMENSIONS,HOME_SUGGESTION_CHIPS,INTERFACE_ROLES_SECTION,MOCK_BROWSER_CONTENT,MOCK_WORKSPACE_CONTENT,PALETTE_SECTION,PREVIEW_STORAGE_ADAPTER,RADIUS_PRESETS,ROLE_ASSISTANT_MESSAGES,ROLE_BORDERS,ROLE_FAMILIES,ROLE_FAMILY_LABELS,ROLE_HEADER,ROLE_INPUT,ROLE_INTENSITIES,ROLE_LINKS_FOCUS,ROLE_PRIMARY_ACTIONS,ROLE_SCROLL_TO_BOTTOM,ROLE_SURFACES,ROLE_USER_MESSAGES,SEMANTIC_COLORS_SECTION,SHADE_KEYS,SHELL_STYLE_ID,STATUS_COLORS_SECTION,STATUS_PALETTE_SECTION,STYLE_SECTIONS,STYLE_SECTIONS_V2,THEME_EDITOR_PRESETS,THEME_SECTION,ThemeEditorState,ZOOM_MAX,ZOOM_MIN,appendPreviewTranscriptEntry,applySceneConfig,applyShellTheme,buildPreviewConfig,buildPreviewConfigWithMessages,buildShellCss,buildSrcdoc,buildSummary,buildTranscriptStreamFrames,coerceColor,coerceFamily,coerceIntensity,coerceRadius,coerceRoundnessStyle,coerceScheme,convertFromPx,convertToPx,createPreviewMessages,createPreviewTranscriptEntry,createThemeEditorTools,createThemePreview,detectRoleAssignment,escapeHtml,findSection,formatCssValue,generateColorScale,getPreviewTranscriptPresetLabel,getShellPalette,getThemeEditorPreset,hexToHsl,hslToHex,isValidHex,normalizeColorValue,paletteColorPath,parseCssValue,presetStreamsText,quickContrastWarnings,resolveRoleAssignment,resolveThemeColorPath,rgbToHex,runContrastChecks,scopeSection,tokenRefDisplayName,toolResult,wcagContrastRatio});
204
+ - Resizable panes`});(ce=n.onAfterMount)==null||ce.call(n,{iframes:U,controllers:[...o]})};for(let we of U){let K=we.dataset.mountId;if(!K)continue;let pe=W.find(G=>G.mountId===K);pe&&(we.addEventListener("load",()=>{Y++,Y>=he&&fe()},{once:!0}),we.srcdoc=E(K,pe.shellMode,bn(pe.config),w))}he===0&&fe()}function I(){var D;if(a)return;let R=Fg(n);if(o.length!==R.length){M();return}if(R.some(B=>{let x=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!x||x.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,x)=>{var w;B.update(R[x].config),((w=n.scene)!=null?w:"conversation")==="minimized"&&B.close()});for(let B of R){let x=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);x&&al(x,B.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(e)),M(),{update(R){if(a)return;let W=R.device!==void 0&&R.device!==n.device||R.scene!==void 0&&R.scene!==n.scene||R.compareMode!==void 0&&R.compareMode!==n.compareMode||R.widgetCssPath!==void 0&&R.widgetCssPath!==n.widgetCssPath;n={...n,...R},W?M():I()},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(R){a||(n={...n,zoom:R},u())}}}function Ho(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Ia={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"},Dy=/^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 Fy(e){return Dy.test(e)}function _r(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=Ia[t];if(n)return n;let o=ts(t);if(si(o)||o==="transparent"||Fy(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(Ia).slice(0,6).join(", ")}).`)}var pl=$s.map(e=>e==="gray"?"neutral":e),Oy={...Object.fromEntries(pl.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Ra(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Oy[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 Pa(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 Wa(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 Ny={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ba(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Ny[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Ha(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=oi(t);return ri(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function ul(e){for(let t of Ir){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 Ng=ul("typo-font-family"),Ma=ul("typo-font-size"),La=ul("typo-font-weight"),dl=ul("typo-line-height"),_g={...Ng,monospace:Ng.mono},Vg={...Ma,small:Ma.sm,md:Ma.base,medium:Ma.base,large:Ma.lg},$g={...La,400:La.normal,500:La.medium,600:La.semibold,700:La.bold},Ug={...dl,"1.25":dl.tight,"1.5":dl.normal,"1.625":dl.relaxed};function zg(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 qg="theme.palette.radius.";function _y(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Ir)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(qg)&&typeof i=="string"&&(s[a.slice(qg.length)]=i);e[r[1]]=s}return e}var bs=_y(),jg=["sm","md","lg","xl","full"];function gl(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?gl(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?gl(e,r,n,o+1):null}function ml(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 ys(e){return e.replace(/^role-/,"")}function Vy(e){for(let[t,n]of Object.entries(bs))if(jg.every(o=>e[o]===n[o]))return t;return"custom"}function gr(e){var o,r;let t={};for(let s of jg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of ir)n[ys(s.roleId)]=ci(a=>e.get(`theme.${a}`),s);return{brand:{primary:Mc(e.get("theme.palette.colors.primary.500")),secondary:Mc(e.get("theme.palette.colors.secondary.500")),accent:Mc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:ml(e,"theme.semantic.typography.fontFamily"),fontSize:ml(e,"theme.semantic.typography.fontSize"),fontWeight:ml(e,"theme.semantic.typography.fontWeight"),lineHeight:ml(e,"theme.semantic.typography.lineHeight")},roundness:{style:Vy(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Mc(e){return typeof e=="string"&&e!==""?e:null}var hs=[{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 Kg(e){let t=new Set(e.targets.map(n=>n.path));return hs.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var $y={AA:4.5,AAA:7};function Uy(e){return Math.round(e*100)/100}function zy(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=Lr.indexOf(a[2]),l=null,m=1/0;return Lr.forEach((p,f)=>{let u=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof u!="string"||!(u.startsWith("#")||u.startsWith("rgb")))&&Vs(u,n)>=o){let C=d>=0?Math.abs(f-d):f;C<m&&(m=C,l=`palette.colors.${i}.${p}`)}}),l}function vs(e,t="AA",n="both",o){let r=$y[t],s=n==="both"?["light","dark"]:[n],a=o?hs.filter(d=>o.includes(d.key)):hs,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let p=gl(e,m.fg,l),f=gl(e,m.bg,l);if(!p||!f)continue;let u=Uy(Vs(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 M=zy(e,m.fg,f,r,l);M&&(v.suggestion=M)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Vr(e,t,n="light",o="AA"){return t.length===0?[]:vs(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 mn={};for(let e of ir){let t=ys(e.roleId);mn[t]=e,mn[e.roleId]=e}Object.assign(mn,{surface:mn.surfaces,background:mn.surfaces,backgrounds:mn.surfaces,user:mn["user-messages"],"user-message":mn["user-messages"],assistant:mn["assistant-messages"],"assistant-message":mn["assistant-messages"],actions:mn["primary-actions"],buttons:mn["primary-actions"],composer:mn.input,links:mn["links-focus"],focus:mn["links-focus"],border:mn.borders,dividers:mn.borders,scroll:mn["scroll-to-bottom"]});function qy(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=mn[t];if(!n){let o=ir.map(r=>ys(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Gg(){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 di)t(n.sections);for(let n of ea)t(n.sections);return e}var jy={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Ky={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Lc=["bottom-right","bottom-left","top-right","top-left"],Ic=["bubble","flat","minimal"],Gy={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Rc(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=x=>x&&typeof x=="object"?x:{},s=(x,w,E=n)=>{let S={};return(E==="light"||E==="both")&&(S[`theme.${x}`]=w),(E==="dark"||E==="both")&&(S[`darkTheme.${x}`]=w),S},a=x=>{if(n==="both")return x;let w={};for(let[E,S]of Object.entries(x))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(w[E]=S);return w},i=()=>n==="dark"?"dark":"light",d=(x,w=[])=>Ho({ok:!0,summary:gr(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),E={summary:gr(e),availableRoles:ir.map(S=>({role:ys(S.roleId),helper:S.helper})),availableFamilies:pl,presets:os.map(S=>{var T;return{id:S.id,name:S.name,description:S.description,tags:(T=S.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 w==="full"&&(o!=null||(o=Gg()),E.fieldIndex=Array.from(o.values()).map(S=>{var T;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(T=S.options)==null?void 0:T.map(_=>_.value)}})),Ho(E)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(x){let w=r(x),E=["primary","secondary","accent"],S={},T={};for(let U of E){if(w[U]===void 0)continue;let Y=_r(w[U]);T[U]=Y;let he=ii(Y);for(let fe of Lr){let ae=he[fe];ae!==void 0&&Object.assign(S,s(`palette.colors.${U}.${fe}`,ae))}}if(Object.keys(T).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let _=Vr(e,["primary-button","user-message"],i());return d(T,_)}},{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:pl},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(x){let w=r(x),E=qy(w.role),S=Ra(w.family,!0),T=Pa(w.intensity),_=a(Js(S,T,E)),U=Object.keys(_).length;e.setBatch(_);let Y=Vr(e,Kg(E),i());return d({role:ys(E.roleId),family:S,intensity:T,tokensWritten:U},Y)}},{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),E={},S={},T=(_,U)=>{var he;if(w[_]===void 0)return;let Y=zg(w[_],U,_);S[_]=(he=Y.split(".").pop())!=null?he:Y,Object.assign(E,s(`semantic.typography.${_}`,Y))};if(T("fontFamily",_g),T("fontSize",Vg),T("fontWeight",$g),T("lineHeight",Ug),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(x){let w=r(x),E={},S={};if(w.style!==void 0){let T=Ba(w.style);S.style=T;for(let[_,U]of Object.entries(bs[T]))Object.assign(E,s(`palette.radius.${_}`,U))}if(w.radius!==void 0){let T=r(w.radius),_={};for(let U of["sm","md","lg","xl","full"]){if(T[U]===void 0)continue;let Y=Ha(T[U]);_[U]=Y,Object.assign(E,s(`palette.radius.${U}`,Y))}S.radius=_}if(Object.keys(E).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(E),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(x){let w=r(x),E={};if(w.scheme!==void 0){let S=Wa(w.scheme);e.set("colorScheme",S),E.scheme=S}if(w.editTarget!==void 0){let S=String(w.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${w.editTarget}". Valid: light, dark, both.`);n=S,E.editTarget=S}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Ho({ok:!0,summary:gr(e),warnings:[],applied:E,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(x){let{presetId:w}=r(x),E=pi(String(w!=null?w:""));if(!E){let U=os.map(Y=>Y.id).join(", ");throw new Error(`Unknown preset "${w}". Valid presets: ${U}.`)}let S=an(E.theme,{validate:!1}),T={...e.getConfig()};E.darkTheme&&(T.darkTheme=an(E.darkTheme,{validate:!1})),E.toolCall&&(T.toolCall=E.toolCall),e.setFullConfig(T,S);let _=Vr(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.name}},_)}},{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:Lc},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:Ic}},additionalProperties:!1}},additionalProperties:!1},execute(x){var U,Y,he;let w=r(x),E={},S={};if(w.launcherPosition!==void 0){let fe=String(w.launcherPosition);if(!Lc.includes(fe))throw new Error(`Unknown launcherPosition "${fe}". Valid: ${Lc.join(", ")}.`);E["launcher.position"]=fe,S.launcherPosition=fe}let T=r(w.features);for(let[fe,ae]of Object.entries(jy))T[fe]!==void 0&&(E[ae]=!!T[fe],(U=S.features)!=null||(S.features={}),S.features[fe]=!!T[fe]);let _=r(w.layout);for(let[fe,ae]of Object.entries(Ky))if(_[fe]!==void 0)if(fe==="messageStyle"){let Ee=String(_[fe]);if(!Ic.includes(Ee))throw new Error(`Unknown messageStyle "${Ee}". Valid: ${Ic.join(", ")}.`);E[ae]=Ee,(Y=S.layout)!=null||(S.layout={}),S.layout[fe]=Ee}else E[ae]=!!_[fe],(he=S.layout)!=null||(S.layout={}),S.layout[fe]=!!_[fe];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(x){let w=r(x),E={},S={};for(let[T,_]of Object.entries(Gy))w[T]!==void 0&&(E[_]=String(w[T]),S[T]=String(w[T]));if(w.suggestions!==void 0){if(!Array.isArray(w.suggestions))throw new Error("`suggestions` must be an array of strings.");let T=w.suggestions.filter(_=>typeof _=="string");E.suggestionChips=T,S.suggestions=T}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(x){var _;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=Gg());let E={},S=[];for(let U of w){let Y=r(U),he=String((_=Y.field)!=null?_:"");try{let fe=o.get(he),ae=fe?fe.path:he;if(!fe&&!/^(theme|darkTheme)\.|\./.test(ae))throw new Error(`Unknown field "${he}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let Ee=Yy(fe,Y.value);if(fe&&ae.startsWith("theme.")){let ye=s(ae.slice(6),Ee);Object.assign(E,ye),S.push({field:he,resolvedPath:Object.keys(ye),ok:!0})}else E[ae]=Ee,S.push({field:he,resolvedPath:ae,ok:!0})}catch(fe){S.push({field:he,ok:!1,error:fe.message})}}let T=S.filter(U=>U.ok);return Object.keys(E).length>0&&e.setBatch(E),Ho({ok:T.length>0,summary:gr(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),E=w.level==="AAA"?"AAA":"AA",S=w.variant==="light"||w.variant==="dark"?w.variant:"both",T=vs(e,E,S);return Ho({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(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 Ho({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${w}". Valid: undo, redo, reset, export.`)}}}]}function Yy(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(_r(t)):_r(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}0&&(module.exports={ADVANCED_TOKENS_SECTION,ALL_ROLES,ALL_TABS,BRAND_PALETTE_SECTION,BUILT_IN_PRESETS,COLORS_SECTIONS,COLOR_FAMILIES,COMPONENTS_SECTIONS,COMPONENT_COLOR_SECTIONS,COMPONENT_SHAPE_SECTIONS,CONFIGURE_SECTIONS,CONFIGURE_SUB_GROUPS,CONTRAST_PAIRS,CSS_NAMED_COLORS,DEVICE_DIMENSIONS,HOME_SUGGESTION_CHIPS,INTERFACE_ROLES_SECTION,MOCK_BROWSER_CONTENT,MOCK_WORKSPACE_CONTENT,PALETTE_SECTION,PREVIEW_STORAGE_ADAPTER,RADIUS_PRESETS,ROLE_ASSISTANT_MESSAGES,ROLE_BORDERS,ROLE_FAMILIES,ROLE_FAMILY_LABELS,ROLE_HEADER,ROLE_INPUT,ROLE_INTENSITIES,ROLE_LINKS_FOCUS,ROLE_PRIMARY_ACTIONS,ROLE_SCROLL_TO_BOTTOM,ROLE_SURFACES,ROLE_USER_MESSAGES,SEMANTIC_COLORS_SECTION,SHADE_KEYS,SHELL_STYLE_ID,STATUS_COLORS_SECTION,STATUS_PALETTE_SECTION,STYLE_SECTIONS,STYLE_SECTIONS_V2,THEME_EDITOR_PRESETS,THEME_SECTION,ThemeEditorState,ZOOM_MAX,ZOOM_MIN,appendPreviewTranscriptEntry,applySceneConfig,applyShellTheme,buildPreviewConfig,buildPreviewConfigWithMessages,buildShellCss,buildSrcdoc,buildSummary,buildTranscriptStreamFrames,coerceColor,coerceFamily,coerceIntensity,coerceRadius,coerceRoundnessStyle,coerceScheme,convertFromPx,convertToPx,createPreviewMessages,createPreviewTranscriptEntry,createThemeEditorTools,createThemePreview,detectRoleAssignment,escapeHtml,findSection,formatCssValue,generateColorScale,getPreviewTranscriptPresetLabel,getShellPalette,getThemeEditorPreset,hexToHsl,hslToHex,isValidHex,normalizeColorValue,paletteColorPath,parseCssValue,presetStreamsText,quickContrastWarnings,resolveRoleAssignment,resolveThemeColorPath,rgbToHex,runContrastChecks,scopeSection,tokenRefDisplayName,toolResult,wcagContrastRatio});