@runtypelabs/persona 3.29.1 → 3.31.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 (68) hide show
  1. package/README.md +15 -2547
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
  5. package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +6 -6
  9. package/dist/codegen.js +4 -4
  10. package/dist/index.cjs +50 -50
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +164 -7
  13. package/dist/index.d.ts +164 -7
  14. package/dist/index.global.js +60 -60
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +49 -49
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js +2 -2
  19. package/dist/launcher.global.js.map +1 -1
  20. package/dist/plugin-kit.cjs +1 -0
  21. package/dist/plugin-kit.d.cts +98 -0
  22. package/dist/plugin-kit.d.ts +98 -0
  23. package/dist/plugin-kit.js +1 -0
  24. package/dist/smart-dom-reader.d.cts +157 -4
  25. package/dist/smart-dom-reader.d.ts +157 -4
  26. package/dist/theme-editor.cjs +40 -40
  27. package/dist/theme-editor.d.cts +161 -6
  28. package/dist/theme-editor.d.ts +161 -6
  29. package/dist/theme-editor.js +40 -40
  30. package/dist/theme-reference.cjs +1 -1
  31. package/dist/theme-reference.d.cts +2 -0
  32. package/dist/theme-reference.d.ts +2 -0
  33. package/dist/theme-reference.js +1 -1
  34. package/dist/widget.css +19 -0
  35. package/package.json +8 -2
  36. package/src/client.ts +6 -0
  37. package/src/components/approval-bubble.test.ts +320 -0
  38. package/src/components/approval-bubble.ts +190 -20
  39. package/src/components/launcher.ts +6 -3
  40. package/src/components/panel.ts +7 -1
  41. package/src/components/tool-bubble.test.ts +39 -0
  42. package/src/components/tool-bubble.ts +4 -0
  43. package/src/defaults.ts +14 -0
  44. package/src/generated/runtype-openapi-contract.ts +4 -0
  45. package/src/index-core.ts +1 -0
  46. package/src/plugin-kit.test.ts +230 -0
  47. package/src/plugin-kit.ts +294 -0
  48. package/src/plugins/types.ts +49 -2
  49. package/src/session.test.ts +161 -0
  50. package/src/session.ts +41 -3
  51. package/src/styles/widget.css +19 -0
  52. package/src/theme-editor/preview-utils.test.ts +10 -0
  53. package/src/theme-editor/preview-utils.ts +29 -1
  54. package/src/theme-editor/sections.test.ts +17 -0
  55. package/src/theme-editor/sections.ts +31 -0
  56. package/src/theme-reference.ts +2 -2
  57. package/src/types/theme.ts +2 -0
  58. package/src/types.ts +109 -2
  59. package/src/ui.approval-plugin.test.ts +204 -0
  60. package/src/ui.scroll.test.ts +383 -0
  61. package/src/ui.ts +539 -56
  62. package/src/utils/auto-follow.test.ts +91 -0
  63. package/src/utils/auto-follow.ts +68 -0
  64. package/src/utils/theme.test.ts +6 -2
  65. package/src/utils/theme.ts +0 -8
  66. package/src/utils/tokens.ts +6 -1
  67. package/src/webmcp-bridge.test.ts +66 -0
  68. 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 Mg=Object.create;var ii=Object.defineProperty;var Lg=Object.getOwnPropertyDescriptor;var Ig=Object.getOwnPropertyNames;var Rg=Object.getPrototypeOf,Pg=Object.prototype.hasOwnProperty;var Wg=(e,t)=>{for(var n in t)ii(e,n,{get:t[n],enumerable:!0})},Zu=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ig(t))!Pg.call(e,r)&&r!==n&&ii(e,r,{get:()=>t[r],enumerable:!(o=Lg(t,r))||o.enumerable});return e};var em=(e,t,n)=>(n=e!=null?Mg(Rg(e)):{},Zu(t||!e||!e.__esModule?ii(n,"default",{value:e,enumerable:!0}):n,e)),Bg=e=>Zu(ii({},"__esModule",{value:!0}),e);var Mv={};Wg(Mv,{ADVANCED_TOKENS_SECTION:()=>zl,ALL_ROLES:()=>fr,ALL_TABS:()=>yi,BRAND_PALETTE_SECTION:()=>_l,BUILT_IN_PRESETS:()=>ql,COLORS_SECTIONS:()=>vm,COLOR_FAMILIES:()=>hi,COMPONENTS_SECTIONS:()=>Dl,COMPONENT_COLOR_SECTIONS:()=>Hl,COMPONENT_SHAPE_SECTIONS:()=>Bl,CONFIGURE_SECTIONS:()=>Ol,CONFIGURE_SUB_GROUPS:()=>da,CONTRAST_PAIRS:()=>ks,CSS_NAMED_COLORS:()=>Oa,DEVICE_DIMENSIONS:()=>Kr,HOME_SUGGESTION_CHIPS:()=>Wc,INTERFACE_ROLES_SECTION:()=>$l,MOCK_BROWSER_CONTENT:()=>Hc,MOCK_WORKSPACE_CONTENT:()=>Dc,PALETTE_SECTION:()=>bm,PREVIEW_STORAGE_ADAPTER:()=>Pc,RADIUS_PRESETS:()=>Es,ROLE_ASSISTANT_MESSAGES:()=>na,ROLE_BORDERS:()=>ia,ROLE_FAMILIES:()=>Qs,ROLE_FAMILY_LABELS:()=>mm,ROLE_HEADER:()=>ea,ROLE_INPUT:()=>sa,ROLE_INTENSITIES:()=>To,ROLE_LINKS_FOCUS:()=>aa,ROLE_PRIMARY_ACTIONS:()=>oa,ROLE_SCROLL_TO_BOTTOM:()=>ra,ROLE_SURFACES:()=>Zs,ROLE_USER_MESSAGES:()=>ta,SEMANTIC_COLORS_SECTION:()=>ym,SHADE_KEYS:()=>Dr,SHELL_STYLE_ID:()=>Ba,STATUS_COLORS_SECTION:()=>Ul,STATUS_PALETTE_SECTION:()=>Vl,STYLE_SECTIONS:()=>Fr,STYLE_SECTIONS_V2:()=>xm,THEME_EDITOR_PRESETS:()=>ms,THEME_SECTION:()=>Nl,ThemeEditorState:()=>di,ZOOM_MAX:()=>ul,ZOOM_MIN:()=>pl,appendPreviewTranscriptEntry:()=>lg,applySceneConfig:()=>bl,applyShellTheme:()=>fl,buildPreviewConfig:()=>xr,buildPreviewConfigWithMessages:()=>dg,buildShellCss:()=>ml,buildSrcdoc:()=>gl,buildSummary:()=>wr,buildTranscriptStreamFrames:()=>cg,coerceColor:()=>Gr,coerceFamily:()=>Na,coerceIntensity:()=>_a,coerceRadius:()=>Ua,coerceRoundnessStyle:()=>$a,coerceScheme:()=>Va,convertFromPx:()=>dm,convertToPx:()=>cm,createPreviewMessages:()=>Oc,createPreviewTranscriptEntry:()=>hl,createThemeEditorTools:()=>$c,createThemePreview:()=>ug,detectRoleAssignment:()=>bi,escapeHtml:()=>Ha,findSection:()=>Cm,formatCssValue:()=>ui,generateColorScale:()=>gi,getPreviewTranscriptPresetLabel:()=>ig,getShellPalette:()=>Bc,getThemeEditorPreset:()=>vi,hexToHsl:()=>Il,hslToHex:()=>Rl,isValidHex:()=>mi,normalizeColorValue:()=>ps,paletteColorPath:()=>pm,parseCssValue:()=>pi,presetStreamsText:()=>Fc,quickContrastWarnings:()=>Yr,resolveRoleAssignment:()=>la,resolveThemeColorPath:()=>Pl,rgbToHex:()=>fi,runContrastChecks:()=>Ls,scopeSection:()=>Sm,tokenRefDisplayName:()=>um,toolResult:()=>_o,wcagContrastRatio:()=>Js});module.exports=Bg(Mv);var tm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Xs(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];tm(s)&&tm(r)?n[o]=Xs(s,r):n[o]=r}return n}var go="min(440px, calc(100vw - 24px))",li="440px",It={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:go,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function nm(e,t){if(!(!e&&!t))return e?t?Xs(e,t):e:t}function om(e){var t,n,o,r,s,a,i,d,l,f,u,g,m,C,v,M,I,R,P,D,W;return e?{...It,...e,theme:nm(It.theme,e.theme),darkTheme:nm(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(t=It.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=It.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var le,J,se,ye,be,K,ae,Re,oe,ee;let w=(le=It.features)==null?void 0:le.artifacts,x=(J=e.features)==null?void 0:J.artifacts,E=(se=It.features)==null?void 0:se.scrollToBottom,S=(ye=e.features)==null?void 0:ye.scrollToBottom,k=(be=It.features)==null?void 0:be.scrollBehavior,V=(K=e.features)==null?void 0:K.scrollBehavior,z=(ae=It.features)==null?void 0:ae.streamAnimation,Y=(Re=e.features)==null?void 0:Re.streamAnimation,he=(oe=It.features)==null?void 0:oe.askUserQuestion,me=(ee=e.features)==null?void 0:ee.askUserQuestion,de=w===void 0&&x===void 0?void 0:{...w,...x,layout:{...w==null?void 0:w.layout,...x==null?void 0:x.layout}},Ee=E===void 0&&S===void 0?void 0:{...E,...S},xe=k===void 0&&V===void 0?void 0:{...k,...V},De=z===void 0&&Y===void 0?void 0:{...z,...Y},Ae=he===void 0&&me===void 0?void 0:{...he,...me,styles:{...he==null?void 0:he.styles,...me==null?void 0:me.styles}};return{...It.features,...e.features,...Ee!==void 0?{scrollToBottom:Ee}:{},...xe!==void 0?{scrollBehavior:xe}:{},...de!==void 0?{artifacts:de}:{},...De!==void 0?{streamAnimation:De}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(a=It.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=It.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(f=It.layout)==null?void 0:f.messages)==null?void 0:u.avatar,...(m=(g=e.layout)==null?void 0:g.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=It.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=It.layout)==null?void 0:R.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...It.markdown,...e.markdown,options:{...(D=It.markdown)==null?void 0:D.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var Hg={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"}},Dg={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"}},Fg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:go,maxWidth:li,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 cs(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."))?cs(e,o):o}function rm(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=cs(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 Og(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 sm(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]=sm(s,r):n[o]=r}return n}function Ng(e,t){return t?sm(e,t):e}function mn(e,t={}){var r,s,a,i,d,l,f,u,g,m,C,v,M;let n={palette:Hg,semantic:Dg,components:Fg},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,...(f=e==null?void 0:e.semantic)==null?void 0:f.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,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.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:Ng(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=Og(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 am(e){var v,M,I,R,P,D,W,w,x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae,le,J,se,ye,be,K,ae,Re,oe,ee,re,it,lt,Le,pe,Je,Be,j,fe,tt,Mt,te,qe,Fn,Dt,an,oo,Mo,F,ue,Fe,Ke,_e,$e,ot,Pt,Kt,Jt,G,xt,st,Se,ce,et,Qt,Gt,In,vn,gt,Lt,Qe,qt,ln,Cn,Sn,yn,Lo,At,Un,zn,Vo,yo,wt,Cr,Io,Sr,On,Xr,Zo,$o,Tt,qn,jn,Rn,Rt,ro,so,Kn,er,Uo,tr,Gn,Ft,Pn,ao,nr,zo,or,Ro,Yn,vo,bt,Zt,en,Xn,rr;let t=rm(e),n={};for(let[we,io]of Object.entries(t)){let lo=we.replace(/\./g,"-");n[`--persona-${lo}`]=io.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"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w: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"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(V=n["--persona-components-voice-recording-background"])!=null?V:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z: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"]=(me=n["--persona-components-approval-requested-border"])!=null?me:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(de=n["--persona-components-approval-requested-text"])!=null?de: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"]=(xe=n["--persona-components-approval-approve-background"])!=null?xe:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(De=n["--persona-components-approval-deny-background"])!=null?De:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(le=n["--persona-components-attachment-image-border"])!=null?le: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"]=(se=n["--persona-semantic-typography-fontSize"])!=null?se:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(be=n["--persona-semantic-typography-lineHeight"])!=null?be: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"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(ae=n["--persona-palette-radius-md"])!=null?ae:"0.375rem",n["--persona-radius-lg"]=(Re=n["--persona-palette-radius-lg"])!=null?Re:"0.5rem",n["--persona-radius-xl"]=(oe=n["--persona-palette-radius-xl"])!=null?oe:"0.75rem",n["--persona-radius-full"]=(ee=n["--persona-palette-radius-full"])!=null?ee:"9999px",n["--persona-launcher-radius"]=(it=(re=n["--persona-components-launcher-borderRadius"])!=null?re:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-launcher-bg"]=(lt=n["--persona-components-launcher-background"])!=null?lt:n["--persona-primary"],n["--persona-launcher-fg"]=(Le=n["--persona-components-launcher-foreground"])!=null?Le:n["--persona-text-inverse"],n["--persona-launcher-border"]=(pe=n["--persona-components-launcher-border"])!=null?pe:n["--persona-border"],n["--persona-button-primary-bg"]=(Je=n["--persona-components-button-primary-background"])!=null?Je:n["--persona-primary"],n["--persona-button-primary-fg"]=(Be=n["--persona-components-button-primary-foreground"])!=null?Be:n["--persona-text-inverse"],n["--persona-button-radius"]=(fe=(j=n["--persona-components-button-primary-borderRadius"])!=null?j:n["--persona-palette-radius-full"])!=null?fe:"9999px",n["--persona-panel-radius"]=(Mt=(tt=n["--persona-components-panel-borderRadius"])!=null?tt:n["--persona-radius-xl"])!=null?Mt:"0.75rem",n["--persona-panel-border"]=(te=n["--persona-components-panel-border"])!=null?te:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Fn=(qe=n["--persona-components-panel-shadow"])!=null?qe:n["--persona-palette-shadows-xl"])!=null?Fn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Dt=n["--persona-components-launcher-shadow"])!=null?Dt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(oo=(an=n["--persona-components-input-borderRadius"])!=null?an:n["--persona-radius-lg"])!=null?oo:"0.5rem",n["--persona-message-user-radius"]=(F=(Mo=n["--persona-components-message-user-borderRadius"])!=null?Mo:n["--persona-radius-lg"])!=null?F:"0.5rem",n["--persona-message-assistant-radius"]=(Fe=(ue=n["--persona-components-message-assistant-borderRadius"])!=null?ue:n["--persona-radius-lg"])!=null?Fe:"0.5rem",n["--persona-header-bg"]=(Ke=n["--persona-components-header-background"])!=null?Ke:n["--persona-surface"],n["--persona-header-border"]=(_e=n["--persona-components-header-border"])!=null?_e:n["--persona-divider"],n["--persona-header-icon-bg"]=($e=n["--persona-components-header-iconBackground"])!=null?$e:n["--persona-primary"],n["--persona-header-icon-fg"]=(ot=n["--persona-components-header-iconForeground"])!=null?ot: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"]=(Kt=n["--persona-components-header-subtitleForeground"])!=null?Kt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Jt=n["--persona-components-header-actionIconForeground"])!=null?Jt:n["--persona-muted"];let o=(G=e.components)==null?void 0:G.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(xt=e.components)==null?void 0:xt.introCard;n["--persona-intro-card-bg"]=(st=n["--persona-components-introCard-background"])!=null?st: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"]=(Qt=(et=r==null?void 0:r.shadow)!=null?et:n["--persona-components-introCard-shadow"])!=null?Qt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Gt=n["--persona-components-input-background"])!=null?Gt:n["--persona-surface"],n["--persona-input-placeholder"]=(In=n["--persona-components-input-placeholder"])!=null?In:n["--persona-text-muted"],n["--persona-message-user-bg"]=(vn=n["--persona-components-message-user-background"])!=null?vn:n["--persona-accent"],n["--persona-message-user-text"]=(gt=n["--persona-components-message-user-text"])!=null?gt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Lt=n["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qe=n["--persona-components-message-assistant-background"])!=null?Qe:n["--persona-surface"],n["--persona-message-assistant-text"]=(qt=n["--persona-components-message-assistant-text"])!=null?qt:n["--persona-text"],n["--persona-message-assistant-border"]=(ln=n["--persona-components-message-assistant-border"])!=null?ln:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Cn=n["--persona-components-message-assistant-shadow"])!=null?Cn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(yn=(Sn=n["--persona-components-scrollToBottom-background"])!=null?Sn:n["--persona-button-primary-bg"])!=null?yn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(At=(Lo=n["--persona-components-scrollToBottom-foreground"])!=null?Lo:n["--persona-button-primary-fg"])!=null?At:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Un=n["--persona-components-scrollToBottom-border"])!=null?Un:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(zn=n["--persona-components-scrollToBottom-size"])!=null?zn:"40px",n["--persona-scroll-to-bottom-radius"]=(wt=(yo=(Vo=n["--persona-components-scrollToBottom-borderRadius"])!=null?Vo:n["--persona-button-radius"])!=null?yo:n["--persona-radius-full"])!=null?wt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Io=(Cr=n["--persona-components-scrollToBottom-shadow"])!=null?Cr:n["--persona-palette-shadows-sm"])!=null?Io:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Sr=n["--persona-components-scrollToBottom-padding"])!=null?Sr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(On=n["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Zo=(Xr=n["--persona-components-scrollToBottom-fontSize"])!=null?Xr:n["--persona-palette-typography-fontSize-sm"])!=null?Zo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($o=n["--persona-components-scrollToBottom-iconSize"])!=null?$o:"14px",n["--persona-tool-bubble-shadow"]=(Tt=n["--persona-components-toolBubble-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(qn=n["--persona-components-reasoningBubble-shadow"])!=null?qn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(jn=n["--persona-components-composer-shadow"])!=null?jn:"none",n["--persona-md-inline-code-bg"]=(Rn=n["--persona-components-markdown-inlineCode-background"])!=null?Rn:n["--persona-container"],n["--persona-md-inline-code-color"]=(Rt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Rt:n["--persona-text"],n["--persona-md-link-color"]=(so=(ro=n["--persona-components-markdown-link-foreground"])!=null?ro:n["--persona-accent"])!=null?so:"#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"]=(Kn=n["--persona-components-markdown-codeBlock-background"])!=null?Kn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(er=n["--persona-components-markdown-codeBlock-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Uo=n["--persona-components-markdown-codeBlock-textColor"])!=null?Uo:"inherit",n["--persona-md-table-header-bg"]=(tr=n["--persona-components-markdown-table-headerBackground"])!=null?tr:n["--persona-container"],n["--persona-md-table-border-color"]=(Gn=n["--persona-components-markdown-table-borderColor"])!=null?Gn:n["--persona-border"],n["--persona-md-hr-color"]=(Ft=n["--persona-components-markdown-hr-color"])!=null?Ft:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Pn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Pn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(ao=n["--persona-components-markdown-blockquote-background"])!=null?ao:"transparent",n["--persona-md-blockquote-text-color"]=(nr=n["--persona-components-markdown-blockquote-textColor"])!=null?nr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zo=n["--persona-components-collapsibleWidget-container"])!=null?zo:n["--persona-surface"],n["--cw-surface"]=(or=n["--persona-components-collapsibleWidget-surface"])!=null?or:n["--persona-surface"],n["--cw-border"]=(Ro=n["--persona-components-collapsibleWidget-border"])!=null?Ro:n["--persona-border"],n["--persona-message-border"]=(Yn=n["--persona-components-message-border"])!=null?Yn:n["--persona-border"];let f=e.components,u=f==null?void 0:f.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=f==null?void 0:f.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let m=f==null?void 0:f.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let C=f==null?void 0:f.artifact;if(C!=null&&C.toolbar){let we=C.toolbar;we.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=we.iconHoverColor),we.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=we.iconHoverBackground),we.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=we.iconPadding),we.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=we.iconBorderRadius),we.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=we.iconBorder),we.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=we.toggleGroupGap),we.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=we.toggleBorderRadius),we.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=we.copyBackground),we.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=we.copyBorder),we.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=we.copyColor),we.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=we.copyBorderRadius),we.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=we.copyPadding),we.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=we.copyMenuBackground,n["--persona-dropdown-bg"]=(vo=n["--persona-dropdown-bg"])!=null?vo:we.copyMenuBackground),we.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,n["--persona-dropdown-border"]=(bt=n["--persona-dropdown-border"])!=null?bt:we.copyMenuBorder),we.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,n["--persona-dropdown-shadow"]=(Zt=n["--persona-dropdown-shadow"])!=null?Zt:we.copyMenuShadow),we.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(en=n["--persona-dropdown-radius"])!=null?en:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Xn=n["--persona-dropdown-item-hover-bg"])!=null?Xn:we.copyMenuItemHoverBackground),we.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(C!=null&&C.tab){let we=C.tab;we.background&&(n["--persona-artifact-tab-bg"]=we.background),we.activeBackground&&(n["--persona-artifact-tab-active-bg"]=we.activeBackground),we.activeBorder&&(n["--persona-artifact-tab-active-border"]=we.activeBorder),we.borderRadius&&(n["--persona-artifact-tab-radius"]=we.borderRadius),we.textColor&&(n["--persona-artifact-tab-color"]=we.textColor),we.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=we.hoverBackground),we.listBackground&&(n["--persona-artifact-tab-list-bg"]=we.listBackground),we.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=we.listBorderColor),we.listPadding&&(n["--persona-artifact-tab-list-padding"]=we.listPadding)}if(C!=null&&C.pane){let we=C.pane;if(we.toolbarBackground){let io=(rr=cs(e,we.toolbarBackground))!=null?rr:we.toolbarBackground;n["--persona-artifact-toolbar-bg"]=io}}return n}var _g={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"}}},im=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"},Vg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ml()},$g=e=>Vg(e),Ug=e=>mn(e),zg=e=>{var n;let t=mn(void 0,{validate:!1});return mn({...e,palette:{...t.palette,colors:{..._g.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ci=e=>{let t=$g(e),n=im(e==null?void 0:e.theme),o=im(e==null?void 0:e.darkTheme);return t==="dark"?zg(Xs(n!=null?n:{},o!=null?o:{})):Ug(n)},qg=e=>am(e),ds=(e,t)=>{let n=ci(t),o=qg(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},lm=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 Ll(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Hr(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]:Hr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var di=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...It,...n}:n!=null?n:It,this.theme=mn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?Ll(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Ll((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):Ll(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=Hr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:mn();this.config={...this.config,darkTheme:Hr(s,r,n)}}else this.config=Hr(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=Hr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:mn();this.config={...this.config,darkTheme:Hr(l,d,i)},o=!0}else this.config=Hr(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=mn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=mn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...It},this.theme=mn(),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=mn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function pi(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 ui(e,t){return t==="rem"?`${e}rem`:`${e}px`}function cm(e,t){return t==="rem"?e*16:e}function dm(e,t){return t==="rem"?e/16:e}function ps(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 mi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function fi(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("%"),f=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(f)?Math.max(0,Math.min(255,Math.round(l?f/100*255:f))):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 Js(e,t){let n=s=>{var l;let a=ps(s),i=a.startsWith("rgb")?(l=fi(a))!=null?l:"#000000":a,d=[1,3,5].map(f=>{let u=parseInt(i.slice(f,f+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 Il(e){var g;let t=ps(e),n=t.startsWith("rgb")?(g=fi(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,f=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:f,l:d}}function Rl(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 f=u=>{let g=Math.round((u+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${f(i)}${f(d)}${f(l)}`}function gi(e){let{h:t,s:n,l:o}=Il(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]=Rl(t,l,d)}return a}var Dr=["50","100","200","300","400","500","600","700","800","900","950"],hi=["primary","secondary","accent","gray","success","warning","error","info"];function pm(e,t){return`palette.colors.${e}.${t}`}function Pl(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.")?Pl(e,`theme.${o}`,n+1):"#cbd5e1"}function um(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 To=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Qs=["primary","secondary","accent","gray"],mm={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Zs={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:To,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},ea={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:To,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"}]},ta={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:To,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},na={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:To,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},oa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:To,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"}]},ra={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:To,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},sa={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:To,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"}]},aa={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:To,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"}]},ia={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:To,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},fr=[Zs,ea,ta,na,oa,ra,sa,aa,ia];function la(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=jg(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function jg(e,t,n,o){let r=t==="solid";if(o==="role-header")return Kg(e,r,n);if(o==="role-input")return Gg(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 Kg(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 Gg(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 Yg=/^palette\.colors\.(\w+)\.(\d+)$/;function bi(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(Yg);if(!r)return null;let s=r[1],a=Qs.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let f=la(a,l,t);if(t.targets.every(g=>{var C;return String((C=e(g.path))!=null?C:"")===f[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var Xg={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"}]}]},Jg={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},Qg={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Zg={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)"}]}]},eh={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"}]}]},th={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"}}]},nh={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)"}]},oh={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"}]}]},Fr=[Jg,Qg,eh,Zg,Xg,th,nh,oh];function gm(){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:hi.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 hm={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"}}]},bm=gm(),ym=hm,vm=[gm(),hm],rh={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:go},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:li},{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"}]}]},sh={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"}]}]},ah={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"}]}]},ih={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"}]}]},lh={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"}]}]},ch={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"}}]},dh={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"}}]},ph={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"}}]},uh={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"}}]},mh={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"}]},us=[{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"}],Wl="0 5px 15px rgba(15, 23, 42, 0.08)",fm=[{value:Wl,label:"Default"},...us],fh={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:us},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:us},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:us},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:us},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:Wl,options:fm},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:Wl,options:fm},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:us}]},Bl=[rh,sh,ah,ih,lh,fh],Hl=[ch,dh,ph,uh,mh],Dl=[...Bl,...Hl],Fl=1024*1024,gh=["What can you help me with?","Tell me about your features","How does this work?"],ca={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 hh(e){return Number(e)*Fl}function bh(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/Fl)):String(t):"10"}function yh(e){var t;return(t=ca[String(e)])!=null?t:ca.images}function vh(e){let t=Array.isArray(e)?e:ca.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(ca)){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 xh={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"}]},wh={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:gh}]},Ch={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:""}]},Sh={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}]},Ah={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"}]}]},Th={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"}]}]},kh={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:go},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},Eh={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:""}]},Mh={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"}]},Lh={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"}]},Ih={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"}]},Rh={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"}]},Ph={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:""}]},Wh={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)}]},Bh={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*Fl,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:bh,parseValue:hh},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:ca.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:vh,parseValue:yh}]},Hh={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"}]}]},Dh={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}]},Fh={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"}]}]},Oh={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}]},Nh={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}]},da=[{label:"Content",sections:[xh,wh]},{label:"Layout",sections:[Ch,Sh,Ah,Th]},{label:"Widget",sections:[kh,Eh,Mh,Lh,Ih,Rh]},{label:"Features",sections:[Ph,Wh,Bh,Hh,Dh]},{label:"Developer",collapsedByDefault:!0,sections:[Fh,Oh,Nh]}],Ol=da.flatMap(e=>e.sections),Nl={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"}]}]},_l={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"}]},Vl={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"}]},$l={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:Zs},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:ea},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:ta},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:na},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:oa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:ra},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:sa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:aa},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:ia}]},Ul={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"}}]},zl={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},xm=[Nl,_l,Vl,$l,Ul,zl],yi=[{id:"style",label:"Style",sections:Fr},{id:"design-system",label:"Design System",sections:Dl},{id:"configure",label:"Configure",sections:Ol}];function wm(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function _h(e,t,n){return{...e,id:`${n}-${e.id}`,path:wm(e.path,t)}}function Cm(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Sm(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=>_h(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])=>[wm(d,t),l]))}))}}var ql=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],ms=[...ql];function vi(e){return ms.find(t=>t.id===e)}var Am=require("marked"),Vh=e=>{if(e)return e},jl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Am.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=Vh(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},xi=e=>e?jl({markedOptions:e.options,renderer:e.renderer}):jl(),Xv=jl();var pa=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Tm=em(require("dompurify"),1),$h={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"]},Uh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,zh=()=>{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:")&&!Uh.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,$h)},wi=e=>e===!1?null:typeof e=="function"?e:zh();var Or="webmcp:",Kl=new Map,km=e=>{var t;Kl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Kl.set(n.name,o)}},Gl=e=>Kl.get(Lm(e)),Ci={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Mm(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}:${qh(t.join(""))}`}function Em(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 qh(e){let t=Em(e,0).toString(36),n=Em(e,2654435761).toString(36);return`${t}.${n}`}var Si=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Ci.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}km(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=Kh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return ko("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return ko(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=Lm(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return ko(`Failed to read WebMCP registry: ${v}`)}km(a);let i=a.find(C=>C.name===s);if(!i)return ko(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return ko(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return ko("Aborted by cancel()");let d=Gl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return ko("User declined the tool call.");if(o!=null&&o.aborted)return ko("Aborted by cancel()");let f=new AbortController,u=!1,g=setTimeout(()=>{u=!0,f.abort()},this.timeoutMs),m=()=>f.abort();o&&(o.aborted?f.abort():o.addEventListener("abort",m,{once:!0}));try{let C=await r.executeTool(i,Jh(n),{signal:f.signal});return Gh(C)}catch(C){if(u)return ko(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return ko("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return ko(v)}finally{clearTimeout(g),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ci.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ci.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Yh;try{return await n(t)}catch(r){return Ci.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>jh(t,o))}},Lm=e=>e.startsWith(Or)?e.slice(Or.length):e,fs=e=>e.startsWith(Or),jh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Kh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Gh=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:Qh(t)}]}},ko=e=>({isError:!0,content:[{type:"text",text:e}]}),Yh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Xh(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)},Xh=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)}},Jh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Qh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var gs=require("partial-json"),Im=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),hs=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)}},Zh=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`},Rm=e=>e.status==="complete"?Zh(e):e.status==="pending"?"Waiting":"",eb=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 Pm=e=>e.status==="complete"?eb(e):"Using tool...",Ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ma=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 Ai(t)},Ti=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 Ai(t)},Yl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=ma(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ki=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&ua(o,n.slice(s,a.index),[]),a[1]!==void 0?ua(o,a[1],["bold"]):a[2]!==void 0?ua(o,a[2],["italic"]):a[3]!==void 0&&ua(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ua(o,n.slice(s),[]),o},ua=(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})},tb=()=>{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()=>{}}},Nr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Wm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Bm=()=>{var t;let e=tb();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)}},Hm=()=>{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,gs.parse)(n,gs.STR|gs.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Im(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Im(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Dm=()=>{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 Ei=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 nb="https://api.runtype.com/v1/dispatch",Mi="https://api.runtype.com";function ob(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 Xl=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 rb(e){switch(e){case"json":return Hm;case"regex-json":return Bm;case"xml":return Dm;default:return Wm}}var Fm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function sb(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=Fm(n);if(!Fm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Nr(e);return Nr(t)!==null&&a===null?t:e}var fa=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:nb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:rb(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 Si(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$/,""))||Mi}/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$/,""))||Mi}/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),f=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Xl).map(D=>{var W,w,x;return{id:D.id,role:D.role,content:(x=(w=(W=D.contentParts)!=null?W:D.llmContent)!=null?w:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,m=!!(g&&g.length>0),C=m?Mm(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&v&&this.lastSentClientToolsFingerprint===C,I=!1,R=null,P;for(let D=0;;D++){let w={...u,...m&&(I||!M)&&g?{clientTools:g}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),P.status===409&&D===0&&m){let x=await P.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=x!=null?x:{error:"Chat request failed"}}break}if(!P.ok){let D=R!=null?R:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(P.status===429){let w=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let W=new Error(D.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!P.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(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Mi}/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,f;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Mi}/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:(f=o==null?void 0:o.streamResponse)!=null?f:!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(Xl).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(Xl).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=f=>{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(),...f!==void 0&&{partId:f}};return o.current=u,r(u),u},l=f=>o.current?o.current:d(f);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 f=l(i.partId);i.partId!==void 0&&!f.partId&&(f.partId=i.partId),f.content+=i.text,r(f)}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 Dt,an,oo,Mo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,f=F=>{let ue=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,Fe=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ke=F.tools?F.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...F,reasoning:ue,toolCall:Fe,tools:Ke}},u=F=>{if(F.role!=="assistant"||F.variant)return!0;let ue=Array.isArray(F.contentParts)&&F.contentParts.length>0,Fe=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||ue||Fe||!!F.stopReason},g=F=>{u(F)&&n({type:"message",message:f(F)})},m=null,C=null,v={current:null},M={current:null},I=!1,R=new Map,P=new Map,D=new Map,W=new Map,w={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},E=(F,ue,Fe="")=>`${F}::${ue}::${Fe}`,S=(F,ue)=>`${F}::${ue}::`,k=(F,ue,Fe,Ke)=>{let _e=E(F,ue,Fe),$e=D.get(_e);if($e)return $e;let ot=Fe?`-${Fe}`:"",Pt={id:`nested-${F}-${ue}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Fe?{partId:Fe}:{},agentMetadata:{executionId:Ke,parentToolId:F,parentStepId:ue}};return D.set(_e,Pt),g(Pt),Pt},V=F=>{if(F==null)return null;try{return String(F)}catch{return null}},z=F=>{var ue,Fe,Ke,_e,$e;return V(($e=(_e=(Ke=(Fe=(ue=F.stepId)!=null?ue:F.step_id)!=null?Fe:F.step)!=null?Ke:F.parentId)!=null?_e:F.flowStepId)!=null?$e:F.flow_step_id)},Y=F=>{var ue,Fe,Ke,_e,$e,ot,Pt;return V((Pt=(ot=($e=(_e=(Ke=(Fe=(ue=F.callId)!=null?ue:F.call_id)!=null?Fe:F.requestId)!=null?Ke:F.request_id)!=null?_e:F.toolCallId)!=null?$e:F.tool_call_id)!=null?ot:F.stepId)!=null?Pt:F.step_id)},he=o,me=!1,de=()=>{if(m)return m;let F;return!me&&he?(F=he,me=!0):he&&M.current?F=`${he}_${M.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(m),m},Ee=(F,ue)=>{w.lastId=ue,F&&w.byStep.set(F,ue)},xe=(F,ue)=>{var $e;let Fe=($e=F.reasoningId)!=null?$e:F.id,Ke=z(F);if(Fe){let ot=String(Fe);return Ee(Ke,ot),ot}if(Ke){let ot=w.byStep.get(Ke);if(ot)return w.lastId=ot,ot}if(w.lastId&&!ue)return w.lastId;if(!ue)return null;let _e=`reason-${l()}`;return Ee(Ke,_e),_e},De=F=>{let ue=R.get(F);if(ue)return ue;let Fe={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return R.set(F,Fe),g(Fe),Fe},Ae=(F,ue)=>{x.lastId=ue,F&&x.byCall.set(F,ue)},le=new Set,J=new Map,se=new Set,ye=new Map,be=F=>{if(!F)return!1;let ue=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},K=(F,ue)=>{var $e;let Fe=($e=F.toolId)!=null?$e:F.id,Ke=Y(F);if(Fe){let ot=String(Fe);return Ae(Ke,ot),ot}if(Ke){let ot=x.byCall.get(Ke);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ue)return x.lastId;if(!ue)return null;let _e=`tool-${l()}`;return Ae(Ke,_e),_e},ae=F=>{let ue=P.get(F);if(ue)return ue;let Fe={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return P.set(F,Fe),g(Fe),Fe},Re=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let ue=Number(F);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Fe=Date.parse(F);if(!Number.isNaN(Fe))return Fe}return Date.now()},oe=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ee=new Map,re=new Map,it=new Map,lt=new Map,Le=null,pe=(F,ue,Fe)=>{var Pt;let Ke=it.get(F);Ke||(Ke=[],it.set(F,Ke));let _e=0,$e=Ke.length;for(;_e<$e;){let Kt=_e+$e>>>1;Ke[Kt].seq<ue?_e=Kt+1:$e=Kt}((Pt=Ke[_e])==null?void 0:Pt.seq)===ue?Ke[_e]={seq:ue,text:Fe}:Ke.splice(_e,0,{seq:ue,text:Fe});let ot="";for(let Kt=0;Kt<Ke.length;Kt++)ot+=Ke[Kt].text;return ot},Je=(F,ue)=>{let Fe=oe(ue),Ke=re.get(F.id),_e=sb(Ke,Fe);F.rawContent=_e;let $e=ee.get(F.id),ot=xt=>{var Se;let st=(Se=F.content)!=null?Se:"";xt.trim()!==""&&(st.trim().length===0||xt.startsWith(st)||xt.trimStart().startsWith(st.trim()))&&(F.content=xt)},Pt=()=>{var xt;if($e){let st=(xt=$e.close)==null?void 0:xt.call($e);st instanceof Promise&&st.catch(()=>{})}ee.delete(F.id),re.delete(F.id),F.streaming=!1,g(F)};if(!$e){ot(Fe),Pt();return}let Kt=Nr(_e);if(Kt!==null&&Kt.trim()!==""){ot(Kt),Pt();return}let Jt=xt=>{var ce;let st=typeof xt=="string"?xt:(ce=xt==null?void 0:xt.text)!=null?ce:null;if(st!==null&&st.trim()!=="")return st;let Se=$e.getExtractedText();return Se!==null&&Se.trim()!==""?Se:Fe},G;try{G=$e.processChunk(_e)}catch{ot(Fe),Pt();return}if(G instanceof Promise){G.then(xt=>{ot(Jt(xt)),Pt()}).catch(()=>{ot(Fe),Pt()});return}ot(Jt(G)),Pt()},Be=[],j=!1,fe,tt=()=>{j||(j=!0,queueMicrotask(()=>{j=!1,fe()}))},Mt=new Ei((F,ue)=>{Be.push({payloadType:F,payload:ue}),tt()}),te=null,qe=new Map,Fn=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(fe=()=>{var F,ue,Fe,Ke,_e,$e,ot,Pt,Kt,Jt,G,xt,st,Se,ce,et,Qt,Gt,In,vn,gt,Lt,Qe,qt,ln,Cn,Sn,yn,Lo,At,Un,zn,Vo,yo,wt,Cr,Io,Sr,On,Xr,Zo,$o,Tt,qn,jn,Rn,Rt,ro,so,Kn,er,Uo,tr,Gn,Ft,Pn,ao,nr,zo,or,Ro,Yn,vo,bt,Zt,en,Xn,rr,we,io,lo,$,Po,qo,jo,Wo,xo,Is,Jn,Qn,wo,Co,Ar,Ko,An,Bo,Jr,Tr,Qr,za,Zr,qa,es,vt,Rs,co,Nn,ja,Ka,ts,Go,Ps,sr,Ws,Bs,Hs,Ds,_n,ns,Ho,Do,Fs,Ga,Os,Ns,kr,Ya,Xa,Ja,Qa,Sl,Er,ar,Za,_s,ir,ei,Vs,lr,$s,ti,Yo,ni,cr,Ot,os,rs,Us;for(let po=0;po<Be.length;po++){let Ge=Be[po].payloadType,T=Be[po].payload;if(Ge==="reason_start"){let U=(F=xe(T,!0))!=null?F:`reason-${l()}`,B=De(U);B.reasoning=(ue=B.reasoning)!=null?ue:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Ke=B.reasoning.startedAt)!=null?Ke:Re((Fe=T.startedAt)!=null?Fe:T.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",g(B)}else if(Ge==="reason_delta"||Ge==="reason_chunk"){let U=($e=(_e=xe(T,!1))!=null?_e:xe(T,!0))!=null?$e:`reason-${l()}`,B=De(U);B.reasoning=(ot=B.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Kt=B.reasoning.startedAt)!=null?Kt:Re((Pt=T.startedAt)!=null?Pt:T.timestamp);let Z=(xt=(G=(Jt=T.reasoningText)!=null?Jt:T.text)!=null?G:T.delta)!=null?xt:"";if(Z&&T.hidden!==!0){let ie=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ie!==void 0){let X=pe(U,ie,String(Z));B.reasoning.chunks=[X]}else B.reasoning.chunks.push(String(Z))}if(B.reasoning.status=T.done?"complete":"streaming",T.done){B.reasoning.completedAt=Re((st=T.completedAt)!=null?st:T.timestamp);let ie=(Se=B.reasoning.startedAt)!=null?Se:Date.now();B.reasoning.durationMs=Math.max(0,((ce=B.reasoning.completedAt)!=null?ce:Date.now())-ie)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(Ge==="reason_complete"){let U=(Qt=(et=xe(T,!1))!=null?et:xe(T,!0))!=null?Qt:`reason-${l()}`,B=R.get(U);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=Re((Gt=T.completedAt)!=null?Gt:T.timestamp);let ie=(In=B.reasoning.startedAt)!=null?In:Date.now();B.reasoning.durationMs=Math.max(0,((vn=B.reasoning.completedAt)!=null?vn:Date.now())-ie),B.streaming=!1,g(B)}let Z=z(T);Z&&w.byStep.delete(Z)}else if(Ge==="tool_start"){let U=(gt=K(T,!0))!=null?gt:`tool-${l()}`,B=(Lt=T.toolName)!=null?Lt:T.name;if(be(B)){le.add(U);continue}let Z=ae(U),ie=(Qe=Z.toolCall)!=null?Qe:{id:U,status:"pending"};ie.name=B!=null?B:ie.name,ie.status="running",T.args!==void 0?ie.args=T.args:T.parameters!==void 0&&(ie.args=T.parameters),ie.startedAt=(ln=ie.startedAt)!=null?ln:Re((qt=T.startedAt)!=null?qt:T.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,Z.toolCall=ie,Z.streaming=!0;let X=T.agentContext;(X||T.executionId)&&(Z.agentMetadata={executionId:(Cn=X==null?void 0:X.executionId)!=null?Cn:T.executionId,iteration:(Sn=X==null?void 0:X.iteration)!=null?Sn:T.iteration}),g(Z)}else if(Ge==="tool_chunk"||Ge==="tool_delta"){let U=(Lo=(yn=K(T,!1))!=null?yn:K(T,!0))!=null?Lo:`tool-${l()}`;if(le.has(U))continue;let B=ae(U),Z=(At=B.toolCall)!=null?At:{id:U,status:"running"};Z.startedAt=(zn=Z.startedAt)!=null?zn:Re((Un=T.startedAt)!=null?Un:T.timestamp);let ie=(wt=(yo=(Vo=T.text)!=null?Vo:T.delta)!=null?yo:T.message)!=null?wt:"";ie&&(Z.chunks=(Cr=Z.chunks)!=null?Cr:[],Z.chunks.push(String(ie))),Z.status="running",B.toolCall=Z,B.streaming=!0;let X=T.agentContext;(X||T.executionId)&&(B.agentMetadata=(On=B.agentMetadata)!=null?On:{executionId:(Io=X==null?void 0:X.executionId)!=null?Io:T.executionId,iteration:(Sr=X==null?void 0:X.iteration)!=null?Sr:T.iteration}),g(B)}else if(Ge==="tool_complete"){let U=(Zo=(Xr=K(T,!1))!=null?Xr:K(T,!0))!=null?Zo:`tool-${l()}`;if(le.has(U)){le.delete(U);continue}let B=ae(U),Z=($o=B.toolCall)!=null?$o:{id:U,status:"running"};Z.status="complete",T.result!==void 0&&(Z.result=T.result),typeof T.duration=="number"&&(Z.duration=T.duration),Z.completedAt=Re((Tt=T.completedAt)!=null?Tt:T.timestamp);let ie=(qn=T.duration)!=null?qn:T.executionTime;if(typeof ie=="number")Z.durationMs=ie;else{let Ne=(jn=Z.startedAt)!=null?jn:Date.now();Z.durationMs=Math.max(0,((Rn=Z.completedAt)!=null?Rn:Date.now())-Ne)}B.toolCall=Z,B.streaming=!1;let X=T.agentContext;(X||T.executionId)&&(B.agentMetadata=(so=B.agentMetadata)!=null?so:{executionId:(Rt=X==null?void 0:X.executionId)!=null?Rt:T.executionId,iteration:(ro=X==null?void 0:X.iteration)!=null?ro:T.iteration}),g(B);let Pe=Y(T);Pe&&x.byCall.delete(Pe)}else if(Ge==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,B=(Kn=U!=null?U:T.toolId)!=null?Kn:`local-${l()}`,Z=ae(B),ie=T.toolName,X=fs(ie),Pe=(er=Z.toolCall)!=null?er:{id:B,status:"pending"};Pe.name=ie,Pe.args=T.parameters,Pe.status=X?"running":"complete",Pe.chunks=(Uo=Pe.chunks)!=null?Uo:[],Pe.startedAt=(Gn=Pe.startedAt)!=null?Gn:Re((tr=T.startedAt)!=null?tr:T.timestamp),X?(Pe.completedAt=void 0,Pe.duration=void 0,Pe.durationMs=void 0):Pe.completedAt=(Ft=Pe.completedAt)!=null?Ft:Pe.startedAt,Z.toolCall=Pe,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(ao=T.executionId)!=null?ao:(Pn=Z.agentMetadata)==null?void 0:Pn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(Z)}else if(Ge==="text_start"){if((nr=T.toolContext)!=null&&nr.toolId)continue;let U=T.partId;if(U!==void 0&&M.current!==null&&U!==M.current){let B=m;B&&(B.streaming=!1,g(B),Le=B,m=null,I=!0)}U!==void 0&&(M.current=U)}else if(Ge==="text_end"){if((zo=T.toolContext)!=null&&zo.toolId)continue;let U=m;U&&(U.streaming=!1,g(U),Le=U,m=null,I=!0)}else if(Ge==="step_chunk"||Ge==="step_delta"){let U=T.stepType,B=T.executionType;if(U==="tool"||B==="context")continue;let Z=T.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Ro=(or=T.id)!=null?or:Z.stepId)!=null?Ro:`step-${l()}`),at=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Ze=`${Z.toolId}::${Ne}`,Ht=W.get(Ze);if(at!==""&&Ht!==void 0&&Ht!==""&&Ht!==at){let ct=D.get(E(Z.toolId,Ne,Ht));ct&&ct.streaming!==!1&&(ct.streaming=!1,g(ct))}at!==""&&W.set(Ze,at);let $t=k(Z.toolId,Ne,at,Z.executionId),_t=(Zt=(bt=(vo=(Yn=T.text)!=null?Yn:T.delta)!=null?vo:T.content)!=null?bt:T.chunk)!=null?Zt:"";_t&&($t.content+=String(_t),$t.streaming=!0,g($t)),T.isComplete&&($t.streaming=!1,g($t));continue}let ie=T.partId;if(ie!==void 0&&M.current!==null&&ie!==M.current){let Ne=m;Ne&&(Ne.streaming=!1,g(Ne),Le=Ne,m=null,I=!0)}ie!==void 0&&(M.current=ie);let X=ie!==void 0&&(en=lt.get(ie))!=null?en:de();ie!==void 0&&(X.partId||(X.partId=ie),lt.set(ie,X));let Pe=(io=(we=(rr=(Xn=T.text)!=null?Xn:T.delta)!=null?rr:T.content)!=null?we:T.chunk)!=null?io:"";if(Pe){let Ne=typeof T.seq=="number"?T.seq:void 0,at=ie!=null?ie:X.id,Ze=Ne!==void 0?pe(at,Ne,String(Pe)):((lo=re.get(X.id))!=null?lo:"")+Pe;X.rawContent=Ze,ee.has(X.id)||ee.set(X.id,this.createStreamParser());let Ht=ee.get(X.id),$t=Ze.trim().startsWith("{")||Ze.trim().startsWith("[");if($t&&re.set(X.id,Ze),Ht.__isPlainTextParser===!0){X.content=Ne!==void 0?Ze:X.content+Pe,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,g(X);continue}let ct=Ht.processChunk(Ze);if(ct instanceof Promise)ct.then(kt=>{var Tn;let Ue=typeof kt=="string"?kt:(Tn=kt==null?void 0:kt.text)!=null?Tn:null;if(Ue!==null&&Ue.trim()!=="")X.content=Ue,g(X);else if(!$t&&!Ze.trim().startsWith("<")){let fn=m,Ut=fn&&fn.id===X.id?fn:X;Ut.id===X.id&&(Ut.content=Ne!==void 0?Ze:Ut.content+Pe,re.delete(Ut.id),ee.delete(Ut.id),Ut.rawContent=void 0,g(Ut))}}).catch(()=>{X.content=Ne!==void 0?Ze:X.content+Pe,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,g(X)});else{let kt=typeof ct=="string"?ct:($=ct==null?void 0:ct.text)!=null?$:null;kt!==null&&kt.trim()!==""?(X.content=kt,g(X)):!$t&&!Ze.trim().startsWith("<")&&(X.content=Ne!==void 0?Ze:X.content+Pe,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,g(X))}}if(T.isComplete){let Ne=(qo=(Po=T.result)==null?void 0:Po.response)!=null?qo:X.content;if(Ne){let at=re.get(X.id),Ze=at!=null?at:oe(Ne);X.rawContent=Ze;let Ht=ee.get(X.id),$t=null,_t=!1;if(Ht&&($t=Ht.getExtractedText(),$t===null&&($t=Nr(Ze)),$t===null)){let ct=Ht.processChunk(Ze);ct instanceof Promise?(_t=!0,ct.then(kt=>{var Tn;let Ue=typeof kt=="string"?kt:(Tn=kt==null?void 0:kt.text)!=null?Tn:null;if(Ue!==null){let fn=m;fn&&fn.id===X.id&&(fn.content=Ue,fn.streaming=!1,ee.delete(fn.id),re.delete(fn.id),g(fn))}})):$t=typeof ct=="string"?ct:(jo=ct==null?void 0:ct.text)!=null?jo:null}if(!_t){$t!==null&&$t.trim()!==""?X.content=$t:re.has(X.id)||(X.content=oe(Ne));let ct=ee.get(X.id);if(ct){let kt=(Wo=ct.close)==null?void 0:Wo.call(ct);kt instanceof Promise&&kt.catch(()=>{}),ee.delete(X.id)}re.delete(X.id),X.streaming=!1,g(X)}}}}else if(Ge==="step_complete"){let U=T.stepType,B=T.executionType;if(U==="tool"||B==="context")continue;let Z=T.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Is=(xo=T.id)!=null?xo:Z.stepId)!=null?Is:"");if(Ne){let at=S(Z.toolId,Ne);for(let[Ze,Ht]of D)Ze.startsWith(at)&&Ht.streaming!==!1&&(Ht.streaming=!1,g(Ht));W.delete(`${Z.toolId}::${Ne}`)}continue}let ie=T.stopReason;if(I){if(m!==null){let Ze=m;ie&&(Ze.stopReason=ie),ee.delete(Ze.id),re.delete(Ze.id),Ze.streaming!==!1&&(Ze.streaming=!1,g(Ze))}let Ne=(Jn=T.result)==null?void 0:Jn.response,at=Le;at&&(ie&&(at.stopReason=ie),Ne!=null?Je(at,Ne):(ee.delete(at.id),re.delete(at.id))),Le=null;continue}let X=(Qn=T.result)==null?void 0:Qn.response,Pe=de();if(ie&&(Pe.stopReason=ie),X!=null){let Ne=ee.get(Pe.id),at=!1,Ze=!1;if(Ne){let Ht=Ne.getExtractedText(),$t=re.get(Pe.id),_t=$t!=null?$t:oe(X);if(Pe.rawContent=_t,Ht!==null&&Ht.trim()!=="")Pe.content=Ht,at=!0;else{let ct=Nr(_t);if(ct!==null)Pe.content=ct,at=!0;else{let kt=Ne.processChunk(_t);if(kt instanceof Promise)Ze=!0,kt.then(Ue=>{var fn;let Tn=typeof Ue=="string"?Ue:(fn=Ue==null?void 0:Ue.text)!=null?fn:null;if(Tn!==null&&Tn.trim()!==""){let Ut=m;Ut&&Ut.id===Pe.id&&(Ut.content=Tn,Ut.streaming=!1,ee.delete(Ut.id),re.delete(Ut.id),g(Ut))}else{let Ut=Ne.getExtractedText(),So=m;So&&So.id===Pe.id&&(Ut!==null&&Ut.trim()!==""?So.content=Ut:re.has(So.id)||(So.content=oe(X)),So.streaming=!1,ee.delete(So.id),re.delete(So.id),g(So))}});else{let Ue=typeof kt=="string"?kt:(wo=kt==null?void 0:kt.text)!=null?wo:null;if(Ue!==null&&Ue.trim()!=="")Pe.content=Ue,at=!0;else{let Tn=Ne.getExtractedText();Tn!==null&&Tn.trim()!==""&&(Pe.content=Tn,at=!0)}}}}}if(!Ze){if(!Pe.rawContent){let Ht=re.get(Pe.id);Pe.rawContent=Ht!=null?Ht:oe(X)}if(!at&&!re.has(Pe.id)&&(Pe.content=oe(X)),Ne){let Ht=(Co=Ne.close)==null?void 0:Co.call(Ne);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(Pe.id),re.delete(Pe.id),Pe.streaming=!1,g(Pe)}}else ee.delete(Pe.id),re.delete(Pe.id),Pe.streaming=!1,g(Pe)}else if(Ge==="flow_complete"){let U=(Ar=T.result)==null?void 0:Ar.response;if(I){if(m!==null){let B=m;ee.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}}else if(U!=null){let B=de(),Z=re.get(B.id),ie=Z!=null?Z:oe(U);B.rawContent=ie;let X=oe(U),Pe=ee.get(B.id);if(Pe){let Ze=Nr(ie);if(Ze!==null)X=Ze;else{let Ht=Pe.processChunk(ie);Ht instanceof Promise&&Ht.then(_t=>{var kt;let ct=typeof _t=="string"?_t:(kt=_t==null?void 0:_t.text)!=null?kt:null;ct!==null&&(B.content=ct,B.streaming=!1,g(B))});let $t=Pe.getExtractedText();$t!==null&&(X=$t)}}ee.delete(B.id),re.delete(B.id);let Ne=X!==B.content,at=B.streaming!==!1;Ne&&(B.content=X),B.streaming=!1,(Ne||at)&&g(B)}else if(m!==null){let B=m;ee.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}n({type:"status",status:"idle"})}else if(Ge==="agent_start")te={executionId:T.executionId,agentId:(Ko=T.agentId)!=null?Ko:"virtual",agentName:(An=T.agentName)!=null?An:"",status:"running",currentIteration:0,maxTurns:(Bo=T.maxTurns)!=null?Bo:1,startedAt:Re(T.startedAt)};else if(Ge==="agent_iteration_start"){if(te&&(te.currentIteration=T.iteration),Fn==="separate"&&T.iteration>1){let U=m;U&&(U.streaming=!1,g(U),qe.set(T.iteration-1,U),m=null)}}else if(Ge==="agent_turn_start")C=null;else if(Ge==="agent_turn_delta"){if(T.contentType==="text"){let U=de();U.content+=(Jr=T.delta)!=null?Jr:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:te==null?void 0:te.agentName},C=U,g(U)}else if(T.contentType==="thinking"){let U=(Tr=T.turnId)!=null?Tr:`agent-think-${T.iteration}`,B=De(U);B.reasoning=(Qr=B.reasoning)!=null?Qr:{id:U,status:"streaming",chunks:[]},B.reasoning.chunks.push((za=T.delta)!=null?za:""),B.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},g(B)}else if(T.contentType==="tool_input"){let U=(Zr=T.toolCallId)!=null?Zr:x.lastId;if(U){let B=P.get(U);B!=null&&B.toolCall&&(B.toolCall.chunks=(qa=B.toolCall.chunks)!=null?qa:[],B.toolCall.chunks.push((es=T.delta)!=null?es:""),g(B))}}}else if(Ge==="agent_turn_complete"){let U=T.turnId;if(U){let ie=R.get(U);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Re(T.completedAt);let X=(vt=ie.reasoning.startedAt)!=null?vt:Date.now();ie.reasoning.durationMs=Math.max(0,((Rs=ie.reasoning.completedAt)!=null?Rs:Date.now())-X),ie.streaming=!1,g(ie)}}let B=T.stopReason,Z=m!=null?m:C;if(B&&Z!==null){let ie=T.turnId;(!ie||((co=Z.agentMetadata)==null?void 0:co.turnId)===ie)&&(Z.stopReason=B,g(Z))}}else if(Ge==="agent_tool_start"){m&&(m.streaming=!1,g(m),m=null);let U=(Nn=T.toolCallId)!=null?Nn:`agent-tool-${l()}`;Ae(Y(T),U);let B=ae(U),Z=(ja=B.toolCall)!=null?ja:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(ts=(Ka=T.toolName)!=null?Ka:T.name)!=null?ts:Z.name,Z.status="running",T.parameters!==void 0&&(Z.args=T.parameters),Z.startedAt=Re((Go=T.startedAt)!=null?Go:T.timestamp),B.toolCall=Z,B.streaming=!0,B.agentMetadata={executionId:T.executionId,iteration:T.iteration},g(B)}else if(Ge==="agent_tool_delta"){let U=(Ps=T.toolCallId)!=null?Ps:x.lastId;if(U){let B=(sr=P.get(U))!=null?sr:ae(U);B.toolCall&&(B.toolCall.chunks=(Ws=B.toolCall.chunks)!=null?Ws:[],B.toolCall.chunks.push((Bs=T.delta)!=null?Bs:""),B.toolCall.status="running",B.streaming=!0,g(B))}}else if(Ge==="agent_tool_complete"){let U=(Hs=T.toolCallId)!=null?Hs:x.lastId;if(U){let B=(Ds=P.get(U))!=null?Ds:ae(U);if(B.toolCall){B.toolCall.status="complete",T.result!==void 0&&(B.toolCall.result=T.result),typeof T.executionTime=="number"&&(B.toolCall.durationMs=T.executionTime),B.toolCall.completedAt=Re((_n=T.completedAt)!=null?_n:T.timestamp),B.streaming=!1,g(B);let Z=Y(T);Z&&x.byCall.delete(Z)}}}else if(Ge==="agent_media"){let U=Array.isArray(T.media)?T.media:[],B=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let ie=Z,X=typeof ie.type=="string"?ie.type:void 0,Pe=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Ne=null,at="";if(X==="media"){let Ze=typeof ie.data=="string"?ie.data:void 0;if(!Ze)continue;at=Pe.length>0?Pe:"application/octet-stream",Ne=`data:${at};base64,${Ze}`}else if(X==="image-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;at=Pe,Ne=Ze}else if(X==="file-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;at=Pe,Ne=Ze}else continue;if(Ne)if(X==="image-url"||at.startsWith("image/"))B.push({type:"image",image:Ne,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))B.push({type:"audio",audio:Ne,mimeType:at});else if(at.startsWith("video/"))B.push({type:"video",video:Ne,mimeType:at});else{let Ze=at||"application/octet-stream";B.push({type:"file",data:Ne,mimeType:Ze,filename:ob(Ze)})}}if(B.length>0){let Z=l(),ie=T.toolCallId,Pe={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};g(Pe);let Ne=m;Ne&&(Ne.streaming=!1,g(Ne)),m=null,v.current=null}}else if(Ge!=="agent_iteration_complete"){if(Ge==="agent_reflection"||Ge==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,B={id:U,role:"assistant",content:(ns=T.reflection)!=null?ns:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Ho=T.reflection)!=null?Ho:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};g(B)}else if(Ge==="agent_complete"){te&&(te.status=T.success?"complete":"error",te.completedAt=Re(T.completedAt),te.stopReason=T.stopReason);let U=m;U&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}else if(Ge==="agent_error"){let U=typeof T.error=="string"?T.error:(Fs=(Do=T.error)==null?void 0:Do.message)!=null?Fs:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ge!=="agent_ping"){if(Ge==="agent_approval_start"){let U=(Ga=T.approvalId)!=null?Ga:`approval-${l()}`,B={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Os=te==null?void 0:te.agentId)!=null?Os:"virtual",executionId:(kr=(Ns=T.executionId)!=null?Ns:te==null?void 0:te.executionId)!=null?kr:"",toolName:(Ya=T.toolName)!=null?Ya:"",toolType:T.toolType,description:(Ja=T.description)!=null?Ja:`Execute ${(Xa=T.toolName)!=null?Xa:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};g(B)}else if(Ge==="step_await"&&T.awaitReason==="approval_required"){let U=(Qa=T.approvalId)!=null?Qa:`approval-${l()}`,B={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Sl=te==null?void 0:te.agentId)!=null?Sl:"virtual",executionId:(ar=(Er=T.executionId)!=null?Er:te==null?void 0:te.executionId)!=null?ar:"",toolName:(Za=T.toolName)!=null?Za:"",toolType:T.toolType,description:(ir=T.description)!=null?ir:`Execute ${(_s=T.toolName)!=null?_s:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};g(B)}else if(Ge==="agent_approval_complete"){let U=T.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ei=T.decision)!=null?ei:"approved",agentId:(Vs=te==null?void 0:te.agentId)!=null?Vs:"virtual",executionId:($s=(lr=T.executionId)!=null?lr:te==null?void 0:te.executionId)!=null?$s:"",toolName:(ti=T.toolName)!=null?ti:"",description:(Yo=T.description)!=null?Yo:"",resolvedAt:Date.now()}};g(Z)}}else if(Ge==="artifact_start"||Ge==="artifact_delta"||Ge==="artifact_update"||Ge==="artifact_complete"){if(Ge==="artifact_start"){let U=T.artifactType,B=String(T.id),Z=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:B,artifactType:U,title:Z,component:typeof T.component=="string"?T.component:void 0}),ye.set(B,{markdown:"",title:Z}),!se.has(B)){se.add(B);let ie={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:Z,artifactType:U,status:"streaming"}})};J.set(B,ie),g(ie)}}else if(Ge==="artifact_delta"){let U=String(T.id),B=typeof T.delta=="string"?T.delta:String((ni=T.delta)!=null?ni:"");n({type:"artifact_delta",id:U,artDelta:B});let Z=ye.get(U);Z&&(Z.markdown+=B)}else if(Ge==="artifact_update"){let U=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:U,component:typeof T.component=="string"?T.component:void 0})}else if(Ge==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let B=J.get(U);if(B){B.streaming=!1;try{let Z=JSON.parse((cr=B.rawContent)!=null?cr:"{}");if(Z.props){Z.props.status="complete";let ie=ye.get(U);ie!=null&&ie.markdown&&(Z.props.markdown=ie.markdown)}B.rawContent=JSON.stringify(Z)}catch{}ye.delete(U),g(B),J.delete(U)}}}else if(Ge==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let B=String((Ot=U.id)!=null?Ot:`msg-${l()}`),Z=U.role,X={id:B,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(g(X),X.rawContent)try{let Pe=JSON.parse(X.rawContent),Ne=(os=Pe==null?void 0:Pe.props)==null?void 0:os.artifactId;typeof Ne=="string"&&se.add(Ne)}catch{}m=null,v.current=null,ee.delete(B),re.delete(B)}else if(Ge==="error"||Ge==="step_error"||Ge==="dispatch_error"||Ge==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if(Ge==="dispatch_error"){let B=(rs=T.message)!=null?rs:T.error;B!=null&&B!==""&&(U=new Error(String(B)))}else if(Ge==="step_error"||Ge==="flow_error"){let B=T.error;typeof B=="string"&&B!==""?U=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(U=new Error(String((Us=B.message)!=null?Us:B)))}else Ge==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let B=m;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:F,value:ue}=await r.read();if(F)break;a+=s.decode(ue,{stream:!0});let Fe=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=(an=Fe.pop())!=null?an:"";for(let Ke of Fe){let _e=Ke.split(`
12
+ `),$e="message",ot="";for(let Jt of _e)Jt.startsWith("event:")?$e=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(ot+=Jt.replace("data:","").trim());if(!ot)continue;let Pt;try{Pt=JSON.parse(ot)}catch(Jt){n({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Kt=$e!=="message"?$e:(oo=Pt.type)!=null?oo:"message";if((Mo=this.onSSEEvent)==null||Mo.call(this,Kt,Pt),this.parseSSEEvent){v.current=m;let Jt=await this.handleCustomSSEEvent(Pt,n,v,g,l,M);if(v.current&&v.current!==m&&(m=v.current),Jt)continue}Mt.push(Kt,Pt),fe()}}Mt.flushPending(),fe(),Mt.destroy()}};function Li(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ga(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ii="[Image]";function Jl(e){return{type:"text",text:e}}var Om=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ab=["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"],Jo=[...Om,...ab];function ib(e){return Om.includes(e)||e.startsWith("image/")}function Ri(e){return ib(e.type)}async function Nm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ri(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 _m(e,t=Jo,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 lb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Vm(e,t){let n=lb(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 Pi=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 Wi=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 f=0;f<a.length;f++)i+=a[f]*a[f];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 ha=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 Wi;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 f=`${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,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=I=>{C||(C=!0,clearTimeout(M),m(new Error(I)))},M=setTimeout(()=>v("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(M),g())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+f+"."+u)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!C){let R=I.code!==1006?` (code ${I.code})`:"";v("WebSocket connection failed"+R+"."+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 Pi(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 f=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:f});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 _r=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 ba(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ha(e.runtype);case"browser":if(!_r.isSupported())throw new Error("Browser speech recognition not supported");return new _r(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function $m(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ba({type:"runtype",runtype:e.runtype});if(_r.isSupported())return ba({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ql(e){try{return $m(e),!0}catch{return!1}}function Um(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 ya=e=>({isError:!0,content:[{type:"text",text:e}]}),zm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Bi=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 f=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(f!=null&&f.name)&&fs(f.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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(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 fa(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 Ql((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=ba(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 f=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=f.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var f,u,g,m,C,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((f=l.transcript)!=null&&f.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}):(m=l.text)!=null&&m.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 f,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(f=this.callbacks).onVoiceStatusChanged)==null||u.call(f,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,f;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:(f=t.browser)==null?void 0:f.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 fa(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:f,rawContent:u}=t,m={id:a!=null?a:n==="user"?Li():n==="assistant"?ga():`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},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:f,streaming:u=!1,voiceProcessing:g,rawContent:m}=o,v={id:d!=null?d:r==="user"?Li():r==="assistant"?ga():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:f!=null?f:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};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,f,u,g,m;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=Li(),s=ga(),a={id:r,role:"user",content:o||Ii,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=Um(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?(u=(f=this.callbacks).onError)==null||u.call(f,C):(m=(g=this.callbacks).onError)==null||m.call(g,new Error(String(C))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=ga();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 f=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!f){let u=Um(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,f||(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 f,u,g,m,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:(f=a==null?void 0:a.createdAt)!=null?f:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.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((g=I==null?void 0:I.error)!=null?g:`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=(m=this.callbacks).onError)==null||C.call(m,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 f,u,g,m,C,v,M,I,R,P,D,W;let o=this.messages.find(w=>w.id===t.id);if(((f=o==null?void 0:o.agentMetadata)==null?void 0:f.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){(C=(m=this.callbacks).onError)==null||C.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let w=(v=t.toolCall)==null?void 0:v.args,x=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(x.length===1){let E=typeof((M=x[0])==null?void 0:M.question)=="string"?x[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 w=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:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((x,E)=>{let S=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!S)return;let k=w[S],V=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,role:"user",content:V||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(r,{[s]:n});if(!w.ok){let x=await w.json().catch(()=>null);throw new Error((P=x==null?void 0:x.error)!=null?P:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let x=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(W=(D=this.callbacks).onError)==null||W.call(D,w instanceof Error?w:new Error(String(w)))}}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,f;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var D,W,w,x,E,S,k;let g=(D=u.toolCall)==null?void 0:D.name,m=(W=u.toolCall)==null?void 0:W.id;if(!g||!m)return null;let C=`${t}:${m}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return null;this.webMcpInflightKeys.add(C),o.push(C);let v=this.markWebMcpToolRunning(u),M=new AbortController;this.webMcpResolveControllers.add(M),r.push(M);let I=(x=(w=u.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?x:g,R=this.client.executeWebMcpToolCall(g,(E=u.toolCall)==null?void 0:E.args,M.signal),P;if(!R)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await R}catch(V){let z=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return z||(k=(S=this.callbacks).onError)==null||k.call(S,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(u,ya(z?"Aborted by cancel()":zm(V)),v),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(u,ya("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:I,output:P,toolMessage:u,startedAt:v,completedAt:Date.now()}})),i=[];try{if(i=a.filter(m=>m!==null),i.length===0)return;let u={};for(let m of i)u[m.resumeKey]=m.output;let g=await this.client.resumeFlow(t,u,{signal:s.signal});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${g.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.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"))))(f=(l=this.callbacks).onError)==null||f.call(l,u instanceof Error?u:new Error(String(u)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,ya("Aborted by cancel()"),m.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 m,C,v,M,I,R,P,D,W,w,x,E;let n=(m=t.agentMetadata)==null?void 0:m.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(k){(P=(R=this.callbacks).onError)==null||P.call(R,k instanceof Error?k:new Error(String(k)))}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,f=this.client.executeWebMcpToolCall(o,l,d),u="execute",g=a;try{let S;if(f?S=await f:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ya("Aborted by cancel()"),a);return}let k=(w=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?w:o;u="resume",await this.resumeWithToolOutput(n,k,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,g)},signal:d})}catch(S){let k=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(u==="execute"||k||d.aborted)&&this.markWebMcpToolComplete(t,ya(k||d.aborted?"Aborted by cancel()":zm(S)),a),k||(E=(x=this.callbacks).onError)==null||E.call(x,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 f,u,g,m,C,v,M,I,R,P,D,W,w;if(s!==o)return r;let a={...r,...n};if(((f=r.agentMetadata)==null?void 0:f.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let x=r.approval,E=n.approval;a.approval={...x,...E,executionId:E.executionId||x.executionId,toolName:E.toolName||x.toolName,description:E.description||x.description,toolType:(u=E.toolType)!=null?u:x.toolType,reason:(g=E.reason)!=null?g:x.reason,parameters:(m=E.parameters)!=null?m:x.parameters}}let i=(C=n.toolCall)==null?void 0:C.name,d=(v=n.agentMetadata)==null?void 0:v.executionId,l=(M=n.toolCall)==null?void 0:M.id;if(i&&fs(i)&&d&&l&&((I=n.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let x=`${d}:${l}`,E=this.webMcpInflightKeys.has(x),S=this.webMcpResolvedKeys.has(x),k=(R=r.toolCall)==null?void 0:R.name,V=((P=r.agentMetadata)==null?void 0:P.executionId)===d&&((D=r.toolCall)==null?void 0:D.id)===l&&k!==void 0&&fs(k)&&((W=r.toolCall)==null?void 0:W.status)==="complete";(E||S||V)&&(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},Oo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var A=require("lucide"),cb={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=cb[e];return r?db(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 db(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,f])=>{l!=="stroke"&&d.setAttribute(l,String(f))}),r.appendChild(d)}),r}var Hi={allowedTypes:Jo,maxFileSize:10*1024*1024,maxFiles:4};function pb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ub(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 va=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Hi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Hi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Hi.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:Hi.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 f=_m(l,this.config.allowedTypes,this.config.maxFileSize);if(!f.valid){let u=(r=f.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Nm(l),g=Ri(l)?URL.createObjectURL(l):null,m={id:pb(),file:l,previewUrl:g,contentPart:u};this.attachments.push(m),this.renderPreview(m)}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=Ri(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=ub(t.file.type),d=Me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Vm(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 qm=require("idiomorph"),Di=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;qm.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 Fi={index:-1,draft:""};function jm(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:{...Fi}}}function Km(e,t){var n,o,r,s,a,i,d,l,f,u,g,m,C,v,M,I,R,P,D,W,w,x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae,le,J,se;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,(f=(l=e.llmContent)==null?void 0:l.length)!=null?f:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(M=(v=e.toolCall)==null?void 0:v.name)!=null?M:"",(P=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?P:0,(x=(w=(W=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?x:"",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,(z=(V=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:V.length)!=null?z:0,(de=(me=(he=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:me.length)!=null?de:0,(Ae=(De=(xe=(Ee=e.reasoning)==null?void 0:Ee.chunks)==null?void 0:xe[e.reasoning.chunks.length-1])==null?void 0:De.slice(-32))!=null?Ae:"",(J=(le=e.contentParts)==null?void 0:le.length)!=null?J:0,(se=e.stopReason)!=null?se:"",t].join("\0")}function Gm(){return new Map}function Ym(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Xm(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Jm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Oi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Qo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Vr(e,t){return Qo(e)-e.scrollTop<=t}function Ni(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,f=n-o;return a||Math.abs(f)<s?{action:"none",delta:f,nextLastScrollTop:n}:!t&&r&&(!l||f>0)?{action:"resume",delta:f,nextLastScrollTop:n}:t&&i&&f<0?{action:"pause",delta:f,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:f,nextLastScrollTop:n}:{action:"none",delta:f,nextLastScrollTop:n}}function _i(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"}function Qm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Zm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function ef(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var En={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Mn=1e5,gr=Mn+1;var xa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},mb=["pre","code","a","script","style"],Vi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:xa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:xa.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:xa.speed,duration:(r=e==null?void 0:e.duration)!=null?r:xa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:xa.buffer}},fb=[{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"}],nf=new Map;for(let e of fb)nf.set(e.name,e);var wa=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=nf.get(e))!=null?o:null},$i=(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},gb=(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},hb=(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},Zl=/\s/,bb=(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},yb=(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(Zl.test(s[i])){let l=i;for(;l<s.length&&Zl.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 f=i;for(;f<s.length&&!Zl.test(s[f]);)l.appendChild(gb(o,s[f],t,n.value)),n.value+=1,f+=1;a.appendChild(l),i=f}r.replaceChild(a,e)},vb=(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(hb(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Ca=(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:mb).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)bb(d,s)||i.push(d),d=a.nextNode();let l={value:(g=o==null?void 0:o.startIndex)!=null?g:0},f=t==="char"?yb:vb;for(let m of i)f(m,n,l);return r.innerHTML},Ui=(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},Sa=(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},tf=new WeakMap,xb=(e,t)=>{var s;if(!e.styles)return;let n=tf.get(t);if(n||(n=new Set,tf.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)},ec=new WeakMap,wb=(e,t)=>{if(!e.onAttach)return;let n=ec.get(t);if(n||(n=new Map,ec.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},of=e=>{let t=ec.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},tc=(e,t)=>{xb(e,t),wb(e,t)};function nc(e,t=Mn){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 Aa=0,hr=null;function oc(e=document){var n;if(Aa++,Aa===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;hr={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,Aa=Math.max(0,Aa-1),Aa===0&&hr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=hr.originalOverflow,r.style.position=hr.originalPosition,r.style.top=hr.originalTop,r.style.width=hr.originalWidth,s.scrollTo(0,hr.scrollY),hr=null}}}var zi={side:"right",width:"420px",animate:!0,reveal:"resize"},wn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Ta=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},No=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:zi.side,width:(r=t==null?void 0:t.width)!=null?r:zi.width,animate:(s=t==null?void 0:t.animate)!=null?s:zi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:zi.reveal}};var Eo={"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 ka=(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 P,D,W,w,x,E,S,k,V,z,Y,he,me;let a=(P=s.launcher)!=null?P:{},i=wn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let de=(D=a.title)!=null?D:"Chat Assistant";d.textContent=de,d.setAttribute("title",de)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let de=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=de,l.setAttribute("title",de)}let f=n.querySelector(".persona-flex-col");f&&(a.textHidden||i?f.style.display="none":f.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let de=(w=a.agentIconSize)!=null?w:"40px";if(u.style.height=de,u.style.width=de,u.innerHTML="",a.agentIconName){let Ee=parseFloat(de)||24,xe=Me(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);xe?(u.appendChild(xe),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 de=(S=a.agentIconSize)!=null?S:"40px";g.style.height=de,g.style.width=de,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let de=(k=a.callToActionIconSize)!=null?k:"32px";m.style.height=de,m.style.width=de,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ee=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Ee=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let xe=parseFloat(de)||24,De=Math.max(xe-Ee,8),Ae=Me(a.callToActionIconName,De,"currentColor",2);Ae?m.appendChild(Ae):m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}else m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let C=a.position&&Eo[a.position]?Eo[a.position]:Eo["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:Mn));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=(me=a.collapsedMaxWidth)!=null?me:"",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 Cb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",qi=(e,t={})=>{var v,M,I,R,P,D;let{showClose:n=!0,wrapperClassName:o=Cb,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 f=(I=a.closeButtonTooltipText)!=null?I:"Close chat",u=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",f),l.style.display=n?"":"none";let g=(P=a.closeButtonIconName)!=null?P:"x",m=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Dn.actionIconColor;let C=Me(g,s,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${w}`,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&&f){let W=null,w=()=>{if(W)return;let E=l.ownerDocument,S=E.body;if(!S)return;W=Oo(E,"div","persona-clear-chat-tooltip"),W.textContent=f;let k=Oo(E,"div");k.className="persona-clear-chat-tooltip-arrow",W.appendChild(k);let V=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(gr),W.style.left=`${V.left+V.width/2}px`,W.style.top=`${V.top-8}px`,W.style.transform="translate(-50%, -100%)",S.appendChild(W)},x=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",x),l.addEventListener("focus",w),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",w),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},Sb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ji=(e,t={})=>{var W,w,x,E,S,k,V,z,Y,he,me,de,Ee;let{wrapperClassName:n=Sb,buttonSize:o,iconSize:r="20px"}=t,a=(w=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?w:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(S=a.iconColor)!=null?S:"",f=(k=a.backgroundColor)!=null?k:"",u=(V=a.borderWidth)!=null?V:"",g=(z=a.borderColor)!=null?z:"",m=(Y=a.borderRadius)!=null?Y:"",C=(he=a.paddingX)!=null?he:"",v=(me=a.paddingY)!=null?me:"",M=(de=a.tooltipText)!=null?de:"Clear chat",I=(Ee=a.showTooltip)!=null?Ee:!0,R=b("div",n),P=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",M),P.style.color=l||Dn.actionIconColor;let D=Me(d,r,"currentColor",1);if(D&&(D.style.display="block",P.appendChild(D)),f&&(P.style.backgroundColor=f,P.classList.remove("hover:persona-bg-gray-100")),u||g){let xe=u||"0px",De=g||"transparent";P.style.border=`${xe} solid ${De}`,P.classList.remove("persona-border-none")}if(m&&(P.style.borderRadius=m,P.classList.remove("persona-rounded-full")),C&&(P.style.paddingLeft=C,P.style.paddingRight=C),v&&(P.style.paddingTop=v,P.style.paddingBottom=v),R.appendChild(P),I&&M){let xe=null,De=()=>{if(xe)return;let le=P.ownerDocument,J=le.body;if(!J)return;xe=Oo(le,"div","persona-clear-chat-tooltip"),xe.textContent=M;let se=Oo(le,"div");se.className="persona-clear-chat-tooltip-arrow",xe.appendChild(se);let ye=P.getBoundingClientRect();xe.style.position="fixed",xe.style.zIndex=String(gr),xe.style.left=`${ye.left+ye.width/2}px`,xe.style.top=`${ye.top-8}px`,xe.style.transform="translate(-50%, -100%)",J.appendChild(xe)},Ae=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};R.addEventListener("mouseenter",De),R.addEventListener("mouseleave",Ae),P.addEventListener("focus",De),P.addEventListener("blur",Ae),R._cleanupTooltip=()=>{Ae(),R.removeEventListener("mouseenter",De),R.removeEventListener("mouseleave",Ae),P.removeEventListener("focus",De),P.removeEventListener("blur",Ae)}}return{button:P,wrapper:R}};var Dn={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))"},$r=e=>{var W,w,x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(W=t==null?void 0:t.launcher)!=null?W:{},s=(w=r.headerIconSize)!=null?w:"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 le=parseFloat(s)||24,J=Me(d,le*.6,"currentColor",1);J?l.replaceChildren(J):l.textContent=(k=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?k:"\u{1F4AC}"}else if((V=t==null?void 0:t.launcher)!=null&&V.iconUrl){let le=b("img");le.src=t.launcher.iconUrl,le.alt="",le.className="persona-rounded-xl persona-object-cover",le.style.height=s,le.style.width=s,l.replaceChildren(le)}else l.textContent=(Y=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?Y:"\u{1F4AC}";let f=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=Dn.titleColor,u.textContent=(me=(he=t==null?void 0:t.launcher)==null?void 0:he.title)!=null?me:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Dn.subtitleColor,g.textContent=(Ee=(de=t==null?void 0:t.launcher)==null?void 0:de.subtitle)!=null?Ee:"Here to help you get answers fast",f.append(u,g),i?o.append(f):o.append(l,f);let m=(xe=r.clearChat)!=null?xe:{},C=(De=m.enabled)!=null?De:!0,v=(Ae=m.placement)!=null?Ae:"inline",M=null,I=null;if(C){let J=ji(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=J.button,I=J.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:P,wrapper:D}=qi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:P,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},Ea=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function bs(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(gr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let 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",m.id),m.destructive&&C.setAttribute("data-destructive",""),m.icon){let M=Me(m.icon,16,"currentColor",1.5);M&&C.appendChild(M)}let v=document.createElement("span");v.textContent=m.label,C.appendChild(v),C.addEventListener("click",M=>{M.stopPropagation(),f(),n(m.id)}),a.appendChild(C)}let i=null;function d(){if(!s)return;let m=o.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=C=>{!a.contains(C.target)&&!o.contains(C.target)&&f()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function f(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():f()}function g(){f(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:f,toggle:u,destroy:g}}function Ln(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[f,u]of Object.entries(i))d.setAttribute(f,u);return d}function rc(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 f=b("button",l);if(f.type="button",f.setAttribute("aria-label",n),t){let g=Me(t,s!=null?s:14,"currentColor",2);g&&f.appendChild(g)}let u=b("span");if(u.textContent=n,f.appendChild(u),i&&f.addEventListener("click",i),d)for(let[g,m]of Object.entries(d))f.setAttribute(g,m);return f}function rf(e){var m,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 f=b("span","persona-combo-btn-label");f.textContent=t,l.appendChild(f);let u=Me(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"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 g=bs({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),r(v)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",v=>{v.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{f.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Ab=e=>{var o;let t=$r({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 Tb(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=bs({items:a.menuItems,onSelect:f=>n==null?void 0:n(f),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",f=>{f.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var kb=e=>{var R,P,D,W,w,x,E,S,k;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,f;if(d)l=rf({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Dn.titleColor,f=(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"),f=b("span","persona-text-base persona-font-semibold persona-truncate"),f.style.color=Dn.titleColor,f.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(f),Tb(l,r==null?void 0:r.trailingActions,(w=r==null?void 0:r.onAction)!=null?w:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=r.onTitleClick;l.addEventListener("click",Y=>{Y.target.closest("button")||z()}),l.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),z())})}let V=r==null?void 0:r.titleRowHover;V&&(l.style.borderRadius=(x=V.borderRadius)!=null?x:"10px",l.style.padding=(E=V.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 z,Y;l.style.backgroundColor=(z=V.background)!=null?z:"",l.style.borderColor=(Y=V.border)!=null?Y:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(S=a.closeButtonSize)!=null?S:"32px",g=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Dn.actionIconColor;let C=(k=a.closeButtonIconName)!=null?k:"x",v=Me(C,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m),i.appendChild(g);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:f,headerSubtitle:I,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},sf={default:Ab,minimal:kb},Eb=e=>{var t;return(t=sf[e])!=null?t:sf.default},Ki=(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}),f=b("div");f.style.display="none";let u=b("span"),g=b("span"),m=b("button");m.style.display="none";let C=b("div");return C.style.display="none",{header:l,iconHolder:f,headerTitle:u,headerSubtitle:g,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Eb(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Gi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Yi=e=>{var W,w,x,E,S,k,V,z,Y,he,me,de;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(w=t.useIcon)!=null?w:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=(z=(V=e==null?void 0:e.copy)==null?void 0:V.sendButtonLabel)!=null?z:"Send",l=(he=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?he:"Stop",f=(me=t.showTooltip)!=null?me:!1,u=(de=t.size)!=null?de:"40px",g=t.backgroundColor,m=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=u,v.style.height=u,v.style.minWidth=u,v.style.minHeight=u,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",m?v.style.color=m:v.style.color="var(--persona-button-primary-fg, #ffffff)";let Ee=parseFloat(u)||24,xe=(m==null?void 0:m.trim())||"currentColor";r?(M=Me(r,Ee,xe,2),M?v.appendChild(M):v.textContent=o):v.textContent=o,I=Me(s,Ee,xe,2),g?v.style.backgroundColor=g:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,m?v.style.color=m: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;f&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,C.appendChild(R)),v.setAttribute("aria-label",a),C.appendChild(v);let P="send";return{button:v,wrapper:C,setMode:Ee=>{if(Ee===P)return;P=Ee;let xe=Ee==="stop"?i:a;if(v.setAttribute("aria-label",xe),R&&(R.textContent=xe),n){if(M&&I){let De=Ee==="stop"?I:M;v.replaceChildren(De)}}else v.textContent=Ee==="stop"?l:d}}},Xi=e=>{var R,P,D,W,w,x,E,S,k,V,z,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=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(o||r))return null;let a=(W=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?W:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=t.iconName)!=null?w:"mic",f=(x=t.iconSize)!=null?x:a,u=parseFloat(f)||24,g=(S=t.backgroundColor)!=null?S:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,m=(V=t.iconColor)!=null?V:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor;d.style.width=f,d.style.height=f,d.style.minWidth=f,d.style.minHeight=f,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let v=Me(l,u,m||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=(z=t.tooltipText)!=null?z:"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}},Ji=e=>{var C,v,M,I,R,P,D,W;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:Jo).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",(P=t.buttonTooltipText)!=null?P:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,f=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=Me(i,f,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),r.click()}),s.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=g,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},Qi=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},Zi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var el=e=>{var C,v,M,I,R,P;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=Zi(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=Gi(t);a();let i=Yi(t),d=Xi(t),l=Ji(t),f=Qi(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"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),u.append(g,m),r.append(u),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,f),{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:f,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:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:u,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var af=()=>{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}},lf=e=>{var C,v,M,I,R,P;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Zi();o.style.display="none";let r=Qi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Gi(t);s.style.maxHeight="100px",a();let i=Yi(t),d=Xi(t),l=Ji(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let f=b("form","persona-widget-composer persona-pill-composer");f.setAttribute("data-persona-composer-form",""),f.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),f.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&&f.append(l.input),f.append(u,s,g),l&&n.append(l.previewsContainer),n.append(f,o,r);let m=f;return{footer:n,suggestions:o,composerForm:f,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:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:m,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var cf=e=>{var f,u,g,m,C,v,M,I,R,P,D,W,w,x,E,S,k;let t=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.enabled)!=null?u:!0,n=wn(e);if(Ta(e)){let V=(m=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?m:{},z=b("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(C=V.expandedSize)!=null?C:"anchored",z.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:Mn);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%",z.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=V.expandedSize)!=null?I:"anchored",he.style.zIndex=String((P=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?P:Mn),{wrapper:z,panel:Y,pillRoot:he}}if(n){let V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return V.appendChild(z),{wrapper:V,panel:z}}if(!t){let V=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?W:"100%";return V.style.width=Y,z.style.width="100%",V.appendChild(z),{wrapper:V,panel:z}}let r=(w=e==null?void 0:e.launcher)!=null?w:{},s=r.position&&Eo[r.position]?Eo[r.position]:Eo["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:Mn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?k:e==null?void 0:e.launcherWidth,l=d!=null?d:go;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Mb=(e,t)=>{var D,W,w,x,E,S,k,V,z;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}=qi(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=(w=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:W.enabled)!=null?w:!0,a=null,i=null;if(s){let Y=ji(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"),l.style.setProperty("scrollbar-gutter","stable");let f=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");f.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",f.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=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",f.append(u,g);let m=b("div","persona-flex persona-flex-col persona-gap-3"),C=(V=e==null?void 0:e.layout)==null?void 0:V.contentMaxWidth;C&&(m.style.maxWidth=C,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(f.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(f,m);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=lf({config:e}),{root:R,textNode:P}=af();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:M,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,introTitle:u,introSubtitle:g,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode,peekBanner:R,peekTextNode:P}},df=(e,t=!0)=>{var M,I,R,P,D,W,w,x,E;if(Ta(e))return Mb(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?Ki(e,o,{showClose:t}):$r({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"),a.style.setProperty("scrollbar-gutter","stable");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=wn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(P=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let f=b("div","persona-flex persona-flex-col persona-gap-3"),u=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;u&&(f.style.maxWidth=u,f.style.marginLeft="auto",f.style.marginRight="auto",f.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,f);let m=el({config:e}),C=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?Ea(n,s,e):(s.header.style.display="none",Ea(n,s,e)),n.append(a);let v=b("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",C||(m.footer.style.display="none"),n.append(m.footer),n.append(v),{container:n,body:a,messagesWrapper:f,composerOverlay:v,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Lb=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}},Ib=(e,t)=>{if(!e)return null;let n=Lb(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Rb=(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},Pb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},sc=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(":"))},ac=320,uf=320,Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Bb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Hb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Db=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Fb=(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=`${ac}px`,l.style.maxHeight=`${uf}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 f=!1;r+=1,l.addEventListener("error",()=>{f||(f=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{f=!0}),Pb(i.image)?(l.src=i.image,o.appendChild(l)):(f=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Ob=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(!sc(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=`${ac}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Nb=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(!sc(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=`${ac}px`,r.style.maxHeight=`${uf}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}},_b=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(!sc(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}},Ma=()=>{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},Vb=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ma};if(t){let r=t(o);if(r!==null)return r}return Ma()},$b=(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},pf=(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},Ub=(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},zb=(e,t,n)=>{var m,C,v,M,I,R;let o=(m=t.showCopy)!=null?m:!0,r=(C=t.showUpvote)!=null?C:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let P=b("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let a=(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],f={"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} ${f} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let g=(P,D,W)=>{let w=Ln({icon:P,label:D,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",W),w};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},ic=(e,t,n,o,r,s)=>{var le,J,se,ye,be,K,ae,Re,oe,ee,re,it,lt,Le,pe,Je,Be;let a=n!=null?n:{},i=(le=a.layout)!=null?le:"bubble",d=a.avatar,l=a.timestamp,f=(J=d==null?void 0:d.show)!=null?J:!1,u=(se=l==null?void 0:l.show)!=null?se:!1,g=(ye=d==null?void 0:d.position)!=null?ye:"left",m=(be=l==null?void 0:l.position)!=null?be:"below",C=Ub(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=Wb(e),I=(ae=(K=e.content)==null?void 0:K.trim())!=null?ae:"",P=M.length>0&&I===Ii,D=Vi((oe=(Re=s==null?void 0:s.widgetConfig)==null?void 0:Re.features)==null?void 0:oe.streamAnimation),W=(it=(re=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:re.streamAnimation)==null?void 0:it.plugins,w=e.role==="assistant"&&D.type!=="none"?wa(D.type,W):null,x=e.role==="assistant"&&((lt=w==null?void 0:w.isAnimating)==null?void 0:lt.call(w,e))===!0,E=e.role==="assistant"&&w!==null&&(!!e.streaming||x);E&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),E&&w&&(w.containerClass&&S.classList.add(w.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let k=E?$i((Le=e.content)!=null?Le:"",D.buffer,w,e,!!e.streaming):(pe=e.content)!=null?pe:"",V=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=V;E&&(w==null?void 0:w.wrap)==="char"?z=Ca(V,"char",e.id,{skipTags:w.skipTags}):E&&(w==null?void 0:w.wrap)==="word"&&(z=Ca(V,"word",e.id,{skipTags:w.skipTags}));let Y=null;if(P?(Y=document.createElement("div"),Y.innerHTML=z,Y.style.display="none",S.appendChild(Y)):S.innerHTML=z,E&&(w!=null&&w.useCaret)&&!P&&I){let j=Ui(),fe=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),tt=fe[fe.length-1];if(tt!=null&&tt.parentNode)tt.parentNode.insertBefore(j,tt.nextSibling);else{let Mt=S.lastElementChild;Mt?Mt.appendChild(j):S.appendChild(j)}}if(u&&m==="inline"&&e.createdAt){let j=pf(e,l);j.classList.add("persona-ml-2","persona-inline"),S.appendChild(j)}if(M.length>0){let j=Fb(M,!P&&!!I,()=>{P&&Y&&(Y.style.display="")});j?v.appendChild(j):P&&Y&&(Y.style.display="")}let he=Bb(e);if(he.length>0){let j=Ob(he);j&&v.appendChild(j)}let me=Hb(e);if(me.length>0){let j=Nb(me);j&&v.appendChild(j)}let de=Db(e);if(de.length>0){let j=_b(de);j&&v.appendChild(j)}if(v.appendChild(S),u&&m==="below"&&e.createdAt){let j=pf(e,l);j.classList.add("persona-mt-1"),v.appendChild(j)}let Ee=e.role==="assistant"?Ib(e.stopReason,(Be=(Je=s==null?void 0:s.widgetConfig)==null?void 0:Je.copy)==null?void 0:Be.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let j=!!(k&&k.trim()),fe=D.placeholder==="skeleton",tt=fe&&D.buffer==="line"&&j;if(j)tt&&v.appendChild(Sa());else if(fe)v.appendChild(Sa());else{let Mt=Vb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Mt&&v.appendChild(Mt)}}if(Ee&&e.stopReason&&!e.streaming&&(I||(S.style.display="none"),v.appendChild(Rb(e.stopReason,Ee))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let j=zb(e,o,r);v.appendChild(j)}if(!f||e.role==="system")return v;let De=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=$b(d,e.role);return g==="right"||g==="left"&&e.role==="user"?De.append(v,Ae):De.append(Ae,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),De};var ys=new Set,qb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),jb=(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
+ `):""},mf=(e,t)=>{let n=ys.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")},lc=(e,t)=>{var me,de,Ee,xe,De,Ae,le,J,se,ye,be;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=(de=(me=t==null?void 0:t.features)==null?void 0:me.reasoningDisplay)!=null?de:{},s=r.expandable!==!1,a=s&&ys.has(e.id),i=n.status!=="complete",d=jb(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 f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=(xe=t==null?void 0:t.reasoning)!=null?xe:{},C=String((De=n.startedAt)!=null?De:Date.now()),v=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",C),K.textContent=Ti(n),K},M=(Ae=m.renderCollapsedSummary)==null?void 0:Ae.call(m,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ti(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(u.textContent=M,f.appendChild(u)):M instanceof HTMLElement?f.appendChild(M):(u.textContent=g,f.appendChild(u));let I=b("span","persona-text-xs persona-text-persona-primary");I.textContent=Rm(n),f.appendChild(I);let R=(le=r.loadingAnimation)!=null?le:"none",P=m.activeTextTemplate,D=m.completeTextTemplate,W=i?P:D,w=M instanceof HTMLElement,x=(K,ae,Re)=>{let oe=Re;for(let ee of ae){let re=b("span","persona-tool-char");re.style.setProperty("--char-index",String(oe)),re.textContent=ee===" "?"\xA0":ee,K.appendChild(re),oe++}return oe},E=(K,ae)=>{u.textContent="";let Re=ki(K,""),oe=0;for(let ee of Re){let re=ee.styles.length>0?(()=>{let it=b("span",ee.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return u.appendChild(it),it})():u;if(ee.isDuration&&i)re.appendChild(v());else{let it=ee.isDuration?Ti(n):ee.text;ae?oe=x(re,it,oe):re.appendChild(document.createTextNode(it))}}};if(!w&&W)if(I.style.display="none",u.style.display="",i&&R!=="none"){let K=(J=m.loadingAnimationDuration)!=null?J:2e3;u.setAttribute("data-preserve-animation","true"),R==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E(W,!1)):(u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),E(W,!0))}else E(W,!1);else if(!w&&i&&R!=="none"){u.style.display="";let K=(se=m.loadingAnimationDuration)!=null?se:2e3;if(u.setAttribute("data-preserve-animation","true"),R==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ae=u.textContent||g;u.textContent="",x(u,ae,0)}n.status==="complete"&&(u.style.display="none")}else w||(n.status==="complete"?u.style.display="none":u.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let ae=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?S.appendChild(ae):S.textContent=a?"Hide":"Show";let Re=b("div","persona-flex persona-items-center persona-ml-auto");Re.append(S),l.append(f,Re)}else l.append(f);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 K=(be=(ye=t==null?void 0:t.reasoning)==null?void 0:ye.renderCollapsedPreview)==null?void 0:be.call(ye,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});qb(k,K)||(k.textContent=d),k.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,k),o;let V=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");V.style.display=a?"":"none";let z=n.chunks.join(""),Y=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),V.appendChild(Y),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let ae=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?S.appendChild(ae):S.textContent=a?"Hide":"Show"}V.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(l,k,V),o};var vs=new Set,Kb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Gb=(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=hs(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},Yb=(e,t)=>{var f,u,g,m,C;let n=e.toolCall,o=(f=t==null?void 0:t.features)==null?void 0:f.toolCallDisplay,r=(u=o==null?void 0:o.collapsedMode)!=null?u:"tool-call",s=Gb(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Pm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return r==="tool-name"?l=((C=n.name)==null?void 0:C.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Yl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Yl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},ff=(e,t,n)=>{var f;let o=vs.has(e),r=(f=n==null?void 0:n.toolCall)!=null?f:{},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=Me(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")},cc=(e,t)=>{var z,Y,he,me,de,Ee,xe,De,Ae;let n=e.toolCall,o=(z=t==null?void 0:t.toolCall)!=null?z:{},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&&vs.has(e.id),{summary:d,previewText:l,isActive:f}=Yb(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"),m=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let C=String((me=n.startedAt)!=null?me:Date.now()),v=()=>{let le=b("span","");return le.setAttribute("data-tool-elapsed",C),le.textContent=ma(n),le},M=(Ee=o.renderCollapsedSummary)==null?void 0:Ee.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(de=s.collapsedMode)!=null?de:"tool-call",isActive:f,config:t!=null?t:{},elapsed:ma(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(m.textContent=M,g.appendChild(m)):M instanceof HTMLElement?g.appendChild(M):(m.textContent=d,g.appendChild(m));let I=(xe=s.loadingAnimation)!=null?xe:"none",R=o.activeTextTemplate,P=o.completeTextTemplate,D=f?R:P,W=M instanceof HTMLElement,w=(le,J,se)=>{let ye=se;for(let be of J){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(ye)),K.textContent=be===" "?"\xA0":be,le.appendChild(K),ye++}return ye},x=(le,J)=>{var K;m.textContent="";let se=((K=n.name)==null?void 0:K.trim())||"tool",ye=ki(le,se),be=0;for(let ae of ye){let Re=ae.styles.length>0?(()=>{let oe=b("span",ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(oe),oe})():m;if(ae.isDuration&&f)Re.appendChild(v());else{let oe=ae.isDuration?ma(n):ae.text;J?be=w(Re,oe,be):Re.appendChild(document.createTextNode(oe))}}};if(!W)if(f&&I!=="none"){let le=(De=o.loadingAnimationDuration)!=null?De:2e3;if(m.setAttribute("data-preserve-animation","true"),I==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${le}ms`),D&&x(D,!1);else if(m.classList.add(`persona-tool-loading-${I}`),m.style.setProperty("--persona-tool-anim-duration",`${le}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let J=m.textContent||d;m.textContent="",w(m,J,0)}}else D&&x(D,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let le=o.toggleTextColor||o.headerTextColor||"currentColor",J=Me(i?"chevron-up":"chevron-down",16,le,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show";let se=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(E),u.append(g,se)}else u.append(g);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&&f&&s.activePreview&&l){let le=(Ae=o.renderCollapsedPreview)==null?void 0:Ae.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:f,config:t!=null?t:{}});Kb(S,le)||(S.textContent=l),S.style.display=""}if(!i&&f&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,S),r;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),n.name){let le=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?le.style.color=o.contentTextColor:o.headerTextColor&&(le.style.color=o.headerTextColor),le.textContent=n.name,k.appendChild(le)}if(n.args!==void 0){let le=b("div","persona-space-y-1"),J=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(se.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(se.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(se.style.color=o.codeBlockTextColor),se.textContent=hs(n.args),le.append(J,se),k.appendChild(le)}if(n.chunks&&n.chunks.length){let le=b("div","persona-space-y-1"),J=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(se.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(se.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(se.style.color=o.codeBlockTextColor),se.textContent=n.chunks.join(""),le.append(J,se),k.appendChild(le)}if(n.status==="complete"&&n.result!==void 0){let le=b("div","persona-space-y-1"),J=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(se.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(se.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(se.style.color=o.codeBlockTextColor),se.textContent=hs(n.result),le.append(J,se),k.appendChild(le)}if(n.status==="complete"&&typeof n.duration=="number"){let le=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(le.style.color=o.contentTextColor),le.textContent=`Duration: ${n.duration}ms`,k.appendChild(le)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let le=o.toggleTextColor||o.headerTextColor||"currentColor",J=Me(i?"chevron-up":"chevron-down",16,le,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(u,S,k),r};var br=require("partial-json");var Xb="ask_user_question",dc=8,xs="data-persona-ask-sheet-for",Jb="Other",Qb="Other\u2026",hf="Type your own answer here",bf="Send",Zb="Next",ey="Back",ty="Submit all",ny="Skip",oy=3,pc="data-ask-current-index",uc="data-ask-question-count",yf="data-ask-answers",mc="data-ask-grouped",vf="data-ask-layout",ry=e=>e.layout==="pills"?"pills":"rows",sy=e=>e.getAttribute(vf)==="pills"?"pills":"rows",gf=!1,xf=e=>e.replace(/["\\]/g,"\\$&"),Ur=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xb,fc=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ws=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,br.parse)(r,br.STR|br.OBJ|br.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},La=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>dc&&!gf&&(gf=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${dc}.`)),t.slice(0,dc)},ay=e=>{var t;return(t=La(e)[0])!=null?t:null},iy=(e,t)=>{var n;return(n=La(e)[t])!=null?n:null},ly=(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))},wf=(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},cy=(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=wf(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},dy=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},py=(e,t,n,o)=>{var f,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(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<oy;m++)s.appendChild(dy(o));return s}if(d.forEach((m,C)=>{s.appendChild(cy(m,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Jb:Qb;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=(f=t.freeTextPlaceholder)!=null?f:hf,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),v.appendChild(M),C.appendChild(v);let I=wf(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=(g=t.freeTextLabel)!=null?g:m,s.appendChild(C)}}return s},Cf=(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:hf,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:bf,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},uy=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:bf,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},my=(e,t,n)=>{var l,f,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:ey,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=(f=n.skipLabel)!=null?f:ny,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:ty:(g=n.nextLabel)!=null?g:Zb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},zr=e=>{let t=e.getAttribute(yf);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Sf=(e,t)=>{e.setAttribute(yf,JSON.stringify(t))},ho=e=>{var n;let t=Number((n=e.getAttribute(pc))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},fy=(e,t)=>{e.setAttribute(pc,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(uc))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yr=e=>e.getAttribute(mc)==="true",gy=(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},hy=(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)))},tl=(e,t)=>{let{payload:n}=ws(t),o=La(n),r=zr(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},Af=e=>{let t=zr(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 u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",f=r.has(l);d.setAttribute("aria-pressed",f?"true":"false"),d.classList.toggle("persona-ask-pill-selected",f)});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=""},Tf=e=>{if(!yr(e))return;let t=zr(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}},gc=(e,t,n)=>{let o=fc(n),r=sy(e),{payload:s,complete:a}=ws(t),i=yr(e),d=ho(e),l=Cs(e),f=i?iy(s,d):ay(s),u=!!(f!=null&&f.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let R=typeof(f==null?void 0:f.question)=="string"?f.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=py(f,o,a,r);v.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Cf(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(uy(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=my(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();Af(e),Tf(e)},by=(e,t,n)=>{let o=fc(t),r=ry(o),s=e.toolCall.id,a=La(n),i=Math.max(1,a.length),d=i>1,l=gy(e,a),f=d?hy(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(xs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(uc,String(i)),u.setAttribute(pc,String(f)),u.setAttribute(mc,d?"true":"false"),u.setAttribute(vf,r),Sf(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`),ly(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let C=b("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",g.appendChild(C),u.appendChild(g);let M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),r!=="rows"&&u.appendChild(Cf(o,r)),gc(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},yy=(e,t,n)=>{let{payload:o}=ws(t),r=Math.max(1,La(o).length);r>Cs(e)&&(e.setAttribute(uc,String(r)),r>1&&!yr(e)&&e.setAttribute(mc,"true")),gc(e,t,n)};var nl=(e,t,n)=>{if(!n||!Ur(e)||fc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${xs}]`).forEach(l=>{l.getAttribute(xs)!==r&&l.remove()});let a=n.querySelector(`[${xs}="${xf(r)}"]`);if(a){yy(a,e,t);return}let{payload:i}=ws(e),d=by(e,t,i);n.appendChild(d)},Ss=(e,t)=>{if(!e)return;let n=t?`[${xs}="${xf(t)}"]`:`[${xs}]`;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)})},hc=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),vr=(e,t)=>{let n=zr(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Sf(e,n),Af(e),Tf(e)},ol=(e,t,n,o)=>{let r=Cs(e),s=Math.max(0,Math.min(r-1,o));fy(e,s),gc(e,t,n)};var rl=new Map,vy=e=>{let n=(e.startsWith(Or)?e.slice(Or.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)},kf=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Ef=(e,t)=>{var o,r,s;let n=(r=(o=kf(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=rl.get(e))!=null?s:n==="expanded"},Mf=(e,t,n)=>{var a,i;let o=kf(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)}},Lf=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Ef(e,n);Mf(o,s,n),r.style.display=s?"":"none"};var sl=(e,t)=>{var x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae,le;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(x=o==null?void 0:o.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(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",f=Me(d,20,l,2);f&&i.appendChild(f);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(k=o==null?void 0:o.title)!=null?k:"Approval Required",g.appendChild(m),!r){let J=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",n.status),n.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):n.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):n.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),g.appendChild(J)}u.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Or)?Gl(n.toolName):void 0,M=(V=o==null?void 0:o.formatDescription)==null?void 0:V.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),I=!n.toolName,R=M||(I?n.description:`The assistant wants to use \u201C${v!=null?v:vy(n.toolName)}\u201D.`),P=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=R,u.appendChild(P),n.reason){let J=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");J.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?J.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor);let se=b("span","persona-font-medium");se.textContent=`${(z=o==null?void 0:o.reasonLabel)!=null?z:"Agent's stated reason:"} `,J.appendChild(se),J.appendChild(document.createTextNode(n.reason)),u.appendChild(J)}let D=(Y=o==null?void 0:o.detailsDisplay)!=null?Y:"collapsed",W=!!n.description&&!I,w=W||!!n.parameters;if(D!=="hidden"&&w){let J=Ef(e.id,t),se=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");se.type="button",se.setAttribute("data-expand-header","true"),se.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor);let ye=b("span");ye.setAttribute("data-approval-details-label","true");let be=b("span","persona-inline-flex persona-items-center");be.setAttribute("data-approval-details-chevron","true"),se.append(ye,be),Mf(se,J,t),u.appendChild(se);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=J?"":"none",W){let ae=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ae.style.color=o.descriptionColor),ae.textContent=n.description,K.appendChild(ae)}if(n.parameters){let ae=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&&(ae.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ae.style.color=o.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=hs(n.parameters),K.appendChild(ae)}u.appendChild(K)}if(r){let J=b("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let se=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");se.type="button",se.style.backgroundColor=(he=o==null?void 0:o.approveButtonColor)!=null?he:"var(--persona-approval-approve-bg, #22c55e)",se.style.color=(me=o==null?void 0:o.approveButtonTextColor)!=null?me:"#ffffff",se.setAttribute("data-approval-action","approve");let ye=Me("shield-check",14,(de=o==null?void 0:o.approveButtonTextColor)!=null?de:"#ffffff",2);ye&&(ye.style.marginRight="4px",se.appendChild(ye));let be=document.createTextNode((Ee=o==null?void 0:o.approveLabel)!=null?Ee:"Approve");se.appendChild(be);let K=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");K.type="button",K.style.backgroundColor=(xe=o==null?void 0:o.denyButtonColor)!=null?xe:"transparent",K.style.color=(De=o==null?void 0:o.denyButtonTextColor)!=null?De:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let ae=Me("shield-x",14,(Ae=o==null?void 0:o.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",K.appendChild(ae));let Re=document.createTextNode((le=o==null?void 0:o.denyLabel)!=null?le:"Deny");K.appendChild(Re),J.append(se,K),u.appendChild(J)}return a.append(i,u),s.appendChild(a),s};var If=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(m=>m.role==="user"))return;let f=document.createDocumentFragment(),u=r?r.isStreaming():!1,g=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(m=>{let 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=m,C.disabled=u,i!=null&&i.fontFamily&&(C.style.fontFamily=g(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(m))}),f.appendChild(C),t.push(C)}),e.appendChild(f)}}};var Ia=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ra=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var xy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),wy=new Set(["step_start","execution_start"]),Cy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Sy=new Set(["step_complete","agent_turn_complete"]),Ay=new Set(["flow_complete","agent_complete"]),Rf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),no=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,qr=(e,t)=>{let n=e[t];return Wf(n)?n:void 0};function bc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function al(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Ty(e,t){return typeof t.type=="string"?t.type:e}function ky(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 Ey(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 Pf(e){var o,r,s,a,i;let t=qr(e,"result"),n=[qr(e,"tokens"),qr(e,"totalTokens"),t?qr(t,"tokens"):void 0,qr(e,"usage"),t?qr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=no(d.output))!=null?o:no(d.outputTokens))!=null?r:no(d.completionTokens);if(l!==void 0)return l}return(i=(s=no(e.outputTokens))!=null?s:no(e.completionTokens))!=null?i:t?(a=no(t.outputTokens))!=null?a:no(t.completionTokens):void 0}function My(e){var n,o,r,s,a;let t=qr(e,"result");return(a=(r=(o=(n=no(e.executionTime))!=null?n:no(e.executionTimeMs))!=null?o:no(e.execution_time))!=null?r:no(e.duration))!=null?a:t?(s=no(t.executionTime))!=null?s:no(t.executionTimeMs):void 0}function Ly(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Pa=class{constructor(t=Ly){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:al(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(!Wf(n)){Rf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Ty(t,n),r=this.now();if(xy.has(o)){this.startRun(r);return}if(wy.has(o)){this.run||this.startRun(r);return}if(Cy.has(o)){if(!Ey(o,n))return;let a=ky(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+bc(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:al(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Sy.has(o)){if(!this.run)return;let a=this.run,i=Pf(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+bc(a.visibleCharCount),f=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:al(l,f),outputTokens:l,durationMs:f,source:d?"usage":"estimate"};return}if(Ay.has(o)){if(!this.run)return;let a=this.run,i=Pf(n),d=i!=null?i:a.exactOutputTokens+bc(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",f=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:al(d,f),outputTokens:d,durationMs:f,source:l},this.run=null;return}if(Rf.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=My(n);return s!=null?s:o-t.startedAt}};function As(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Iy={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)"}},Ry={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Py=["flowName","stepName","reasoningText","text","name","tool","toolName"],Wy=100;function By(e,t){let n={...Iy,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Ry}function Hy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Dy(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 Fy(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 Oy(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 Ny(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 _y(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Vy(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 $y(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 yc(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");As(l,(g=o.classNames)==null?void 0:g.eventRow);let f=a.find(m=>m.renderEventStreamRow);if(f!=null&&f.renderEventStreamRow&&i){let m=f.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var z,Y;let m=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=(z=o.timestampFormat)!=null?z:"relative";I.textContent=R==="relative"?Hy(e.timestamp,n):Dy(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let D=By(e.type,o.badgeColors),W=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");W.style.backgroundColor=D.bg,W.style.color=D.text,W.style.borderColor=D.text+"50",W.textContent=e.type;let w=(Y=o.descriptionFields)!=null?Y:Py,x=Fy(e.payload,w),E=null;x&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=x);let S=b("div","persona-flex-1 persona-min-w-0"),k=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),V=Me("clipboard","12px","currentColor",1.5);return V&&k.appendChild(V),k.addEventListener("click",async he=>{he.stopPropagation(),await Oy(Ny(e)),k.innerHTML="";let me=Me("check","12px","currentColor",1.5);me&&k.appendChild(me),setTimeout(()=>{k.innerHTML="";let de=Me("clipboard","12px","currentColor",1.5);de&&k.appendChild(de)},1500)}),C.appendChild(v),C.appendChild(I),P&&C.appendChild(P),C.appendChild(W),E&&C.appendChild(E),C.appendChild(S),C.appendChild(k),m.appendChild(C),d&&m.appendChild($y(e,a,i)),m}}function Bf(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",f=(M=i==null?void 0:i.label)!=null?M:"",u=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},g=s.find(P=>P.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let P=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=u.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");As(D,P==null?void 0:P.panel);let W=[],w="",x="",E=null,S=[],k={},V=0,z=Oi(),Y=0,he=0,me=!1,de=null,Ee=!1,xe=0,De=new Set,Ae=new Map,le="",J="",se=null,ye,be,K,ae,Re,oe=null,ee=null,re=null;function it(){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");As(ce,P==null?void 0:P.headerBar);let et=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(et.textContent="Events",ye=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ye.textContent="0",a){ee=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let Cn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Cn.textContent="Throughput",oe=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"),oe.textContent="-- tok/s",re=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),re.style.display="none",re.style.pointerEvents="none";let Sn=ee,yn=re,Lo=()=>{if(!yn.textContent)return;let Un=Sn.getBoundingClientRect(),zn=Se.getBoundingClientRect();yn.style.left=`${Un.left-zn.left}px`,yn.style.top=`${Un.bottom-zn.top+4}px`,yn.style.display="block"},At=()=>{yn.style.display="none"};ee.addEventListener("mouseenter",Lo),ee.addEventListener("mouseleave",At),ee.appendChild(Cn),ee.appendChild(oe)}let Qt=b("div","persona-flex-1");be=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 Gt=b("option","");Gt.value="",Gt.textContent="All events",be.appendChild(Gt),K=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"),K.type="button",K.title="Copy All";let vn=Me("clipboard-copy","12px","currentColor",1.5);vn&&K.appendChild(vn);let gt=b("span","persona-text-xs");gt.textContent="Copy All",K.appendChild(gt),ce.appendChild(et),ce.appendChild(ye),ee&&ce.appendChild(ee),ce.appendChild(Qt),ce.appendChild(be),ce.appendChild(K);let Lt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");As(Lt,P==null?void 0:P.searchBar);let Qe=Me("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");Qe&&qt.appendChild(Qe),ae=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),As(ae,P==null?void 0:P.searchInput),ae.type="text",ae.placeholder="Search event payloads...",Re=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"),Re.type="button",Re.style.display="none";let ln=Me("x","12px","currentColor",2);return ln&&Re.appendChild(ln),Lt.appendChild(qt),Lt.appendChild(ae),Lt.appendChild(Re),Se.appendChild(ce),Se.appendChild(Lt),re&&Se.appendChild(re),Se}let lt,Le=s.find(Se=>Se.renderEventStreamToolbar);if(Le!=null&&Le.renderEventStreamToolbar&&r){let Se=Le.renderEventStreamToolbar({config:r,defaultRenderer:()=>it(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ce=>{w=ce,an(),F()},onSearchChange:ce=>{x=ce,an(),F()}});lt=Se!=null?Se:it()}else lt=it();let pe=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");pe.style.display="none";function Je(){if(!a||!oe||!ee)return;let Se=a();oe.textContent=_y(Se);let ce=Vy(Se);re&&(re.textContent=ce,ce||(re.style.display="none")),ce?ee.setAttribute("aria-label",ce):ee.removeAttribute("aria-label")}let Be=b("div","persona-flex-1 persona-min-h-0 persona-relative"),j=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");j.style.height="100%";let fe=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");As(fe,P==null?void 0:P.scrollIndicator),fe.style.display="none",fe.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let tt=Me(l,"14px","currentColor",2);tt&&fe.appendChild(tt);let Mt=b("span","");Mt.textContent=f,fe.appendChild(Mt);let te=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",Be.appendChild(j),Be.appendChild(te),Be.appendChild(fe),D.setAttribute("tabindex","0"),D.appendChild(lt),D.appendChild(pe),D.appendChild(Be);function qe(){let Se=t.getAll(),ce={};for(let gt of Se)ce[gt.type]=(ce[gt.type]||0)+1;let et=Object.keys(ce).sort(),Qt=et.length!==S.length||!et.every((gt,Lt)=>gt===S[Lt]),Gt=!Qt&&et.some(gt=>ce[gt]!==k[gt]),In=Se.length!==Object.values(k).reduce((gt,Lt)=>gt+Lt,0);if(!Qt&&!Gt&&!In||(S=et,k=ce,!be))return;let vn=be.value;if(be.options[0].textContent="All events",Qt){for(;be.options.length>1;)be.remove(1);for(let gt of et){let Lt=b("option","");Lt.value=gt,Lt.textContent=`${gt} (${ce[gt]||0})`,be.appendChild(Lt)}vn&&et.includes(vn)?be.value=vn:vn&&(be.value="",w="")}else for(let gt=1;gt<be.options.length;gt++){let Lt=be.options[gt];Lt.textContent=`${Lt.value} (${ce[Lt.value]||0})`}}function Fn(){let Se=t.getAll();if(w&&(Se=Se.filter(ce=>ce.type===w)),x){let ce=x.toLowerCase();Se=Se.filter(et=>et.type.toLowerCase().includes(ce)||et.payload.toLowerCase().includes(ce))}return Se}function Dt(){return w!==""||x!==""}function an(){V=0,Y=0,z.resume(),fe.style.display="none"}function oo(Se){De.has(Se)?De.delete(Se):De.add(Se),se=Se;let ce=j.scrollTop,et=z.isFollowing();Ee=!0,z.pause(),F(),j.scrollTop=ce,et&&z.resume(),Ee=!1}function Mo(){return Vr(j,50)}function F(){he=Date.now(),me=!1,Je(),qe();let Se=t.getEvictedCount();Se>0?(pe.textContent=`${Se.toLocaleString()} older events truncated`,pe.style.display=""):pe.style.display="none",W=Fn();let ce=W.length,et=t.getSize()>0;ye&&(ye.textContent=String(t.getSize())),ce===0&&et&&Dt()?(te.textContent=x?`No events matching '${x}'`:"No events matching filter",te.style.display="",j.style.display="none"):(te.style.display="none",j.style.display=""),K&&(K.title=Dt()?`Copy Filtered (${ce})`:"Copy All"),d&&!z.isFollowing()&&ce>V&&(Y+=ce-V,Mt.textContent=f?`${f}${Y>0?` (${Y})`:""}`:"",fe.style.display=""),V=ce;let Qt=t.getAll(),Gt=Qt.length>0?Qt[0].timestamp:0,In=new Set(W.map(Lt=>Lt.id));for(let Lt of De)In.has(Lt)||De.delete(Lt);let vn=w!==le||x!==J,gt=Ae.size===0&&W.length>0;if(vn||gt||W.length===0){j.innerHTML="",Ae.clear();let Lt=document.createDocumentFragment();for(let Qe=0;Qe<W.length;Qe++){let qt=yc(W[Qe],Qe,Gt,u,De,oo,s,r);Ae.set(W[Qe].id,qt),Lt.appendChild(qt)}j.appendChild(Lt),le=w,J=x,se=null}else{if(se!==null){let Qe=Ae.get(se);if(Qe&&Qe.parentNode===j){let qt=W.findIndex(ln=>ln.id===se);if(qt>=0){let ln=yc(W[qt],qt,Gt,u,De,oo,s,r);j.insertBefore(ln,Qe),Qe.remove(),Ae.set(se,ln)}}se=null}let Lt=new Set(W.map(Qe=>Qe.id));for(let[Qe,qt]of Ae)Lt.has(Qe)||(qt.remove(),Ae.delete(Qe));for(let Qe=0;Qe<W.length;Qe++){let qt=W[Qe];if(!Ae.has(qt.id)){let ln=yc(qt,Qe,Gt,u,De,oo,s,r);Ae.set(qt.id,ln),j.appendChild(ln)}}}z.isFollowing()&&(j.scrollTop=j.scrollHeight)}function ue(){if(Date.now()-he>=Wy){de!==null&&(cancelAnimationFrame(de),de=null),F();return}me||(me=!0,de=requestAnimationFrame(()=>{de=null,F()}))}let Fe=(Se,ce)=>{if(!K)return;K.innerHTML="";let et=Me(Se,"12px","currentColor",1.5);et&&K.appendChild(et);let Qt=b("span","persona-text-xs");Qt.textContent="Copy All",K.appendChild(Qt),setTimeout(()=>{K.innerHTML="";let Gt=Me("clipboard-copy","12px","currentColor",1.5);Gt&&K.appendChild(Gt);let In=b("span","persona-text-xs");In.textContent="Copy All",K.appendChild(In),K.disabled=!1},ce)},Ke=async()=>{if(K){K.disabled=!0;try{let Se;Dt()?Se=W:n?(Se=await n(),Se.length===0&&(Se=t.getAll())):Se=t.getAll();let ce=Se.map(et=>{try{return JSON.parse(et.payload)}catch{return et.payload}});await navigator.clipboard.writeText(JSON.stringify(ce,null,2)),Fe("check",1500)}catch{Fe("x",1500)}}},_e=()=>{be&&(w=be.value,an(),F())},$e=()=>{!ae||!Re||(Re.style.display=ae.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{x=ae.value,an(),F()},150))},ot=()=>{!ae||!Re||(ae.value="",x="",Re.style.display="none",E&&clearTimeout(E),an(),F())},Pt=()=>{if(Ee)return;let Se=j.scrollTop,{action:ce,nextLastScrollTop:et}=Ni({following:z.isFollowing(),currentScrollTop:Se,lastScrollTop:xe,nearBottom:Mo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=et,ce==="resume"?(z.resume(),Y=0,fe.style.display="none"):ce==="pause"&&(z.pause(),d&&(Mt.textContent=f,fe.style.display=""))},Kt=Se=>{let ce=_i({following:z.isFollowing(),deltaY:Se.deltaY,nearBottom:Mo(),resumeWhenNearBottom:!0});ce==="pause"?(z.pause(),d&&(Mt.textContent=f,fe.style.display="")):ce==="resume"&&(z.resume(),Y=0,fe.style.display="none")},Jt=()=>{d&&(j.scrollTop=j.scrollHeight,z.resume(),Y=0,fe.style.display="none")},G=Se=>{let ce=Se.target;if(!ce||ce.closest("button"))return;let et=ce.closest("[data-event-id]");if(!et)return;let Qt=et.getAttribute("data-event-id");Qt&&oo(Qt)},xt=Se=>{if((Se.metaKey||Se.ctrlKey)&&Se.key==="f"){Se.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}Se.key==="Escape"&&(ae&&document.activeElement===ae?(ot(),ae.blur(),D.focus()):o&&o())};K&&K.addEventListener("click",Ke),be&&be.addEventListener("change",_e),ae&&ae.addEventListener("input",$e),Re&&Re.addEventListener("click",ot),j.addEventListener("scroll",Pt),j.addEventListener("wheel",Kt,{passive:!0}),j.addEventListener("click",G),fe.addEventListener("click",Jt),D.addEventListener("keydown",xt);function st(){E&&clearTimeout(E),de!==null&&(cancelAnimationFrame(de),de=null),me=!1,Ae.clear(),K&&K.removeEventListener("click",Ke),be&&be.removeEventListener("change",_e),ae&&ae.removeEventListener("input",$e),Re&&Re.removeEventListener("click",ot),j.removeEventListener("scroll",Pt),j.removeEventListener("wheel",Kt),j.removeEventListener("click",G),fe.removeEventListener("click",Jt),D.removeEventListener("keydown",xt)}return{element:D,update:ue,destroy:st}}}function Hf(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 f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.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 m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(f,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 Df=(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",f=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Hf(e,t)});if(f)return f}return Hf(e,t)};var vc=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)})}},jr=new vc;jr.register("PersonaArtifactCard",Df);function Uy(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 Ff(e,t){var be,K,ae,Re;let n=(K=(be=e.features)==null?void 0:be.artifacts)==null?void 0:K.layout,r=((ae=n==null?void 0:n.toolbarPreset)!=null?ae:"default")==="document",s=(Re=n==null?void 0:n.panePadding)==null?void 0:Re.trim(),a=e.markdown?xi(e.markdown):null,i=wi(e.sanitize),d=oe=>{let ee=a?a(oe):pa(oe);return i?i(ee):ee},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,f=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),V==null||V.hide()};l&&l.addEventListener("click",()=>{var oe;f(),(oe=t.onDismiss)==null||oe.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 m=b("span","persona-text-xs persona-font-medium persona-truncate");m.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 oe;f(),(oe=t.onDismiss)==null||oe.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?Ln({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Ln({icon:"eye",label:"Rendered view"}),R=r?Ln({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Ln({icon:"code-2",label:"Source"}),P=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(W&&w&&w.length>0),E=null,S,k=null,V=null;if(r&&(D||W)&&!x){if(S=D?rc({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let oe=Me("chevron-down",14,"currentColor",2);oe&&S.appendChild(oe)}}else r&&x?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?rc({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Ln({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),E.append(S,k)):r?S=Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Ln({icon:"copy",label:"Copy"});let z=r?Ln({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ln({icon:"refresh-cw",label:"Refresh"}),Y=r?Ln({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Ln({icon:"x",label:"Close"}),he=()=>{var lt,Le,pe;let oe=(lt=Ae.find(Je=>Je.id===le))!=null?lt:Ae[Ae.length-1],ee=(Le=oe==null?void 0:oe.id)!=null?Le:null,re=(oe==null?void 0:oe.artifactType)==="markdown"&&(pe=oe.markdown)!=null?pe:"",it=oe?JSON.stringify({component:oe.component,props:oe.props},null,2):"";return{markdown:re,jsonPayload:it,id:ee}},me=async()=>{var lt;let{markdown:oe,jsonPayload:ee}=he(),re=(lt=Ae.find(Le=>Le.id===le))!=null?lt:Ae[Ae.length-1],it=(re==null?void 0:re.artifactType)==="markdown"?oe:re?ee:"";try{await navigator.clipboard.writeText(it)}catch{}};if(S.addEventListener("click",async()=>{let oe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(oe&&x){let{markdown:ee,jsonPayload:re,id:it}=he();try{await oe({actionId:"primary",artifactId:it,markdown:ee,jsonPayload:re})}catch{}return}await me()}),k&&(w!=null&&w.length)){let oe=()=>{var re;return(re=u.closest("[data-persona-root]"))!=null?re:document.body},ee=()=>{V=bs({items:w.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:it,jsonPayload:lt,id:Le}=he(),pe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{pe?await pe({actionId:re,artifactId:Le,markdown:it,jsonPayload:lt}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(it):re==="json"||re==="source"?await navigator.clipboard.writeText(lt):await navigator.clipboard.writeText(it||lt)}catch{}},anchor:E!=null?E:k,position:"bottom-right",portal:oe()})};u.isConnected?ee():requestAnimationFrame(ee),k.addEventListener("click",re=>{re.stopPropagation(),V==null||V.toggle()})}z.addEventListener("click",async()=>{var oe;try{await((oe=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:oe.call(n))}catch{}se()}),Y.addEventListener("click",()=>{var oe;f(),(oe=t.onDismiss)==null||oe.call(t)});let de=()=>{r&&(I.setAttribute("aria-pressed",v==="rendered"?"true":"false"),R.setAttribute("aria-pressed",v==="source"?"true":"false"))};I.addEventListener("click",()=>{v="rendered",de(),se()}),R.addEventListener("click",()=>{v="source",de(),se()});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?(g.replaceChildren(),M.append(I,R),E?P.append(E,z,Y):P.append(S,z,Y),g.append(M,Ee,P),de()):(g.appendChild(m),g.appendChild(C)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let xe=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"),De=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(xe.style.paddingLeft=s,xe.style.paddingRight=s,De.style.padding=s),u.appendChild(g),u.appendChild(xe),u.appendChild(De);let Ae=[],le=null,J=!1,se=()=>{var it,lt,Le,pe;let oe=r&&Ae.length<=1;xe.classList.toggle("persona-hidden",oe),xe.replaceChildren();for(let Je of Ae){let Be=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");Be.type="button",Be.textContent=Je.title||Je.id.slice(0,8),Je.id===le&&Be.classList.add("persona-bg-persona-container","persona-border-persona-border"),Be.addEventListener("click",()=>t.onSelect(Je.id)),xe.appendChild(Be)}De.replaceChildren();let ee=le&&Ae.find(Je=>Je.id===le)||Ae[Ae.length-1];if(!ee)return;if(r){let Je=ee.artifactType==="markdown"?"MD":(it=ee.component)!=null?it:"Component",j=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ee.textContent=`${j} \xB7 ${Je}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(r&&v==="source"){let Be=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Be.textContent=(lt=ee.markdown)!=null?lt:"",De.appendChild(Be);return}let Je=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Je.innerHTML=d((Le=ee.markdown)!=null?Le:""),De.appendChild(Je);return}let re=ee.component?jr.get(ee.component):void 0;if(re){let Be={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let j=re((pe=ee.props)!=null?pe:{},Be);if(j){De.appendChild(j);return}}catch{}}De.appendChild(Uy(ee))},ye=()=>{var ee;let oe=Ae.length>0;if(u.classList.toggle("persona-hidden",!oe),l){let re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,lt=((ee=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;oe&&lt&&J?(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(oe){var ee,re,it;Ae=oe.artifacts,le=(it=(re=oe.selectedId)!=null?re:(ee=oe.artifacts[oe.artifacts.length-1])==null?void 0:ee.id)!=null?it:null,Ae.length>0&&(J=!0),se(),ye()},setMobileOpen(oe){J=oe,!oe&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ye()}}}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 Of(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 zy(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 il(e,t){var d,l,f,u,g,m,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"),zy(e),Of(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",(f=n==null?void 0:n.splitGap)!=null?f:"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=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(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"),Of(e,t)}var Nf=["panel","seamless"];function ll(e,t){var i,d,l,f,u,g;for(let m of Nf)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!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=Nf.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(f=n==null?void 0:n.paneBorderRadius)==null?void 0:f.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 m=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function _f(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 qy(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 jy(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 Ky(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Gy(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Vf(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 $f(e,t,n,o,r,s){let a=qy(r,200),i=Gy(t,n,o,200);i=Math.max(a,i);let d=jy(s);return d!==null&&(i=Math.min(i,d)),Ky(e,a,i)}var Uf={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"}},xc=(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=Uf[a])!=null?v:Uf.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 f=document.createElement("form");f.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var w,x;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let P=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=I.label,R.appendChild(P);let D=(w=I.type)!=null?w:"text",W;D==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=D),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${I.name}`,W.name=I.name,W.placeholder=(x=I.placeholder)!=null?x:"",I.required&&(W.required=!0),R.appendChild(W),f.appendChild(R)});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]"),m=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(g),u.appendChild(m),f.appendChild(u),s.replaceChildren(d,f),f.addEventListener("submit",async I=>{var W,w;I.preventDefault();let R=(W=n.formEndpoint)!=null?W:"/form",P=new FormData(f),D={};P.forEach((x,E)=>{D[E]=x}),D.type=a,m.disabled=!0,g.textContent="Submitting\u2026";try{let x=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let E=await x.json();g.textContent=(w=E.message)!=null?w:"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{m.disabled=!1}})})};var wc=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()}},Cc=new wc;var zf=()=>{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 Yy=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Xy=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Ac=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Yy(e),n=Xy(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Sc=e=>typeof e=="string"?e:e==null?"":String(e),Wa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Sc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Sc(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Sc(n.text)}}},qf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Tc=e=>{let t=new Set(qf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(qf(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,f)=>l||(f==null?void 0:f({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 f=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:f});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(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:n}};var Jy=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}},Qy=e=>e.map(t=>({...t,streaming:!1})),Zy=e=>e.map(t=>({...t,status:"complete"})),jf=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Jy(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Qy(n.messages):void 0,artifacts:n.artifacts?Zy(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 kc=require("partial-json");function Kf(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=jr.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 Gf(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 Yf(e){let t=Gf(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 Xf(e){let t=Gf(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 ev=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Jf(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=ev}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,m.appendChild(v),g.appendChild(m);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 w=1;w<=5;w++){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",`${w} star${w>1?"s":""}: ${l[w-1]}`),x.title=l[w-1],x.dataset.rating=String(w),x.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
29
29
  </svg>
30
- `,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
+ `,x.addEventListener("click",()=>{u=w,I.forEach((E,S)=>{let k=S<w;E.classList.toggle("selected",k),E.setAttribute("aria-checked",S===w-1?"true":"false")})}),I.push(x),M.appendChild(x)}g.appendChild(M);let R=null;if(d){let w=document.createElement("div");w.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"),w.appendChild(R),g.appendChild(w)}let P=document.createElement("div");P.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(),f.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let w=(R==null?void 0:R.value.trim())||void 0;await t(u,w),f.remove()}catch(w){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),P.appendChild(D),P.appendChild(W),g.appendChild(P),f.appendChild(g),f}function Qf(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:f="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,m=document.createElement("div");m.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),m.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 P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=f,R.appendChild(P),R.appendChild(D);let W=document.createElement("div");W.className="persona-feedback-numbers";let w=[];for(let V=0;V<=10;V++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${V} out of 10`),z.textContent=String(V),z.dataset.rating=String(V),V<=6?z.classList.add("persona-feedback-detractor"):V<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=V,w.forEach((Y,he)=>{Y.classList.toggle("selected",he===V),Y.setAttribute("aria-checked",he===V?"true":"false")})}),w.push(z),W.appendChild(z)}I.appendChild(R),I.appendChild(W),m.appendChild(I);let x=null;if(d){let V=document.createElement("div");V.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"),V.appendChild(x),m.appendChild(V)}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(),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){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let V=(x==null?void 0:x.value.trim())||void 0;await t(g,V),u.remove()}catch(V){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",V)}}),E.appendChild(S),E.appendChild(k),m.appendChild(E),u.appendChild(m),u}var Ts="persona-chat-history",tv=30*1e3,nv={"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 ov(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=nv[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 cl(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 rv(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 sv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ec=e=>!e||typeof e!="object"?{}:{...e},Zf=e=>e.map(t=>({...t,streaming:!1})),eg=(e,t,n)=>{let o=e!=null&&e.markdown?xi(e.markdown):null,r=wi(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,f,u;let a=(l=s.text)!=null?l:"",i=(f=s.message.rawContent)!=null?f: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=pa(a),r?r(d):d}};function tg(e){var i,d,l,f;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=(f=e==null?void 0:e.iconStrokeWidth)!=null?f:.5,a=Me(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 ng=(e,t,n)=>{var rd,sd,ad,id,ld,cd,dd,pd,ud,md,fd,gd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Jd,Qd,Zd;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=om(t),r=Cc.getForInstance(o.plugins);o.components&&jr.registerAll(o.components);let s=zf(),i=o.persistState===!1?null:(rd=o.storageAdapter)!=null?rd:jf(),d={},l=null,f=!1,u=c=>{if(o.onStateLoaded)try{let p=o.onStateLoaded(c);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(f=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return u(h)});else{let p=c!=null?c:{messages:[],metadata:{}},h=u(p);h.metadata&&(d=Ec(h.metadata)),(sd=h.messages)!=null&&sd.length&&(o={...o,initialMessages:h.messages}),(ad=h.artifacts)!=null&&ad.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(id=h.selectedArtifactId)!=null?id: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:{}});(ld=c.messages)!=null&&ld.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,m=c=>{var h;d=(h=c({...d}))!=null?h:{},ts()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ac],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wa.message,Wa.messageAndClick],M=Tc({parsers:C,handlers:v,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(dd=(cd=o.launcher)==null?void 0:cd.enabled)!=null?dd:!0,R=(ud=(pd=o.launcher)==null?void 0:pd.autoExpand)!=null?ud:!1,P=(md=o.autoFocusInput)!=null?md:!1,D=R,W=I,w=(gd=(fd=o.layout)==null?void 0:fd.header)==null?void 0:gd.layout,x=!1,E=()=>Ta(o),S=()=>I||E(),k=E()?!1:I?R:!0,V=!1,z=null,Y=()=>{V=!0,z&&clearTimeout(z),z=setTimeout(()=>{V&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),V=!1)},1e4)},he=eg(o,M,Y),me=(bd=(hd=o.features)==null?void 0:hd.showReasoning)!=null?bd:!0,de=(vd=(yd=o.features)==null?void 0:yd.showToolCalls)!=null?vd:!0,Ee=(wd=(xd=o.features)==null?void 0:xd.showEventStreamToggle)!=null?wd:!1,xe=(Sd=(Cd=o.features)==null?void 0:Cd.scrollToBottom)!=null?Sd:{},De=(Td=(Ad=o.features)==null?void 0:Ad.scrollBehavior)!=null?Td:{},le=`${(Ed=typeof o.persistState=="object"?(kd=o.persistState)==null?void 0:kd.keyPrefix:void 0)!=null?Ed:"persona-"}event-stream`,J=Ee?new Ra(le):null,se=(Id=(Ld=(Md=o.features)==null?void 0:Md.eventStream)==null?void 0:Ld.maxEvents)!=null?Id:2e3,ye=Ee?new Ia(se,J):null,be=Ee?new Pa:null,K=null,ae=!1,Re=null,oe=0;J==null||J.open().then(()=>ye==null?void 0:ye.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ee={onCopy:c=>{var p,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=(p=o.messageActions)==null?void 0:p.onCopy)==null||h.call(p,c)},onFeedback:c=>{var p,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=(p=o.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,c)}},re=(Rd=o.statusIndicator)!=null?Rd:{},it=c=>{var p,h,y,L;return c==="idle"?(p=re.idleText)!=null?p:En.idle:c==="connecting"?(h=re.connectingText)!=null?h:En.connecting:c==="connected"?(y=re.connectedText)!=null?y:En.connected:c==="error"?(L=re.errorText)!=null?L:En.error:En[c]};function lt(c,p,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=p,L.style.color="inherit",L.style.textDecoration="none",c.appendChild(L)}else c.textContent=p}let{wrapper:Le,panel:pe,pillRoot:Je}=cf(o),Be=df(o,S()),{container:j,body:fe,messagesWrapper:tt,suggestions:Mt,textarea:te,sendButton:qe,sendButtonWrapper:Fn,composerForm:Dt,statusText:an,introTitle:oo,introSubtitle:Mo,closeButton:F,iconHolder:ue,headerTitle:Fe,headerSubtitle:Ke,header:_e,footer:$e,actionsRow:ot,leftActions:Pt,rightActions:Kt}=Be,Jt=Be.setSendButtonMode,G=Be.micButton,xt=Be.micButtonWrapper,st=Be.attachmentButton,Se=Be.attachmentButtonWrapper,ce=Be.attachmentInput,et=Be.attachmentPreviewsContainer;j.classList.add("persona-relative"),fe.classList.add("persona-relative");let Qt=12,Gt=()=>{var c;return(c=xe.label)!=null?c:""},In=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},vn=()=>xe.enabled!==!1,gt=()=>{var c;return(c=De.mode)!=null?c:"follow"},Lt=()=>{var c;return(c=De.anchorTopOffset)!=null?c:16},Qe=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");Qe.type="button",Qe.style.display="none",Qe.setAttribute("data-persona-scroll-to-bottom","true");let qt=b("span","persona-flex persona-items-center"),ln=b("span",""),Cn=b("span","");Cn.setAttribute("data-persona-scroll-to-bottom-count",""),Cn.style.display="none",Qe.append(qt,ln,Cn),j.appendChild(Qe);let Sn=b("div","persona-stream-anchor-spacer");Sn.setAttribute("aria-hidden","true"),Sn.setAttribute("data-persona-anchor-spacer",""),Sn.style.flexShrink="0",Sn.style.pointerEvents="none",Sn.style.height="0px",fe.appendChild(Sn);let yn=()=>{let p=$e.style.display==="none"?0:$e.offsetHeight;Qe.style.bottom=`${p+Qt}px`};yn();let Lo=()=>{let c=!!Gt();Qe.setAttribute("aria-label",Gt()||"Jump to latest"),Qe.title=Gt(),Qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),qt.innerHTML="";let p=Me(In(),"14px","currentColor",2);p?(qt.appendChild(p),qt.style.display=""):qt.style.display="none",ln.textContent=Gt(),ln.style.display=c?"":"none"};Lo();let At=null,Un=null,zn=r.find(c=>c.renderHeader);if(zn!=null&&zn.renderHeader){let c=zn.renderHeader({config:o,defaultRenderer:()=>{let p=$r({config:o,showClose:S()});return Ea(j,p,o),p.header},onClose:()=>Ot(!1,"user")});if(c){let p=j.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(c),_e=c)}}let Vo=()=>{var p,h,y,L;if(!ye)return;if(ae=!0,!K&&ye&&(K=Bf({buffer:ye,getFullHistory:()=>ye.getAllFromStore(),onClose:()=>yo(),config:o,plugins:r,getThroughput:()=>{var N;return(N=be==null?void 0:be.getMetric())!=null?N:{status:"idle"}}})),K&&(fe.style.display="none",(p=$e.parentNode)==null||p.insertBefore(K.element,$e),K.update()),wt){wt.style.boxShadow=`inset 0 0 0 1.5px ${Dn.actionIconColor}`;let N=(L=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:L.toggleButtonActive;N&&N.split(/\s+/).forEach(_=>_&&wt.classList.add(_))}let c=()=>{if(!ae)return;let N=Date.now();N-oe>=200&&(K==null||K.update(),oe=N),Re=requestAnimationFrame(c)};oe=0,Re=requestAnimationFrame(c),_n(),s.emit("eventStream:opened",{timestamp:Date.now()})},yo=()=>{var c,p,h;if(ae){if(ae=!1,K&&K.element.remove(),fe.style.display="",wt){wt.style.boxShadow="";let y=(h=(p=(c=o.features)==null?void 0:c.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(L=>L&&wt.classList.remove(L))}Re!==null&&(cancelAnimationFrame(Re),Re=null),_n(),s.emit("eventStream:closed",{timestamp:Date.now()})}},wt=null;if(Ee){let c=(Wd=(Pd=o.features)==null?void 0:Pd.eventStream)==null?void 0:Wd.classNames,p="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:"");wt=b("button",p),wt.style.width="28px",wt.style.height="28px",wt.style.color=Dn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let h=Me("activity","18px","currentColor",1.5);h&&wt.appendChild(h);let y=Be.clearChatButtonWrapper,L=Be.closeButtonWrapper,N=y||L;N&&N.parentNode===_e?_e.insertBefore(wt,N):_e.appendChild(wt),wt.addEventListener("click",()=>{ae?yo():Vo()})}let Cr=c=>{var y,L,N;let p=o.attachments;if(!(p!=null&&p.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=p.allowedTypes)!=null?y:Jo).join(","),_.multiple=((L=p.maxFiles)!=null?L:4)>1,_.style.display="none",_.setAttribute("aria-label",(N=p.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(_)}},Io=r.find(c=>c.renderComposer);if(Io!=null&&Io.renderComposer){let c=o.composer,p=Io.renderComposer({config:o,defaultRenderer:()=>el({config:o}).footer,onSubmit:h=>{var _;if(!$||$.isStreaming())return;let y=h.trim(),L=(_=At==null?void 0:At.hasAttachments())!=null?_:!1;if(!y&&!L)return;T();let N;L&&(N=[],N.push(...At.getContentParts()),y&&N.push(Jl(y))),$.sendMessage(y,{contentParts:N}),L&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ce==null||ce.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:((Bd=o.voiceRecognition)==null?void 0:Bd.enabled)===!0?()=>{Un==null||Un()}:void 0});p&&($e.replaceWith(p),$e=p)}let Sr=c=>{let p=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]"),N=c.querySelector("[data-persona-composer-status]");p&&(Dt=p),h&&(te=h),y&&(qe=y),L&&(G=L,xt=L.parentElement),N&&(an=N);let _=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Mt=_);let q=c.querySelector(".persona-attachment-button");q&&(st=q,Se=q.parentElement),ce=c.querySelector('input[type="file"]'),et=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(ot=O)};Cr($e),Sr($e);let On=(Nd=(Hd=o.layout)==null?void 0:Hd.contentMaxWidth)!=null?Nd:E()?(Od=(Fd=(Dd=o.launcher)==null?void 0:Dd.composerBar)==null?void 0:Fd.contentMaxWidth)!=null?Od:"720px":void 0;if(On&&(tt.style.maxWidth=On,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%"),On&&Dt&&!E()&&(Dt.style.maxWidth=On,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),On&&Mt&&!E()&&(Mt.style.maxWidth=On,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),On&&et&&!E()&&(et.style.maxWidth=On,et.style.marginLeft="auto",et.style.marginRight="auto"),(_d=o.attachments)!=null&&_d.enabled&&ce&&et){At=va.fromConfig(o.attachments),At.setPreviewsContainer(et),ce.addEventListener("change",h=>{let y=h.target;At==null||At.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,p=tg(c);j.appendChild(p)}(()=>{var y,L;let c=(L=(y=o.layout)==null?void 0:y.slots)!=null?L:{},p=N=>{switch(N){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return tt;case"footer-top":return Mt;case"composer":return Dt;case"footer-bottom":return an;default:return null}},h=(N,_)=>{var q;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")_e.insertBefore(_,_e.firstChild);else if(N==="header-right")_e.appendChild(_);else{let O=_e.querySelector(".persona-flex-col");O?(q=O.parentNode)==null||q.insertBefore(_,O.nextSibling):_e.appendChild(_)}break;case"body-top":{let O=fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(_):fe.insertBefore(_,fe.firstChild);break}case"body-bottom":fe.appendChild(_);break;case"footer-top":Mt.replaceWith(_);break;case"footer-bottom":an.replaceWith(_);break;default:break}};for(let[N,_]of Object.entries(c))if(_)try{let q=_({config:o,defaultContent:()=>p(N)});q&&h(N,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,q)}})();let Zo=c=>{var _,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 N=h.getAttribute("data-bubble-type");if(N==="reasoning")ys.has(L)?ys.delete(L):ys.add(L),mf(L,y);else if(N==="tool")vs.has(L)?vs.delete(L):vs.add(L),ff(L,y,o);else if(N==="approval"){let O=o.approval!==!1?o.approval:void 0,Ce=((_=O==null?void 0:O.detailsDisplay)!=null?_:"collapsed")==="expanded",ge=(q=rl.get(L))!=null?q:Ce;rl.set(L,!ge),Lf(L,y,o)}qo.delete(L)};tt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Zo(c))}),tt.addEventListener("keydown",c=>{let p=c.target;(c.key==="Enter"||c.key===" ")&&p.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Zo(c))});let $o=new Map;tt.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 L=y.getAttribute("data-actions-for");if(!L)return;let N=h.getAttribute("data-action");if(N==="copy"){let O=$.getMessages().find(Ce=>Ce.id===L);if(O&&ee.onCopy){let Ce=O.content||"";navigator.clipboard.writeText(Ce).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 ne=Me("copy",14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),ee.onCopy(O)}}else if(N==="upvote"||N==="downvote"){let O=((_=$o.get(L))!=null?_:null)===N,Ce=N==="upvote"?"thumbs-up":"thumbs-down";if(O){$o.delete(L),h.classList.remove("persona-message-action-active");let ge=Me(Ce,14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))}else{let ge=N==="upvote"?"downvote":"upvote",ne=y.querySelector(`[data-action="${ge}"]`);if(ne){ne.classList.remove("persona-message-action-active");let je=Me(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);je&&(ne.innerHTML="",ne.appendChild(je))}$o.set(L,N),h.classList.add("persona-message-action-active");let ke=Me(Ce,14,"currentColor",2);ke&&(ke.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ke)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Te=$.getMessages().find(nt=>nt.id===L);Te&&ee.onFeedback&&ee.onFeedback({type:N,messageId:Te.id,message:Te})}}}),tt.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 N=h.getAttribute("data-approval-action");if(!N)return;let _=N==="approve"?"approved":"denied",O=$.getMessages().find(ge=>ge.id===L);if(!(O!=null&&O.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?$.resolveWebMcpApproval(L,_):$.resolveApproval(O.approval,_)});let Tt=null,qn=null,jn={artifacts:[],selectedId:null},Rn=!1,Rt={current:null};tt.addEventListener("click",c=>{var ne,ke,Ve,Te,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||((Ve=(ke=(ne=o.features)==null?void 0:ne.artifacts)==null?void 0:ke.onArtifactAction)==null?void 0:Ve.call(ke,{type:"download",artifactId:y}))===!0)return;let N=$.getArtifactById(y),_=N==null?void 0:N.markdown,q=(N==null?void 0:N.title)||"artifact";if(!_){let je=h.closest("[data-open-artifact]"),dt=je==null?void 0:je.closest("[data-message-id]"),pt=dt==null?void 0:dt.getAttribute("data-message-id");if(pt){let Ie=$.getMessages().find(ze=>ze.id===pt);if(Ie!=null&&Ie.rawContent)try{let ze=JSON.parse(Ie.rawContent);_=(Te=ze==null?void 0:ze.props)==null?void 0:Te.markdown,q=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||q}catch{}}}if(!_)return;let O=new Blob([_],{type:"text/markdown"}),Ce=URL.createObjectURL(O),ge=document.createElement("a");ge.href=Ce,ge.download=`${q}.md`,ge.click(),URL.revokeObjectURL(Ce)}),tt.addEventListener("click",c=>{var N,_,q;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((q=(_=(N=o.features)==null?void 0:N.artifacts)==null?void 0:_.onArtifactAction)==null?void 0:q.call(_,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Rn=!1,$.selectArtifact(y),Yn())}),tt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let p=c.target;p.hasAttribute("data-open-artifact")&&(c.preventDefault(),p.click())});let ro=Be.composerOverlay,so=(c,p,h)=>{var q,O,Ce,ge;let y=p.trim();if(!y||!Rt.current)return;let L=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),Ss(ro,L);let _=Rt.current.getMessages().find(ne=>{var ke;return((ke=ne.toolCall)==null?void 0:ke.id)===L});(Ce=_==null?void 0:_.agentMetadata)!=null&&Ce.awaitingLocalTool?Rt.current.resolveAskUserQuestion(_,(ge=h.structured)!=null?ge:y):Rt.current.sendMessage(y)},Kn=c=>{var L;let p=Rt.current;if(!p)return;let h=(L=c.getAttribute("data-tool-call-id"))!=null?L:"",y=p.getMessages().find(N=>{var _;return((_=N.toolCall)==null?void 0:_.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:tl(c,y),currentIndex:ho(c)})},er=c=>Object.entries(c).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Uo=c=>{var L,N,_;if(((N=(L=o.features)==null?void 0:L.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let p=ho(c),h=Cs(c);if(p>=h-1)return;let y=(_=Rt.current)==null?void 0:_.getMessages().find(q=>{var O;return((O=q.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(ol(c,y,o,p+1),Kn(c))};ro.addEventListener("click",c=>{var N,_,q,O,Ce,ge,ne,ke,Ve,Te,nt,je,dt,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=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Ss(ro,We);let Ie=(_=Rt.current)==null?void 0:_.getMessages().find(ze=>{var Ye;return((Ye=ze.toolCall)==null?void 0:Ye.id)===We});(q=Ie==null?void 0:Ie.agentMetadata)!=null&&q.awaitingLocalTool&&((O=Rt.current)==null||O.markAskUserQuestionResolved(Ie),(Ce=Rt.current)==null||Ce.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(L==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Ie=y.getAttribute("data-multi-select")==="true",ze=yr(y);if(ze&&Ie){let Ye=zr(y)[ho(y)],Ct=new Set(Array.isArray(Ye)?Ye:[]);Ct.has(We)?Ct.delete(We):Ct.add(We),vr(y,Array.from(Ct)),Kn(y);return}if(ze){vr(y,We),Kn(y),Uo(y);return}if(Ie){let Ye=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ye?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ye);let Ct=y.querySelector('[data-ask-user-action="submit-multi"]');Ct&&(Ct.disabled=hc(y).length===0);return}so(y,We,{source:"pick",values:[We]});return}if(L==="submit-multi"){let We=hc(y);if(We.length===0)return;so(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 Ie=We.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.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"]'),Ie=(ge=We==null?void 0:We.value)!=null?ge:"";if(!Ie.trim())return;if(yr(y)){vr(y,Ie.trim()),Kn(y),Uo(y);return}so(y,Ie,{source:"free-text"});return}if(L==="next"||L==="back"){if(!Rt.current)return;let We=(ne=y.getAttribute("data-tool-call-id"))!=null?ne:"",Ie=Rt.current.getMessages().find(He=>{var Oe;return((Oe=He.toolCall)==null?void 0:Oe.id)===We});if(!Ie)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(Ve=(ke=ze==null?void 0:ze.value)==null?void 0:ke.trim())!=null?Ve:"";if(Ye){let He=zr(y)[ho(y)];(typeof He!="string"||He!==Ye)&&vr(y,Ye)}let Ct=L==="next"?1:-1,H=ho(y)+Ct;ol(y,Ie,o,H),Kn(y);return}if(L==="submit-all"){if(!Rt.current)return;let We=(Te=y.getAttribute("data-tool-call-id"))!=null?Te:"",Ie=Rt.current.getMessages().find(He=>{var Oe;return((Oe=He.toolCall)==null?void 0:Oe.id)===We});if(!Ie)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(je=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?je:"";Ye&&vr(y,Ye);let Ct=tl(y,Ie);Rt.current.persistAskUserQuestionProgress(Ie,{answers:Ct,currentIndex:ho(y)});let H=er(Ct);so(y,H||"(submitted)",{source:"submit-all",structured:Ct});return}if(L==="skip"){if(!Rt.current)return;let We=(dt=y.getAttribute("data-tool-call-id"))!=null?dt:"",Ie=Rt.current.getMessages().find(Oe=>{var ve;return((ve=Oe.toolCall)==null?void 0:ve.id)===We});if(!Ie)return;let ze=yr(y),Ye=ho(y),Ct=Cs(y),H=Ye>=Ct-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Ss(ro,We),(pt=Ie.agentMetadata)!=null&&pt.awaitingLocalTool&&(Rt.current.markAskUserQuestionResolved(Ie),Rt.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}vr(y,"");let He=y.querySelector('[data-ask-free-text-input="true"]');if(He&&(He.value=""),H){let Oe=tl(y,Ie),ve=er(Oe);so(y,ve||"(skipped)",{source:"submit-all",structured:Oe});return}ol(y,Ie,o,Ye+1),Kn(y);return}}),ro.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let h=c.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let L=h.value;if(L.trim()){if(yr(y)){vr(y,L.trim()),Kn(y),Uo(y);return}so(y,L,{source:"free-text"})}});let tr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let p=c.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=ro.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),N=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",tr);let Gn=null,Ft=null,Pn=null,ao=null,nr=()=>{};function zo(){ao==null||ao(),ao=null}let or=()=>{var _;if(!Gn||!Ft)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){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=Gn.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 N=y.offsetWidth-L/2;Ft.style.left=`${Math.max(0,N)}px`},Ro=()=>{},Yn=()=>{var h,y,L,N,_;if(!Tt||!bo(o))return;il(e,o),ll(e,o),Ro();let c=(N=(L=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:L.narrowHostMaxWidth)!=null?N:520,p=pe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=c),Tt.update(jn),Rn?(Tt.setMobileOpen(!1),Tt.element.classList.add("persona-hidden"),(_=Tt.backdrop)==null||_.classList.add("persona-hidden")):jn.artifacts.length>0&&(Tt.element.classList.remove("persona-hidden"),Tt.setMobileOpen(!0)),nr()};if(bo(o)){pe.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(j),Tt=Ff(o,{onSelect:h=>{var y;return(y=Rt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Rn=!0,Yn()}}),Tt.element.classList.add("persona-hidden"),Gn=p,p.appendChild(c),p.appendChild(Tt.element),Tt.backdrop&&pe.appendChild(Tt.backdrop),pe.appendChild(p),nr=()=>{var y,L,N,_;if(!Gn||!Tt)return;if(!(((N=(L=(y=o.features)==null?void 0:y.artifacts)==null?void 0:L.layout)==null?void 0:N.resizable)===!0)){Pn==null||Pn(),Pn=null,zo(),Ft&&(Ft.remove(),Ft=null),Tt.element.style.removeProperty("width"),Tt.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 O=e.ownerDocument,Ce=(_=O.defaultView)!=null?_:window,ge=ne=>{var dt,pt;if(!Tt||ne.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;ne.preventDefault(),zo();let ke=ne.clientX,Ve=Tt.element.getBoundingClientRect().width,Te=(pt=(dt=o.features)==null?void 0:dt.artifacts)==null?void 0:pt.layout,nt=We=>{let Ie=Gn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ye=ze?0:Vf(Gn,Ce),Ct=ze?0:q.getBoundingClientRect().width||6,H=Ve-(We.clientX-ke),He=$f(H,Ie,Ye,Ct,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);Tt.element.style.width=`${He}px`,Tt.element.style.maxWidth="none",or()},je=()=>{O.removeEventListener("pointermove",nt),O.removeEventListener("pointerup",je),O.removeEventListener("pointercancel",je),ao=null;try{q.releasePointerCapture(ne.pointerId)}catch{}};ao=je,O.addEventListener("pointermove",nt),O.addEventListener("pointerup",je),O.addEventListener("pointercancel",je);try{q.setPointerCapture(ne.pointerId)}catch{}};q.addEventListener("pointerdown",ge),Ft=q,Gn.insertBefore(q,Tt.element),Pn=()=>{q.removeEventListener("pointerdown",ge)}}if(Ft){let q=jn.artifacts.length>0&&!Rn;Ft.classList.toggle("persona-hidden",!q),or()}},Ro=()=>{var Ce,ge,ne,ke,Ve,Te,nt,je,dt,pt,We,Ie,ze,Ye;if(!I||!Tt||((ge=(Ce=o.launcher)==null?void 0:Ce.sidebarMode)!=null?ge:!1)||wn(o)&&No(o).reveal==="emerge")return;let y=(ne=e.ownerDocument.defaultView)!=null?ne:window,L=(Ve=(ke=o.launcher)==null?void 0:ke.mobileFullscreen)!=null?Ve:!0,N=(nt=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?nt:640;if(L&&y.innerWidth<=N||!_f(o,I))return;let _=(pt=(dt=(je=o.launcher)==null?void 0:je.width)!=null?dt:o.launcherWidth)!=null?pt:go,q=(Ye=(ze=(Ie=(We=o.features)==null?void 0:We.artifacts)==null?void 0:Ie.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ye:"min(720px, calc(100vw - 24px))";jn.artifacts.length>0&&!Rn?(pe.style.width=q,pe.style.maxWidth=q):(pe.style.width=_,pe.style.maxWidth=_)},typeof ResizeObserver!="undefined"&&(qn=new ResizeObserver(()=>{Yn()}),qn.observe(pe))}else pe.appendChild(j),E()&&Je&&(Be.peekBanner&&Je.appendChild(Be.peekBanner),Je.appendChild($e));e.appendChild(Le),Je&&e.appendChild(Je);let vo=()=>{var He,Oe,ve,Vt,Nt,Yt,St,jt,Zn,rn,Xe,Wt,dn,mo,eo,Mr,Lr,is,ls,Xt,Ir,ur,mr,Xo,rt,xn,Wn,sn;if(E()){pe.style.width="100%",pe.style.maxWidth="100%";let ut=(Oe=(He=o.launcher)==null?void 0:He.composerBar)!=null?Oe:{},yt=Le.dataset.state==="expanded",mt=(ve=ut.expandedSize)!=null?ve:"anchored";if(!(yt&&mt!=="fullscreen")){j.style.background="",j.style.border="",j.style.borderRadius="",j.style.overflow="",j.style.boxShadow="";return}let pn=(Nt=(Vt=o.theme)==null?void 0:Vt.components)==null?void 0:Nt.panel,Fo=ci(o),un=(Pr,ai)=>{var Ks;return Pr==null||Pr===""?ai:(Ks=cs(Fo,Pr))!=null?Ks:Pr},Bn="1px solid var(--persona-border)",fo="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Rr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";j.style.background="var(--persona-surface, #ffffff)",j.style.border=un(pn==null?void 0:pn.border,Bn),j.style.borderRadius=un(pn==null?void 0:pn.borderRadius,Rr),j.style.boxShadow=un(pn==null?void 0:pn.shadow,fo),j.style.overflow="hidden";return}let c=wn(o),p=(St=(Yt=o.launcher)==null?void 0:Yt.sidebarMode)!=null?St:!1,h=c||p||((Zn=(jt=o.launcher)==null?void 0:jt.fullHeight)!=null?Zn:!1),y=((rn=o.launcher)==null?void 0:rn.enabled)===!1,L=(Wt=(Xe=o.theme)==null?void 0:Xe.components)==null?void 0:Wt.panel,N=ci(o),_=(ut,yt)=>{var mt;return ut==null||ut===""?yt:(mt=cs(N,ut))!=null?mt:ut},q=(dn=e.ownerDocument.defaultView)!=null?dn:window,O=(eo=(mo=o.launcher)==null?void 0:mo.mobileFullscreen)!=null?eo:!0,Ce=(Lr=(Mr=o.launcher)==null?void 0:Mr.mobileBreakpoint)!=null?Lr:640,ge=q.innerWidth<=Ce,ne=O&&ge&&I,ke=(ls=(is=o.launcher)==null?void 0:is.position)!=null?ls:"bottom-left",Ve=ke==="bottom-left"||ke==="top-left",Te=(Ir=(Xt=o.launcher)==null?void 0:Xt.zIndex)!=null?Ir:Mn,nt=p||ne?"none":"1px solid var(--persona-border)",je=ne?"none":p?Ve?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ne&&(je="none",nt="none");let dt=p||ne?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=_(L==null?void 0:L.border,nt),We=_(L==null?void 0:L.shadow,je),Ie=_(L==null?void 0:L.borderRadius,dt),ze=fe.scrollTop;e.style.cssText="",Le.style.cssText="",pe.style.cssText="",j.style.cssText="",fe.style.cssText="",$e.style.cssText="";let Ye=()=>{var yt;if(ze<=0)return;((yt=fe.ownerDocument.defaultView)!=null?yt:window).requestAnimationFrame(()=>{if(fe.scrollTop===ze)return;let mt=fe.scrollHeight-fe.clientHeight;mt<=0||(fe.scrollTop=Math.min(ze,mt))})};if(ne){Le.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"),Le.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: ${Te} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
- `,ce.style.cssText=`
42
+ `,pe.style.cssText=`
43
43
  position: relative !important;
44
44
  display: flex !important;
45
45
  flex-direction: column !important;
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:o}var 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
+ `,j.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
+ `,fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.overflowY="auto",$e.style.flexShrink="0",x=!0,Ye();return}let Ct=(mr=(ur=o==null?void 0:o.launcher)==null?void 0:ur.width)!=null?mr:o==null?void 0:o.launcherWidth,H=Ct!=null?Ct:go;if(!p&&!c)y&&h?(pe.style.width="100%",pe.style.maxWidth="100%"):(pe.style.width=H,pe.style.maxWidth=H);else if(c)if(No(o).reveal==="emerge"){let yt=No(o).width;pe.style.width=yt,pe.style.maxWidth=yt}else pe.style.width="100%",pe.style.maxWidth="100%";if(Ro(),pe.style.boxShadow=We,pe.style.borderRadius=Ie,j.style.border=pt,j.style.borderRadius=Ie,c&&!ne&&(L==null?void 0:L.border)===void 0&&(j.style.border="none",No(o).side==="right"?j.style.borderLeft="1px solid var(--persona-border)":j.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%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",y&&(Le.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.height="100%",pe.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.overflowY="auto",$e.style.flexShrink="0"),Le.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"),!p&&!y&&!c&&((Xo=Eo[ke])!=null?Xo:Eo["bottom-right"]).split(" ").forEach(yt=>Le.classList.add(yt)),p){let ut=(xn=(rt=o.launcher)==null?void 0:rt.sidebarWidth)!=null?xn:"420px";Le.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${Ft} !important;
70
+ width: ${ut} !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: ${Te} !important;
78
+ ${Ve?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
+ `,pe.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
82
82
  flex-direction: column !important;
@@ -88,8 +88,8 @@ _Details: ${n.message}_`:o}var na=e=>({isError:!0,content:[{type:"text",text:e}]
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
90
  box-shadow: ${We} !important;
91
- border-radius: ${Pe} !important;
92
- `,ce.style.setProperty("width","100%","important"),ce.style.setProperty("max-width","100%","important"),de.style.cssText=`
91
+ border-radius: ${Ie} !important;
92
+ `,pe.style.setProperty("width","100%","important"),pe.style.setProperty("max-width","100%","important"),j.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
95
  flex: 1 1 0% !important;
@@ -98,13 +98,13 @@ _Details: ${n.message}_`:o}var na=e=>({isError:!0,content:[{type:"text",text:e}]
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${Pe} !important;
102
- border: ${lt} !important;
103
- `,Ue.style.cssText=`
101
+ border-radius: ${Ie} !important;
102
+ border: ${pt} !important;
103
+ `,$e.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!y&&!c){let 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 ut="max-height: -moz-available !important; max-height: stretch !important;",yt=p?"":"padding-top: 1.25em !important;",mt=p?"":`z-index: ${(sn=(Wn=o.launcher)==null?void 0:Wn.zIndex)!=null?sn:Mn} !important;`;Le.style.cssText+=ut+yt+mt}Ye()};vo(),ds(e,o),il(e,o),ll(e,o);let bt=[];bt.push(()=>{document.removeEventListener("keydown",tr)});let Zt=null,en=null;bt.push(()=>{Zt==null||Zt(),Zt=null,en==null||en(),en=null}),qn&&bt.push(()=>{qn==null||qn.disconnect(),qn=null}),bt.push(()=>{Pn==null||Pn(),Pn=null,zo(),Ft&&(Ft.remove(),Ft=null),Tt==null||Tt.element.style.removeProperty("width"),Tt==null||Tt.element.style.removeProperty("maxWidth")}),Ee&&bt.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),K==null||K.destroy(),K=null,ye==null||ye.destroy(),ye=null,J=null});let Xn=null,rr=()=>{Xn&&(Xn(),Xn=null),o.colorScheme==="auto"&&(Xn=lm(()=>{ds(e,o)}))};rr(),bt.push(()=>{Xn&&(Xn(),Xn=null)});let we=(Vd=o.features)==null?void 0:Vd.streamAnimation;if(we!=null&&we.type&&we.type!=="none"){let c=wa(we.type,we.plugins);c&&(tc(c,e),bt.push(()=>of(e)))}let io=If(Mt),lo=null,$,Po=!1,qo=Gm(),jo=new Map,Wo=new Map,xo=new Map,Is=0,Jn=Oi(),Qn=0,wo=null,Co=!1,Ar=!1,Ko=0,An=null,Bo=null,Jr=!1,Tr=!1,Qr=null,za=4,Zr=24,qa=80,es=new Map,vt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Rs=(Ud=($d=o.voiceRecognition)==null?void 0:$d.autoResume)!=null?Ud:!1,co=c=>{s.emit("voice:state",{active:vt.active,source:c,timestamp:Date.now()})},Nn=()=>{m(c=>({...c,voiceState:{active:vt.active,timestamp:Date.now(),manuallyDeactivated:vt.manuallyDeactivated}}))},ja=()=>{var y,L;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Ec(d.voiceState),p=!!c.active,h=Number((L=c.timestamp)!=null?L:0);vt.manuallyDeactivated=!!c.manuallyDeactivated,p&&Date.now()-h<tv&&setTimeout(()=>{var N,_;vt.active||(vt.manuallyDeactivated=!1,((_=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:_.type)==="runtype"?$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),co("restore"),$.isVoiceActive()&&zs()}):fn("restore"))},1e3)},Ka=()=>$?Zf($.getMessages()).filter(c=>!c.__skipPersist):[];function ts(c){if(!(i!=null&&i.save))return;let h={messages:c?Zf(c):$?Ka():[],metadata:d,artifacts:jn.artifacts,selectedArtifactId:jn.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 Go=null,Ps=()=>Le.querySelector("#persona-scroll-container")||fe,sr=()=>{Go!==null&&(cancelAnimationFrame(Go),Go=null),Co=!1},Ws=()=>{wo!==null&&(cancelAnimationFrame(wo),wo=null),Ar=!1,sr()},Bs=()=>{Ko>0?(Cn.textContent=String(Ko),Cn.style.display="",Qe.setAttribute("aria-label",`${Gt()||"Jump to latest"} (${Ko} new)`)):(Cn.textContent="",Cn.style.display="none",Qe.setAttribute("aria-label",Gt()||"Jump to latest"))},Hs=()=>{Ko!==0&&(Ko=0,Bs())},Ds=()=>gt()==="follow"?!Jn.isFollowing():!Vr(fe,Zr),_n=()=>{if(!vn()||ae){Qe.parentNode&&Qe.remove(),Qe.style.display="none";return}Qe.parentNode!==j&&j.appendChild(Qe),yn();let p=Qo(fe)>0&&Ds();p||Hs(),Qe.style.display=p?"":"none"},ns=()=>{Jn.pause()&&(Ws(),_n())},Ho=()=>{Jn.resume(),Hs(),_n()},Do=(c=!1)=>{gt()==="follow"&&Jn.isFollowing()&&(!c&&!Po||(wo!==null&&(cancelAnimationFrame(wo),wo=null),Ar=!0,wo=requestAnimationFrame(()=>{wo=null,Ar=!1,Jn.isFollowing()&&Ga(Ps(),c?220:140)})))},Fs=(c,p,h,y=()=>!0)=>{let L=c.scrollTop,N=p(),_=N-L;sr();let q=performance.now();Co=!0;let O=ge=>1-Math.pow(1-ge,3),Ce=ge=>{if(!y()){sr();return}let ne=p();ne!==N&&(N=ne,_=N-L);let ke=ge-q,Ve=Math.min(ke/h,1),Te=O(Ve),nt=L+_*Te;c.scrollTop=nt,Qn=c.scrollTop,Ve<1?Go=requestAnimationFrame(Ce):(c.scrollTop=N,Qn=c.scrollTop,Go=null,Co=!1)};Go=requestAnimationFrame(Ce)},Ga=(c,p=500)=>{let h=Qo(c)-c.scrollTop;if(Math.abs(h)<1){Qn=c.scrollTop;return}if(Math.abs(h)>=qa){sr(),Co=!0,c.scrollTop=Qo(c),Qn=c.scrollTop,Co=!1;return}Fs(c,()=>Qo(c),p,()=>Jn.isFollowing())},Os=()=>{let c=Ps();Co=!0,c.scrollTop=Qo(c),Qn=c.scrollTop,Co=!1,_n()},Ns=c=>{Sn.style.height=`${Math.max(0,Math.round(c))}px`,An&&(An.spacerHeight=Math.max(0,c))},kr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),sr(),An=null,Sn.style.height="0px"},Ya=c=>{Bo!==null&&cancelAnimationFrame(Bo),Bo=requestAnimationFrame(()=>{var Ce;Bo=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=fe.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,L=h;for(;L&&L!==fe;)y+=L.offsetTop,L=L.offsetParent;let N=(Ce=An==null?void 0:An.spacerHeight)!=null?Ce:0,_=fe.scrollHeight-N,{targetScrollTop:q,spacerHeight:O}=Zm({anchorOffsetTop:y,topOffset:Lt(),viewportHeight:fe.clientHeight,contentHeight:_});An={initialSpacerHeight:O,contentHeightAtAnchor:_,spacerHeight:O},Ns(O),Fs(fe,()=>q,220)})},Xa=()=>{if(gt()==="follow"){if(!Jn.isFollowing()||Vr(fe,1))return;Do(!Po);return}if(An&&An.initialSpacerHeight>0){let c=fe.scrollHeight-An.spacerHeight,p=ef({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:c});p!==An.spacerHeight&&Ns(p)}_n()},Ja=c=>{let p=gt();p==="follow"?(Ho(),Do(!0)):p==="anchor-top"&&Ya(c)},Qa=c=>{let p=new Map;c.forEach(h=>{let y=es.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!Tr&&gt()!=="anchor-top"&&Ds()&&(Ko+=1,Bs(),_n())),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}))}),es.clear(),p.forEach((h,y)=>{es.set(y,h)})},Er=(c,p,h)=>{var pt,We,Ie,ze,Ye,Ct;let y=document.createElement("div"),N=(()=>{var He;let H=r.find(Oe=>Oe.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((He=o.loadingIndicator)!=null&&He.render)return o.loadingIndicator.render})(),_=(H,He)=>He==null?!1:typeof He=="string"?(H.textContent=He,!0):(H.appendChild(He),!0),q=new Set,O=new Set,Ce=r.some(H=>H.renderAskUserQuestion),ge=[],ne=[],ke=o.enableComponentStreaming!==!1,Ve=r.some(H=>H.renderApproval)&&o.approval!==!1,Te=[];if(p.forEach(H=>{var Xe,Wt,dn,mo,eo,Mr,Lr,is,ls,Xt,Ir,ur,mr,Xo;q.add(H.id);let He=Ce&&Ur(H),Oe=Ve&&H.variant==="approval"&&!!H.approval,ve=!He&&H.role==="assistant"&&!H.variant&&ke&&Yf(H);if(!Oe&&xo.has(H.id)){let rt=c.querySelector(`#wrapper-${H.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),xo.delete(H.id)}if(!ve&&Wo.has(H.id)){let rt=c.querySelector(`#wrapper-${H.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Wo.delete(H.id)}let Vt=Ur(H)?`:${(Xe=H.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Wt=H.agentMetadata)!=null&&Wt.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt=Km(H,Is)+Vt,Yt=He||Oe||ve?null:Ym(qo,H.id,Nt);if(Yt){y.appendChild(Yt.cloneNode(!0)),Ur(H)&&((dn=H.toolCall)!=null&&dn.id)&&((mo=H.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((eo=H.agentMetadata)!=null&&eo.askUserQuestionAnswered)&&(O.add(H.toolCall.id),nl(H,o,Be.composerOverlay));return}let St=null,jt=r.find(rt=>!!(H.variant==="reasoning"&&rt.renderReasoning||H.variant==="tool"&&rt.renderToolCall||!H.variant&&rt.renderMessage)),Zn=(Mr=o.layout)==null?void 0:Mr.messages;if(Ur(H)&&((Lr=H.agentMetadata)==null?void 0:Lr.askUserQuestionAnswered)===!0){jo.delete(H.id);let rt=c.querySelector(`#wrapper-${H.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(Ur(H)&&((ls=(is=o.features)==null?void 0:is.askUserQuestion)==null?void 0:ls.enabled)!==!1){let rt=r.find(xn=>typeof xn.renderAskUserQuestion=="function");if(rt&&Rt.current){let xn=jo.get(H.id),Wn=xn!==Nt,sn=null;if(Wn){let{payload:mt,complete:Vn}=ws(H),pn=H.id,Fo=()=>{var un;return(un=Rt.current)==null?void 0:un.getMessages().find(Bn=>Bn.id===pn)};sn=rt.renderAskUserQuestion({message:H,payload:mt,complete:Vn,resolve:un=>{var fo;let Bn=Fo();Bn&&((fo=Rt.current)==null||fo.resolveAskUserQuestion(Bn,un))},dismiss:()=>{var Bn,fo,Rr;let un=Fo();(Bn=un==null?void 0:un.agentMetadata)!=null&&Bn.awaitingLocalTool&&((fo=Rt.current)==null||fo.markAskUserQuestionResolved(un),(Rr=Rt.current)==null||Rr.resolveAskUserQuestion(un,"(dismissed)"))},config:o})}let ut=xn!=null;if(Wn&&sn===null&&!ut){((Xt=H.agentMetadata)==null?void 0:Xt.awaitingLocalTool)===!0&&!((Ir=H.agentMetadata)!=null&&Ir.askUserQuestionAnswered)&&(O.add(H.toolCall.id),nl(H,o,Be.composerOverlay));return}let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${H.id}`,yt.setAttribute("data-wrapper-id",H.id),yt.setAttribute("data-ask-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),y.appendChild(yt),ge.push({messageId:H.id,fingerprint:Nt,bubble:sn});return}else{((ur=H.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((mr=H.agentMetadata)!=null&&mr.askUserQuestionAnswered)&&(O.add(H.toolCall.id),nl(H,o,Be.composerOverlay));return}}else if(Oe){let rt=r.find(ut=>typeof ut.renderApproval=="function"),Wn=xo.get(H.id)!==Nt,sn=null;if(Wn&&(rt!=null&&rt.renderApproval)){let ut=H.id,yt=(mt,Vn)=>{var Fo,un,Bn;let pn=(Fo=Rt.current)==null?void 0:Fo.getMessages().find(fo=>fo.id===ut);pn!=null&&pn.approval&&(pn.approval.toolType==="webmcp"?(un=Rt.current)==null||un.resolveWebMcpApproval(pn.id,mt):(Bn=Rt.current)==null||Bn.resolveApproval(pn.approval,mt,Vn))};sn=rt.renderApproval({message:H,defaultRenderer:()=>sl(H,o),config:o,approve:mt=>yt("approved",mt),deny:mt=>yt("denied",mt)})}if(Wn&&sn===null){let ut=c.querySelector(`#wrapper-${H.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),xo.delete(H.id),St=sl(H,o)}else{let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${H.id}`,ut.setAttribute("data-wrapper-id",H.id),ut.setAttribute("data-approval-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),Te.push({messageId:H.id,fingerprint:Nt,bubble:sn});return}}else if(jt)if(H.variant==="reasoning"&&H.reasoning&&jt.renderReasoning){if(!me)return;St=jt.renderReasoning({message:H,defaultRenderer:()=>lc(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&jt.renderToolCall){if(!de)return;St=jt.renderToolCall({message:H,defaultRenderer:()=>cc(H,o),config:o})}else jt.renderMessage&&(St=jt.renderMessage({message:H,defaultRenderer:()=>{let rt=ic(H,h,Zn,o.messageActions,ee,{loadingIndicatorRenderer:N,widgetConfig:o});return H.role!=="user"&&xc(rt,H,o,$),rt},config:o}));if(!St&&ve){let rt=Xf(H);if(rt){let xn=Wo.get(H.id),Wn=xn!==Nt,sn=o.wrapComponentDirectiveInBubble!==!1,ut=null;if(Wn){let yt=Kf(rt,{config:o,message:H,transform:h});if(yt)if(sn){let mt=document.createElement("div");if(mt.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(" "),mt.id=`bubble-${H.id}`,mt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Vn=document.createElement("div");Vn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Vn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),mt.appendChild(Vn)}mt.appendChild(yt),ut=mt}else{let mt=document.createElement("div");if(mt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",mt.id=`bubble-${H.id}`,mt.setAttribute("data-message-id",H.id),mt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Vn=document.createElement("div");Vn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Vn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),mt.appendChild(Vn)}mt.appendChild(yt),ut=mt}}if(ut||xn!=null){let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${H.id}`,yt.setAttribute("data-wrapper-id",H.id),yt.setAttribute("data-component-directive-stub","true"),yt.setAttribute("data-preserve-runtime","true"),sn||yt.classList.add("persona-w-full"),y.appendChild(yt),ne.push({messageId:H.id,fingerprint:Nt,bubble:ut});return}}}if(!St)if(H.variant==="reasoning"&&H.reasoning){if(!me)return;St=lc(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!de)return;St=cc(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;St=sl(H,o)}else{let rt=(Xo=o.layout)==null?void 0:Xo.messages;rt!=null&&rt.renderUserMessage&&H.role==="user"?St=rt.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):rt!=null&&rt.renderAssistantMessage&&H.role==="assistant"?St=rt.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):St=ic(H,h,rt,o.messageActions,ee,{loadingIndicatorRenderer:N,widgetConfig:o}),H.role!=="user"&&St&&xc(St,H,o,$)}let rn=document.createElement("div");rn.className="persona-flex",rn.id=`wrapper-${H.id}`,rn.setAttribute("data-wrapper-id",H.id),H.role==="user"&&rn.classList.add("persona-justify-end"),(St==null?void 0:St.getAttribute("data-persona-component-directive"))==="true"&&rn.classList.add("persona-w-full"),rn.appendChild(St),Xm(qo,H.id,Nt,rn),y.appendChild(rn)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Oe=He.getAttribute("data-persona-ask-sheet-for");Oe&&!O.has(Oe)&&Ss(Be.composerOverlay,Oe)}),(We=(pt=o.features)==null?void 0:pt.toolCallDisplay)!=null&&We.grouped){let H=[],He=[];p.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&de){He.push(Oe);return}He.length>1&&H.push(He),He=[]}),He.length>1&&H.push(He),H.forEach((Oe,ve)=>{var Xe,Wt;let Vt=Oe.map(dn=>Array.from(y.children).find(mo=>mo instanceof HTMLElement&&mo.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if(Vt.length<2)return;let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id=`wrapper-tool-group-${ve}-${Oe[0].id}`,Nt.setAttribute("data-wrapper-id",`tool-group-${ve}-${Oe[0].id}`);let Yt=document.createElement("div");Yt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Yt.setAttribute("data-persona-tool-group","true");let St=document.createElement("div");St.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${Oe.length} tools`,Zn=(Wt=(Xe=o.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Wt.call(Xe,{messages:Oe,toolCalls:Oe.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:jt,config:o});_(St,Zn)||(St.textContent=jt);let rn=document.createElement("div");rn.className="persona-tool-group-stack persona-flex persona-flex-col",Yt.append(St,rn),Nt.appendChild(Yt),Vt[0].before(Nt),Vt.forEach((dn,mo)=>{let eo=document.createElement("div");eo.className="persona-tool-group-item persona-relative",eo.setAttribute("data-persona-tool-group-item","true"),mo<Vt.length-1&&eo.setAttribute("data-persona-tool-group-connector","true"),eo.appendChild(dn),rn.appendChild(eo)})})}Jm(qo,q);let nt=p.some(H=>H.role==="assistant"&&H.streaming),je=p[p.length-1],dt=(je==null?void 0:je.role)==="assistant"&&!je.streaming&&je.variant!=="approval";if(Po&&p.some(H=>H.role==="user")&&!nt&&!dt){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:Ma},He=r.find(ve=>ve.renderLoadingIndicator),Oe=null;if(He!=null&&He.renderLoadingIndicator&&(Oe=He.renderLoadingIndicator(H)),Oe===null&&((Ie=o.loadingIndicator)!=null&&Ie.render)&&(Oe=o.loadingIndicator.render(H)),Oe===null&&(Oe=Ma()),Oe){let ve=document.createElement("div"),Vt=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ve.className=Vt?["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(" "),ve.setAttribute("data-typing-indicator","true"),ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ve.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(ve),y.appendChild(Nt)}}if(!Po&&p.length>0){let H=p[p.length-1],He={config:o,lastMessage:H,messageCount:p.length},Oe=r.find(Vt=>Vt.renderIdleIndicator),ve=null;if(Oe!=null&&Oe.renderIdleIndicator&&(ve=Oe.renderIdleIndicator(He)),ve===null&&((Ye=o.loadingIndicator)!=null&&Ye.renderIdle)&&(ve=o.loadingIndicator.renderIdle(He)),ve){let Vt=document.createElement("div"),Nt=((Ct=o.loadingIndicator)==null?void 0:Ct.showBubble)!==!1;Vt.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(" "),Vt.setAttribute("data-idle-indicator","true"),Vt.appendChild(ve);let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id="wrapper-idle-indicator",Yt.setAttribute("data-wrapper-id","idle-indicator"),Yt.appendChild(Vt),y.appendChild(Yt)}}if(Di(c,y),ge.length>0)for(let{messageId:H,fingerprint:He,bubble:Oe}of ge){let ve=c.querySelector(`#wrapper-${H}`);ve&&Oe!==null&&(ve.replaceChildren(Oe),ve.setAttribute("data-bubble-fp",He),jo.set(H,He))}if(jo.size>0)for(let H of jo.keys())q.has(H)||jo.delete(H);if(ne.length>0)for(let{messageId:H,fingerprint:He,bubble:Oe}of ne){let ve=c.querySelector(`#wrapper-${H}`);ve&&Oe!==null&&(ve.replaceChildren(Oe),ve.setAttribute("data-bubble-fp",He),Wo.set(H,He))}if(Wo.size>0)for(let H of Wo.keys())q.has(H)||Wo.delete(H);if(Te.length>0)for(let{messageId:H,fingerprint:He,bubble:Oe}of Te){let ve=c.querySelector(`#wrapper-${H}`);ve&&Oe!==null&&(ve.replaceChildren(Oe),ve.setAttribute("data-bubble-fp",He),xo.set(H,He))}if(xo.size>0)for(let H of xo.keys())q.has(H)||xo.delete(H)},ar=null,Za=()=>{var h;if(ar)return;let c=y=>{let L=y.composedPath();L.includes(Le)||Je&&L.includes(Je)||Ot(!1,"user")};ar=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},_s=()=>{var p;if(!ar)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("pointerdown",ar,!0),ar=null};bt.push(()=>_s());let ir=null,ei=()=>{var h;if(ir)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ot(!1,"user"))};ir=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Vs=()=>{var p;if(!ir)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("keydown",ir,!0),ir=null};bt.push(()=>Vs());let lr=!1,$s=new Set,ti=()=>{var p,h,y,L;let c=(y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((L=o.features)==null?void 0:L.streamAnimation)},Yo=()=>{var dt,pt,We,Ie;if(!E())return;let c=Be.peekBanner,p=Be.peekTextNode;if(!c||!p)return;if(k){c.classList.remove("persona-pill-peek--visible");return}let h=(dt=$==null?void 0:$.getMessages())!=null?dt:[],y;for(let ze=h.length-1;ze>=0;ze--){let Ye=h[ze];if(Ye.role==="assistant"&&Ye.content){y=Ye;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let L=y.content,N=!!y.streaming,_=ti(),q=Vi(_),O=q.type!=="none"?wa(q.type,_==null?void 0:_.plugins):null,Ce=((pt=O==null?void 0:O.isAnimating)==null?void 0:pt.call(O,y))===!0,ge=O!==null&&(N||Ce);ge&&O&&!$s.has(O.name)&&(tc(O,e),$s.add(O.name));let ne=ge&&(O!=null&&O.containerClass)?O.containerClass:null,ke=(We=p.dataset.personaPeekStreamClass)!=null?We:null;ke&&ke!==ne&&(p.classList.remove(ke),delete p.dataset.personaPeekStreamClass),ne&&ke!==ne&&(p.classList.add(ne),p.dataset.personaPeekStreamClass=ne),ge?(p.style.setProperty("--persona-stream-step",`${q.speed}ms`),p.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ve=ge?$i(L,q.buffer,O,y,N):L;if(ge&&q.placeholder==="skeleton"&&N&&(!Ve||!Ve.trim())){let ze=document.createElement("div"),Ye=Sa();Ye.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ye),Di(p,ze)}else{let ze=Math.max(0,Ve.length-100),Ye=Ve.length>100?Ve.slice(-100):Ve,Ct=pa(Ye);if(!ge||!O){let H=Ve.length>100?`\u2026${Ye}`:Ye;p.textContent!==H&&(p.textContent=H)}else{let H=Ct;(O.wrap==="char"||O.wrap==="word")&&(H=Ca(Ct,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:ze}));let He=document.createElement("div");if(He.innerHTML=H,O.useCaret&&Ye.length>0){let Oe=Ui(),ve=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Vt=ve[ve.length-1];Vt!=null&&Vt.parentNode?Vt.parentNode.insertBefore(Oe,Vt.nextSibling):He.appendChild(Oe)}Di(p,He),(Ie=O.onAfterRender)==null||Ie.call(O,{container:p,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let je=Po||lr;c.classList.toggle("persona-pill-peek--visible",je)};if(E()){let c=Be.peekBanner;if(c){let y=L=>{L.preventDefault(),L.stopPropagation(),Ot(!0,"user")};c.addEventListener("pointerdown",y),bt.push(()=>{c.removeEventListener("pointerdown",y)})}let p=()=>{lr||(lr=!0,Yo())},h=()=>{lr&&(lr=!1,Yo())};pe.addEventListener("pointerenter",p),pe.addEventListener("pointerleave",h),bt.push(()=>{pe.removeEventListener("pointerenter",p),pe.removeEventListener("pointerleave",h)}),Je&&(Je.addEventListener("pointerenter",p),Je.addEventListener("pointerleave",h),bt.push(()=>{Je.removeEventListener("pointerenter",p),Je.removeEventListener("pointerleave",h)}))}let ni=c=>{var ke,Ve,Te,nt,je,dt,pt,We;let p=(Ve=(ke=o.launcher)==null?void 0:ke.composerBar)!=null?Ve:{},h=(Te=p.expandedSize)!=null?Te:"anchored",y=(nt=p.bottomOffset)!=null?nt:"16px",L=p.collapsedMaxWidth,N=(je=p.expandedMaxWidth)!=null?je:"880px",_=(dt=p.expandedTopOffset)!=null?dt:"5vh",q=(pt=p.modalMaxWidth)!=null?pt:"880px",O=(We=p.modalMaxHeight)!=null?We:"min(90vh, 800px)",Ce="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ne=Le.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Je){let Ie=Je.style;Ie.bottom=y,Ie.width=L!=null?L:""}if(c&&h!=="fullscreen"){if(h==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=q,ne.maxWidth=Ce,ne.maxHeight=O,ne.height=O;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${y} + ${ge})`,ne.top=_,ne.width=N,ne.maxWidth=Ce}},cr=()=>{var O,Ce,ge,ne,ke,Ve,Te,nt;if(!S())return;if(E()){let dt=(ge=((Ce=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ce:{}).expandedSize)!=null?ge:"anchored",pt=k?"expanded":"collapsed";Le.dataset.state=pt,Le.dataset.expandedSize=dt,Je&&(Je.dataset.state=pt,Je.dataset.expandedSize=dt),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ni(k),j.style.display=k?"flex":"none",vo(),k?(Za(),ei()):(_s(),Vs()),Yo();return}let c=wn(o),p=(ne=e.ownerDocument.defaultView)!=null?ne:window,h=(Ve=(ke=o.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Ve:640,y=(nt=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?nt:!0,L=p.innerWidth<=h,N=y&&L&&I,_=No(o).reveal;k?(Le.style.removeProperty("display"),Le.style.display=c?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),tn?tn.element.style.display="none":nn&&(nn.style.display="none")):(c?c&&(_==="overlay"||_==="push")&&!N?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),tn?tn.element.style.display=c?"none":"":nn&&(nn.style.display=c?"none":""))},Ot=(c,p="user")=>{var N,_;if(!S()||k===c)return;let h=k;k=c,cr();let y=(()=>{var Te,nt,je,dt,pt,We,Ie,ze,Ye,Ct;let q=(nt=(Te=o.launcher)==null?void 0:Te.sidebarMode)!=null?nt:!1,O=(je=e.ownerDocument.defaultView)!=null?je:window,Ce=(pt=(dt=o.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,ge=(Ie=(We=o.launcher)==null?void 0:We.mobileBreakpoint)!=null?Ie:640,ne=O.innerWidth<=ge,ke=wn(o)&&Ce&&ne,Ve=E()&&((Ct=(Ye=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Ye.expandedSize)!=null?Ct:"fullscreen")==="fullscreen";return q||Ce&&ne&&I||ke||Ve})();if(k&&y){if(!Zt){let q=e.getRootNode(),O=q instanceof ShadowRoot?q.host:e.closest(".persona-host");O&&(Zt=nc(O,(_=(N=o.launcher)==null?void 0:N.zIndex)!=null?_:Mn))}en||(en=oc(e.ownerDocument))}else k||(Zt==null||Zt(),Zt=null,en==null||en(),en=null);k&&(qs(),gt()==="follow"?Do(!0):Os());let L={open:k,source:p,timestamp:Date.now()};k&&!h?s.emit("widget:opened",L):!k&&h&&s.emit("widget:closed",L),s.emit("widget:state",{open:k,launcherEnabled:I,voiceActive:vt.active,streaming:$.isStreaming()})},os=c=>{Jt(c?"stop":"send"),G&&(G.disabled=c),io.buttons.forEach(p=>{p.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=c)})},rs=()=>{vt.active||te&&te.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>rs(),200)});let Us=()=>{var h,y,L,N,_,q,O,Ce,ge,ne,ke;oo.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Mo.textContent=(N=(L=o.copy)==null?void 0:L.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",te.placeholder=(q=(_=o.copy)==null?void 0:_.inputPlaceholder)!=null?q:"How can I help...";let c=fe.querySelector("[data-persona-intro-card]");if(c){let Ve=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ve?"":"none",Ve?(fe.classList.remove("persona-gap-3"),fe.classList.add("persona-gap-6")):(fe.classList.remove("persona-gap-6"),fe.classList.add("persona-gap-3"))}!((ge=(Ce=o.sendButton)==null?void 0:Ce.useIcon)!=null&&ge)&&!($!=null&&$.isStreaming())&&(qe.textContent=(ke=(ne=o.copy)==null?void 0:ne.sendButtonLabel)!=null?ke:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(p=>({...p,sessionId:c}))}});let po=null,Ge=()=>{po==null&&(po=setInterval(()=>{let c=tt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(po),po=null;return}let p=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ai(p-y))})},100))};if($=new Bi(o,{onMessagesChanged(c){var y;Er(tt,c,he),Ge(),$&&(c.some(N=>N.role==="user")?io.render([],$,te,c):io.render(o.suggestionChips,$,te,c,o.suggestionChipsConfig)),Do(!Po),Qa(c);let p=[...c].reverse().find(L=>L.role==="user");c.length===0&&kr(),!Jr||Tr?(Jr=!0,Qr=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Qr&&(Qr=p.id,Ja(p.id));let h=vt.lastUserMessageId;p&&p.id!==h&&(vt.lastUserMessageId=p.id,s.emit("user:message",p)),vt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),ts(c),Yo()},onStatusChanged(c){var y;let p=(y=o.statusIndicator)!=null?y:{};lt(an,(L=>{var N,_,q,O;return L==="idle"?(N=p.idleText)!=null?N:En.idle:L==="connecting"?(_=p.connectingText)!=null?_:En.connecting:L==="connected"?(q=p.connectedText)!=null?q:En.connected:L==="error"?(O=p.errorText)!=null?O:En.error:En[L]})(c),p,c)},onStreamingChanged(c){Po=c,os(c),$&&Er(tt,$.getMessages(),he),c||Do(!0),Yo()},onVoiceStatusChanged(c){var p,h;if(((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":dr(),Sg();break;case"speaking":dr(),Ag();break;default:c==="idle"&&$.isBargeInActive()?(dr(),zs(),G==null||G.setAttribute("aria-label","End voice session")):(vt.active=!1,dr(),co("system"),Nn());break}},onArtifactsState(c){jn=c,Yn(),ts()}}),Rt.current=$,Jr=!0,((qd=(zd=o.voiceRecognition)==null?void 0:zd.provider)==null?void 0:qd.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)}),(ye||o.onSSEEvent)&&$.setSSEEventCallback((c,p)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,p),be==null||be.processEvent(c,p),ye==null||ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(p)})}),l&&l.then(c=>{var p,h,y;if(c){if(c.metadata&&(d=Ec(c.metadata),M.syncFromMetadata()),(p=c.messages)!=null&&p.length){Tr=!0;try{$.hydrateMessages(c.messages)}finally{Tr=!1}}(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 T=()=>{var p,h,y;!E()||k||!((y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ot(!0,"auto")},U=c=>{var L;if(c.preventDefault(),$.isStreaming()){$.cancel(),be==null||be.reset(),K==null||K.update();return}let p=te.value.trim(),h=(L=At==null?void 0:At.hasAttachments())!=null?L:!1;if(!p&&!h)return;T();let y;h&&(y=[],y.push(...At.getContentParts()),p&&y.push(Jl(p))),te.value="",te.style.height="auto",X(),$.sendMessage(p,{contentParts:y}),h&&At.clearAttachments()},B=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Z={...Fi},ie=!1,X=()=>{Z={...Fi}},Pe=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var p;return(p=c.content)!=null?p:""}).filter(c=>c.length>0),Ne=c=>{if(!te)return;ie=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),ie=!1;let p=te.value.length;te.setSelectionRange(p,p)},at=()=>{ie||X()},Ze=c=>{if(te){if(B()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let p=te.selectionStart===0&&te.selectionEnd===0,h=jm({direction:c.key==="ArrowUp"?"up":"down",history:Pe(),currentValue:te.value,atStart:p,state:Z});if(Z=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Ne(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}X(),c.preventDefault(),qe.click()}}},Ht=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(j)&&($.cancel(),be==null||be.reset(),K==null||K.update(),X(),c.preventDefault(),c.stopImmediatePropagation())},$t=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!At)return;let p=ov(c.clipboardData);p.length!==0&&(c.preventDefault(),await At.handleFiles(p))},_t=null,ct=!1,kt=null,Ue=null,Tn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fn=(c="user")=>{var N,_,q,O,Ce,ge,ne;if(ct||$.isStreaming())return;let p=Tn();if(!p)return;_t=new p;let y=(_=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?_:2e3;_t.continuous=!0,_t.interimResults=!0,_t.lang="en-US";let L=te.value;_t.onresult=ke=>{let Ve="",Te="";for(let je=0;je<ke.results.length;je++){let dt=ke.results[je],pt=dt[0].transcript;dt.isFinal?Ve+=pt+" ":Te=pt}let nt=L+Ve+Te;te.value=nt,kt&&clearTimeout(kt),(Ve||Te)&&(kt=window.setTimeout(()=>{let je=te.value.trim();je&&_t&&ct&&(Ut(),te.value="",te.style.height="auto",$.sendMessage(je,{viaVoice:!0}))},y))},_t.onerror=ke=>{ke.error!=="no-speech"&&Ut()},_t.onend=()=>{if(ct){let ke=te.value.trim();ke&&ke!==L.trim()&&(te.value="",te.style.height="auto",$.sendMessage(ke,{viaVoice:!0})),Ut()}};try{if(_t.start(),ct=!0,vt.active=!0,c!=="system"&&(vt.manuallyDeactivated=!1),co(c),Nn(),G){let ke=(q=o.voiceRecognition)!=null?q:{};Ue={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(O=ke.iconName)!=null?O:"mic",iconSize:parseFloat((ne=(ge=ke.iconSize)!=null?ge:(Ce=o.sendButton)==null?void 0:Ce.size)!=null?ne:"40")||24};let Ve=ke.recordingBackgroundColor,Te=ke.recordingIconColor,nt=ke.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=Ve!=null?Ve:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let je=G.querySelector("svg");je&&je.setAttribute("stroke",Te)}nt&&(G.style.borderColor=nt),G.setAttribute("aria-label","Stop voice recognition")}}catch{Ut("system")}},Ut=(c="user")=>{if(ct){if(ct=!1,kt&&(clearTimeout(kt),kt=null),_t){try{_t.stop()}catch{}_t=null}if(vt.active=!1,co(c),Nn(),G){if(G.classList.remove("persona-voice-recording"),Ue){G.style.backgroundColor=Ue.backgroundColor,G.style.color=Ue.color,G.style.borderColor=Ue.borderColor;let p=G.querySelector("svg");p&&p.setAttribute("stroke",Ue.color||"currentColor"),Ue=null}G.setAttribute("aria-label","Start voice recognition")}}},So=(c,p)=>{var dt,pt,We,Ie,ze,Ye,Ct,H;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((dt=c==null?void 0:c.provider)==null?void 0:dt.type)==="runtype";if(!(h||y))return null;let N=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=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",O=(We=p==null?void 0:p.size)!=null?We:"40px",Ce=(Ie=c==null?void 0:c.iconSize)!=null?Ie:O,ge=parseFloat(Ce)||24,ne=(ze=c==null?void 0:c.backgroundColor)!=null?ze:p==null?void 0:p.backgroundColor,ke=(Ye=c==null?void 0:c.iconColor)!=null?Ye:p==null?void 0:p.textColor;_.style.width=Ce,_.style.height=Ce,_.style.minWidth=Ce,_.style.minHeight=Ce,_.style.fontSize="18px",_.style.lineHeight="1",ke?_.style.color=ke:_.style.color="var(--persona-text, #111827)";let Te=Me(q,ge,ke||"currentColor",1.5);Te?_.appendChild(Te):_.textContent="\u{1F3A4}",ne?_.style.backgroundColor=ne:_.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),N.appendChild(_);let nt=(Ct=c==null?void 0:c.tooltipText)!=null?Ct:"Start voice recognition";if(((H=c==null?void 0:c.showTooltip)!=null?H:!1)&&nt){let He=b("div","persona-send-button-tooltip");He.textContent=nt,N.appendChild(He)}return{micButton:_,micButtonWrapper:N}},Al=()=>{var p,h,y,L,N;if(!G||Ue)return;let c=(p=o.voiceRecognition)!=null?p:{};Ue={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(L=c.iconSize)!=null?L:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},Tl=(c,p)=>{var N,_,q,O,Ce;if(!G)return;let h=G.querySelector("svg");h&&h.remove();let y=(Ce=Ue==null?void 0:Ue.iconSize)!=null?Ce:parseFloat((O=(q=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?q:(_=o.sendButton)==null?void 0:_.size)!=null?O:"40")||24,L=Me(c,y,p,1.5);L&&G.appendChild(L)},oi=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},zs=()=>{var L;if(!G)return;Al();let c=(L=o.voiceRecognition)!=null?L:{},p=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(oi(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=G.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(G.style.borderColor=y),G.setAttribute("aria-label","Stop voice recognition")},Sg=()=>{var q,O,Ce,ge,ne,ke,Ve,Te;if(!G)return;Al();let c=(q=o.voiceRecognition)!=null?q:{},p=$.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ge=(Ce=c.processingIconColor)!=null?Ce:Ue==null?void 0:Ue.color)!=null?ge:"",L=(ke=(ne=c.processingBackgroundColor)!=null?ne:Ue==null?void 0:Ue.backgroundColor)!=null?ke:"",N=(Te=(Ve=c.processingBorderColor)!=null?Ve:Ue==null?void 0:Ue.borderColor)!=null?Te:"";oi(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=L,G.style.borderColor=N;let _=y||"currentColor";G.style.color=_,Tl(h,_),G.setAttribute("aria-label","Processing voice input"),p==="none"&&(G.style.cursor="default")},Ag=()=>{var Ce,ge,ne,ke,Ve,Te,nt,je,dt,pt,We,Ie;if(!G)return;Al();let c=(Ce=o.voiceRecognition)!=null?Ce:{},p=$.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:h,L=(Te=c.speakingIconColor)!=null?Te:p==="barge-in"?(ke=(ne=c.recordingIconColor)!=null?ne:Ue==null?void 0:Ue.color)!=null?ke:"":(Ve=Ue==null?void 0:Ue.color)!=null?Ve:"",N=(dt=c.speakingBackgroundColor)!=null?dt:p==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(je=Ue==null?void 0:Ue.backgroundColor)!=null?je:"",_=(Ie=c.speakingBorderColor)!=null?Ie:p==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(We=Ue==null?void 0:Ue.borderColor)!=null?We:"";oi(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=N,G.style.borderColor=_;let q=L||"currentColor";G.style.color=q,Tl(y,q);let O=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",O),p==="none"&&(G.style.cursor="default"),p==="barge-in"&&G.classList.add("persona-voice-recording")},dr=()=>{var c,p,h;G&&(oi(),Ue&&(G.style.backgroundColor=(c=Ue.backgroundColor)!=null?c:"",G.style.color=(p=Ue.color)!=null?p:"",G.style.borderColor=(h=Ue.borderColor)!=null?h:"",Tl(Ue.iconName,Ue.color||"currentColor"),Ue=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},ri=()=>{var c,p;if(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.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(()=>{vt.active=!1,vt.manuallyDeactivated=!0,Nn(),co("user"),dr()});return}$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),vt.manuallyDeactivated=!$.isVoiceActive(),Nn(),co("user"),$.isVoiceActive()?zs():dr()});return}if(ct){let h=te.value.trim();vt.manuallyDeactivated=!0,Nn(),Ut("user"),h&&(te.value="",te.style.height="auto",$.sendMessage(h))}else vt.manuallyDeactivated=!1,Nn(),fn("user")};Un=ri,G&&(G.addEventListener("click",ri),bt.push(()=>{var c,p;((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),dr()):Ut("system"),G&&G.removeEventListener("click",ri)}));let Tg=s.on("assistant:complete",()=>{Rs&&(vt.active||vt.manuallyDeactivated||Rs==="assistant"&&!vt.lastUserMessageWasVoice||setTimeout(()=>{var c,p;!vt.active&&!vt.manuallyDeactivated&&(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),co("auto"),$.isVoiceActive()&&zs()}):fn("auto"))},600))});bt.push(Tg);let kg=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});bt.push(kg);let ss=()=>{Ot(!k,"user")},tn=null,nn=null;if(I&&!E()){let c=r.find(p=>p.renderLauncher);if(c!=null&&c.renderLauncher){let p=c.renderLauncher({config:o,defaultRenderer:()=>ka(o,ss).element,onToggle:ss});p&&(nn=p)}nn||(tn=ka(o,ss))}tn?e.appendChild(tn.element):nn&&e.appendChild(nn),cr(),io.render(o.suggestionChips,$,te,void 0,o.suggestionChipsConfig),Us(),os($.isStreaming()),gt()==="follow"?Do(!0):Os(),ja(),P&&(!I||E()?setTimeout(()=>rs(),0):k&&setTimeout(()=>rs(),200));let qs=()=>{var O,Ce,ge,ne,ke,Ve,Te,nt,je,dt,pt,We,Ie,ze,Ye,Ct,H,He,Oe,ve,Vt,Nt;if(E()){yn(),cr();return}let c=wn(o),p=(Ce=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ce:!1,h=c||p||((ne=(ge=o.launcher)==null?void 0:ge.fullHeight)!=null?ne:!1),y=(ke=e.ownerDocument.defaultView)!=null?ke:window,L=(Te=(Ve=o.launcher)==null?void 0:Ve.mobileFullscreen)!=null?Te:!0,N=(je=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?je:640,_=y.innerWidth<=N,q=L&&_&&I;try{if(q){vo(),ds(e,o);return}if(x&&(x=!1,vo(),ds(e,o)),!I&&!c){pe.style.height="",pe.style.width="";return}if(!p&&!c){let Yt=(pt=(dt=o==null?void 0:o.launcher)==null?void 0:dt.width)!=null?pt:o==null?void 0:o.launcherWidth,St=Yt!=null?Yt:go;pe.style.width=St,pe.style.maxWidth=St}if(Ro(),!h){let Yt=y.innerHeight,St=64,jt=(Ie=(We=o.launcher)==null?void 0:We.heightOffset)!=null?Ie:0,Zn=Math.max(200,Yt-St),rn=Math.min(640,Zn),Xe=Math.max(200,rn-jt);pe.style.height=`${Xe}px`}}finally{if(yn(),cr(),k&&I){let St=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((Ct=(Ye=o.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?Ct:640),jt=(He=(H=o.launcher)==null?void 0:H.sidebarMode)!=null?He:!1,Zn=(ve=(Oe=o.launcher)==null?void 0:Oe.mobileFullscreen)!=null?ve:!0,rn=wn(o)&&Zn&&St,Xe=jt||Zn&&St&&I||rn;if(Xe&&!en){let Wt=e.getRootNode(),dn=Wt instanceof ShadowRoot?Wt.host:e.closest(".persona-host");dn&&!Zt&&(Zt=nc(dn,(Nt=(Vt=o.launcher)==null?void 0:Vt.zIndex)!=null?Nt:Mn)),en=oc(e.ownerDocument)}else Xe||(Zt==null||Zt(),Zt=null,en==null||en(),en=null)}}};qs();let Uc=(jd=e.ownerDocument.defaultView)!=null?jd:window;if(Uc.addEventListener("resize",qs),bt.push(()=>Uc.removeEventListener("resize",qs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe($e),bt.push(()=>c.disconnect())}Qn=fe.scrollTop;let zc=Qo(fe),Eg=()=>{let c=fe.getRootNode(),p=typeof c.getSelection=="function"?c.getSelection():null;return p!=null?p:fe.ownerDocument.getSelection()},kl=()=>Qm(Eg(),fe),qc=()=>{let c=fe.scrollTop,p=Qo(fe),h=p<zc;if(zc=p,gt()!=="follow"){Qn=c,_n();return}let{action:y,nextLastScrollTop:L}=Ni({following:Jn.isFollowing(),currentScrollTop:c,lastScrollTop:Qn,nearBottom:Vr(fe,Zr),userScrollThreshold:za,isAutoScrolling:Co||Ar||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Qn=L,y==="resume"){kl()||Ho();return}y==="pause"&&ns()};if(fe.addEventListener("scroll",qc,{passive:!0}),bt.push(()=>fe.removeEventListener("scroll",qc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Xa()});c.observe(tt),c.observe(fe),bt.push(()=>c.disconnect())}let jc=()=>{gt()==="follow"&&Jn.isFollowing()&&kl()&&ns()},Kc=fe.ownerDocument;Kc.addEventListener("selectionchange",jc),bt.push(()=>{Kc.removeEventListener("selectionchange",jc)});let Gc=c=>{if(gt()!=="follow")return;let p=_i({following:Jn.isFollowing(),deltaY:c.deltaY,nearBottom:Vr(fe,Zr),resumeWhenNearBottom:!0});p==="pause"?ns():p==="resume"&&!kl()&&Ho()};fe.addEventListener("wheel",Gc,{passive:!0}),bt.push(()=>fe.removeEventListener("wheel",Gc)),Qe.addEventListener("click",()=>{kr(),fe.scrollTop=fe.scrollHeight,Qn=fe.scrollTop,Ho(),Do(!0),_n()}),bt.push(()=>Qe.remove()),bt.push(()=>{Ws(),kr()});let Yc=()=>{F&&(lo&&(F.removeEventListener("click",lo),lo=null),S()?(F.style.display="",lo=()=>{Ot(!1,"user")},F.addEventListener("click",lo)):F.style.display="none")};Yc(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{$.clearMessages(),qo.clear(),Ho(),Ss(Be.composerOverlay);try{localStorage.removeItem(Ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),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(),ye==null||ye.clear(),be==null||be.reset(),K==null||K.update()})})(),Dt&&Dt.addEventListener("submit",U),te==null||te.addEventListener("keydown",Ze),te==null||te.addEventListener("input",at),te==null||te.addEventListener("paste",$t);let Xc=(Kd=e.ownerDocument)!=null?Kd:document;Xc.addEventListener("keydown",Ht,!0);let Jc="persona-attachment-drop-active",js=0,El=()=>{js=0,j.classList.remove(Jc)},as=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&At!==null},Qc=c=>{!cl(c.dataTransfer)||!as()||(js++,js===1&&j.classList.add(Jc))},Zc=c=>{!cl(c.dataTransfer)||!as()||(js--,js<=0&&El())},ed=c=>{!cl(c.dataTransfer)||!as()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},td=c=>{var h;if(!cl(c.dataTransfer)||!as())return;c.preventDefault(),c.stopPropagation(),El();let p=Array.from((h=c.dataTransfer.files)!=null?h:[]);p.length!==0&&At.handleFiles(p)},pr=!0;j.addEventListener("dragenter",Qc,pr),j.addEventListener("dragleave",Zc,pr),e.addEventListener("dragover",ed,pr),e.addEventListener("drop",td,pr);let si=e.ownerDocument,nd=c=>{as()&&c.preventDefault()},od=c=>{as()&&c.preventDefault()};si.addEventListener("dragover",nd),si.addEventListener("drop",od),bt.push(()=>{Dt&&Dt.removeEventListener("submit",U),te==null||te.removeEventListener("keydown",Ze),te==null||te.removeEventListener("input",at),te==null||te.removeEventListener("paste",$t),Xc.removeEventListener("keydown",Ht,!0)}),bt.push(()=>{j.removeEventListener("dragenter",Qc,pr),j.removeEventListener("dragleave",Zc,pr),e.removeEventListener("dragover",ed,pr),e.removeEventListener("drop",td,pr),si.removeEventListener("dragover",nd),si.removeEventListener("drop",od),El()}),bt.push(()=>{$.cancel()}),tn?bt.push(()=>{tn==null||tn.destroy()}):nn&&bt.push(()=>{nn==null||nn.remove()});let cn={update(c){var Fo,un,Bn,fo,Rr,Pr,ai,Ks,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,Jp,Qp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,fu,gu,hu,bu,yu,vu,xu,wu,Cu,Su,Au,Tu,ku,Eu,Mu,Lu,Iu,Ru,Pu,Wu,Bu,Hu,Du,Fu,Ou,Nu,_u,Vu,$u,Uu,zu,qu,ju,Ku,Gu,Yu,Xu,Ju,Qu;let p=o.toolCall,h=o.messageActions,y=(Fo=o.layout)==null?void 0:Fo.messages,L=o.colorScheme,N=o.loadingIndicator,_=o.iterationDisplay,q=(un=o.features)==null?void 0:un.showReasoning,O=(Bn=o.features)==null?void 0:Bn.showToolCalls,Ce=(fo=o.features)==null?void 0:fo.toolCallDisplay,ge=(Rr=o.features)==null?void 0:Rr.reasoningDisplay;o={...o,...c},vo(),ds(e,o),il(e,o),ll(e,o),Yn(),o.colorScheme!==L&&rr();let ne=Cc.getForInstance(o.plugins);r.length=0,r.push(...ne),I=(ai=(Pr=o.launcher)==null?void 0:Pr.enabled)!=null?ai:!0,R=(ep=(Ks=o.launcher)==null?void 0:Ks.autoExpand)!=null?ep:!1,me=(np=(tp=o.features)==null?void 0:tp.showReasoning)!=null?np:!0,de=(rp=(op=o.features)==null?void 0:op.showToolCalls)!=null?rp:!0,xe=(ap=(sp=o.features)==null?void 0:sp.scrollToBottom)!=null?ap:{};let ke=gt();De=(lp=(ip=o.features)==null?void 0:ip.scrollBehavior)!=null?lp:{},ke!==gt()&&(kr(),Ho()),Lo(),_n();let Ve=Ee;if(Ee=(dp=(cp=o.features)==null?void 0:cp.showEventStreamToggle)!=null?dp:!1,Ee&&!Ve){if(ye||(J=new Ra(le),ye=new Ia(se,J),be=be!=null?be:new Pa,J.open().then(()=>ye==null?void 0:ye.restore()).catch(()=>{}),$.setSSEEventCallback((Q,Et)=>{var zt;(zt=o.onSSEEvent)==null||zt.call(o,Q,Et),be==null||be.processEvent(Q,Et),ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!wt&&_e){let Q=(up=(pp=o.features)==null?void 0:pp.eventStream)==null?void 0:up.classNames,Et="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");wt=b("button",Et),wt.style.width="28px",wt.style.height="28px",wt.style.color=Dn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let zt=Me("activity","18px","currentColor",1.5);zt&&wt.appendChild(zt);let ft=Be.clearChatButtonWrapper,Bt=Be.closeButtonWrapper,gn=ft||Bt;gn&&gn.parentNode===_e?_e.insertBefore(wt,gn):_e.appendChild(wt),wt.addEventListener("click",()=>{ae?yo():Vo()})}}else!Ee&&Ve&&(yo(),wt&&(wt.remove(),wt=null),ye==null||ye.clear(),J==null||J.destroy(),ye=null,J=null,be==null||be.reset(),be=null);if(((mp=o.launcher)==null?void 0:mp.enabled)===!1&&tn&&(tn.destroy(),tn=null),((fp=o.launcher)==null?void 0:fp.enabled)===!1&&nn&&(nn.remove(),nn=null),((gp=o.launcher)==null?void 0:gp.enabled)!==!1&&!tn&&!nn){let Q=r.find(Et=>Et.renderLauncher);if(Q!=null&&Q.renderLauncher){let Et=Q.renderLauncher({config:o,defaultRenderer:()=>ka(o,ss).element,onToggle:ss});Et&&(nn=Et,e.appendChild(nn))}nn||(tn=ka(o,ss),e.appendChild(tn.element))}tn&&tn.update(o),Fe&&((hp=o.launcher)==null?void 0:hp.title)!==void 0&&(Fe.textContent=o.launcher.title),Ke&&((bp=o.launcher)==null?void 0:bp.subtitle)!==void 0&&(Ke.textContent=o.launcher.subtitle);let Te=(yp=o.layout)==null?void 0:yp.header;if((Te==null?void 0:Te.layout)!==w&&_e){let Q=Te?Ki(o,Te,{showClose:S(),onClose:()=>Ot(!1,"user")}):$r({config:o,showClose:S(),onClose:()=>Ot(!1,"user")});_e.replaceWith(Q.header),_e=Q.header,ue=Q.iconHolder,Fe=Q.headerTitle,Ke=Q.headerSubtitle,F=Q.closeButton,w=Te==null?void 0:Te.layout}else if(Te&&(ue&&(ue.style.display=Te.showIcon===!1?"none":""),Fe&&(Fe.style.display=Te.showTitle===!1?"none":""),Ke&&(Ke.style.display=Te.showSubtitle===!1?"none":""),F&&(F.style.display=Te.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let Q=Te.showClearChat;if(Q!==void 0){Be.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:Et}=Be;Et&&!Et.classList.contains("persona-absolute")&&(Q?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let je=((vp=o.layout)==null?void 0:vp.showHeader)!==!1;_e&&(_e.style.display=je?"":"none");let dt=((xp=o.layout)==null?void 0:xp.showFooter)!==!1;$e&&($e.style.display=dt?"":"none"),yn(),_n(),I!==W?I?Ot(R,"auto"):(k=!0,cr()):R!==D&&Ot(R,"auto"),D=R,W=I,qs(),Yc();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(p),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ye=JSON.stringify((wp=o.layout)==null?void 0:wp.messages)!==JSON.stringify(y),Ct=((Cp=o.loadingIndicator)==null?void 0:Cp.render)!==(N==null?void 0:N.render)||((Sp=o.loadingIndicator)==null?void 0:Sp.renderIdle)!==(N==null?void 0:N.renderIdle)||((Ap=o.loadingIndicator)==null?void 0:Ap.showBubble)!==(N==null?void 0:N.showBubble),H=o.iterationDisplay!==_,He=((kp=(Tp=o.features)==null?void 0:Tp.showReasoning)!=null?kp:!0)!==(q!=null?q:!0)||((Mp=(Ep=o.features)==null?void 0:Ep.showToolCalls)!=null?Mp:!0)!==(O!=null?O:!0)||JSON.stringify((Lp=o.features)==null?void 0:Lp.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Ip=o.features)==null?void 0:Ip.reasoningDisplay)!==JSON.stringify(ge);(Ie||ze||Ye||Ct||H||He)&&$&&(Is++,Er(tt,$.getMessages(),he));let ve=(Rp=o.launcher)!=null?Rp:{},Vt=(Pp=ve.headerIconHidden)!=null?Pp:!1,Nt=(Bp=(Wp=o.layout)==null?void 0:Wp.header)==null?void 0:Bp.showIcon,Yt=Vt||Nt===!1,St=ve.headerIconName,jt=(Hp=ve.headerIconSize)!=null?Hp:"48px";if(ue){let Q=j.querySelector(".persona-border-b-persona-divider"),Et=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Yt)ue.style.display="none",Q&&Et&&!Q.contains(Et)&&Q.insertBefore(Et,Q.firstChild);else{if(ue.style.display="",ue.style.height=jt,ue.style.width=jt,Q&&Et&&(Q.contains(ue)?ue.nextSibling!==Et&&(ue.remove(),Q.insertBefore(ue,Et)):Q.insertBefore(ue,Et)),St){let ft=parseFloat(jt)||24,Bt=Me(St,ft*.6,"#ffffff",2);Bt?ue.replaceChildren(Bt):ue.textContent=(Dp=ve.agentIconText)!=null?Dp:"\u{1F4AC}"}else if(ve.iconUrl){let ft=ue.querySelector("img");if(ft)ft.src=ve.iconUrl,ft.style.height=jt,ft.style.width=jt;else{let Bt=document.createElement("img");Bt.src=ve.iconUrl,Bt.alt="",Bt.className="persona-rounded-xl persona-object-cover",Bt.style.height=jt,Bt.style.width=jt,ue.replaceChildren(Bt)}}else{let ft=ue.querySelector("svg"),Bt=ue.querySelector("img");(ft||Bt)&&ue.replaceChildren(),ue.textContent=(Fp=ve.agentIconText)!=null?Fp:"\u{1F4AC}"}let zt=ue.querySelector("img");zt&&(zt.style.height=jt,zt.style.width=jt)}}let Zn=(Np=(Op=o.layout)==null?void 0:Op.header)==null?void 0:Np.showTitle,rn=(Vp=(_p=o.layout)==null?void 0:_p.header)==null?void 0:Vp.showSubtitle;if(Fe&&(Fe.style.display=Zn===!1?"none":""),Ke&&(Ke.style.display=rn===!1?"none":""),F){((Up=($p=o.layout)==null?void 0:$p.header)==null?void 0:Up.showCloseButton)===!1?F.style.display="none":F.style.display="";let Et=(zp=ve.closeButtonSize)!=null?zp:"32px",zt=(qp=ve.closeButtonPlacement)!=null?qp:"inline";F.style.height=Et,F.style.width=Et;let{closeButtonWrapper:ft}=Be,Bt=zt==="top-right",gn=ft==null?void 0:ft.classList.contains("persona-absolute");if(ft&&Bt!==gn)if(ft.remove(),Bt)ft.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(ft);else{let ht=(Kp=(jp=ve.clearChat)==null?void 0:jp.placement)!=null?Kp:"inline",hn=(Yp=(Gp=ve.clearChat)==null?void 0:Gp.enabled)!=null?Yp:!0;ft.className=hn&&ht==="inline"?"":"persona-ml-auto";let $n=j.querySelector(".persona-border-b-persona-divider");$n&&$n.appendChild(ft)}if(F.style.color=ve.closeButtonColor||Dn.actionIconColor,ve.closeButtonBackgroundColor?(F.style.backgroundColor=ve.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ht=ve.closeButtonBorderWidth||"0px",hn=ve.closeButtonBorderColor||"transparent";F.style.border=`${ht} solid ${hn}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");ve.closeButtonBorderRadius?(F.style.borderRadius=ve.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(F.style.paddingLeft=ve.closeButtonPaddingX,F.style.paddingRight=ve.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),ve.closeButtonPaddingY?(F.style.paddingTop=ve.closeButtonPaddingY,F.style.paddingBottom=ve.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let kn=(Xp=ve.closeButtonIconName)!=null?Xp:"x",Ao=(Jp=ve.closeButtonIconText)!=null?Jp:"\xD7";F.innerHTML="";let Hn=Me(kn,"28px","currentColor",1);Hn?F.appendChild(Hn):F.textContent=Ao;let on=(Qp=ve.closeButtonTooltipText)!=null?Qp:"Close chat",to=(Zp=ve.closeButtonShowTooltip)!=null?Zp:!0;if(F.setAttribute("aria-label",on),ft&&(ft._cleanupTooltip&&(ft._cleanupTooltip(),delete ft._cleanupTooltip),to&&on)){let ht=null,hn=()=>{if(ht||!F)return;let Wr=F.ownerDocument,Gs=Wr.body;if(!Gs)return;ht=Oo(Wr,"div","persona-clear-chat-tooltip"),ht.textContent=on;let Ys=Oo(Wr,"div");Ys.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ys);let Br=F.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(gr),ht.style.left=`${Br.left+Br.width/2}px`,ht.style.top=`${Br.top-8}px`,ht.style.transform="translate(-50%, -100%)",Gs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ft.addEventListener("mouseenter",hn),ft.addEventListener("mouseleave",$n),F.addEventListener("focus",hn),F.addEventListener("blur",$n),ft._cleanupTooltip=()=>{$n(),ft&&(ft.removeEventListener("mouseenter",hn),ft.removeEventListener("mouseleave",$n)),F&&(F.removeEventListener("focus",hn),F.removeEventListener("blur",$n))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Wt}=Be;if(Xe){let Q=(eu=ve.clearChat)!=null?eu:{},Et=(tu=Q.enabled)!=null?tu:!0,zt=(ou=(nu=o.layout)==null?void 0:nu.header)==null?void 0:ou.showClearChat,ft=zt!==void 0?zt:Et,Bt=(ru=Q.placement)!=null?ru:"inline";if(Wt){Wt.style.display=ft?"":"none";let{closeButtonWrapper:gn}=Be;!E()&&gn&&!gn.classList.contains("persona-absolute")&&(ft?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let kn=Bt==="top-right",Ao=Wt.classList.contains("persona-absolute");if(!E()&&kn!==Ao&&ft){if(Wt.remove(),kn)Wt.className="persona-absolute persona-top-4 persona-z-50",Wt.style.right="48px",j.style.position="relative",j.appendChild(Wt);else{Wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wt.style.right="";let on=j.querySelector(".persona-border-b-persona-divider"),to=Be.closeButtonWrapper;on&&to&&to.parentElement===on?on.insertBefore(Wt,to):on&&on.appendChild(Wt)}let Hn=Be.closeButtonWrapper;Hn&&!Hn.classList.contains("persona-absolute")&&(kn?Hn.classList.add("persona-ml-auto"):Hn.classList.remove("persona-ml-auto"))}}if(ft){if(!E()){let ht=(su=Q.size)!=null?su:"32px";Xe.style.height=ht,Xe.style.width=ht}let gn=(au=Q.iconName)!=null?au:"refresh-cw",kn=(iu=Q.iconColor)!=null?iu:"";Xe.style.color=kn||Dn.actionIconColor,Xe.innerHTML="";let Ao=E()?"14px":"20px",Hn=Me(gn,Ao,"currentColor",2);if(Hn&&Xe.appendChild(Hn),Q.backgroundColor?(Xe.style.backgroundColor=Q.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ht=Q.borderWidth||"0px",hn=Q.borderColor||"transparent";Xe.style.border=`${ht} solid ${hn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");Q.borderRadius?(Xe.style.borderRadius=Q.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),Q.paddingX?(Xe.style.paddingLeft=Q.paddingX,Xe.style.paddingRight=Q.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),Q.paddingY?(Xe.style.paddingTop=Q.paddingY,Xe.style.paddingBottom=Q.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let on=(lu=Q.tooltipText)!=null?lu:"Clear chat",to=(cu=Q.showTooltip)!=null?cu:!0;if(Xe.setAttribute("aria-label",on),Wt&&(Wt._cleanupTooltip&&(Wt._cleanupTooltip(),delete Wt._cleanupTooltip),to&&on)){let ht=null,hn=()=>{if(ht||!Xe)return;let Wr=Xe.ownerDocument,Gs=Wr.body;if(!Gs)return;ht=Oo(Wr,"div","persona-clear-chat-tooltip"),ht.textContent=on;let Ys=Oo(Wr,"div");Ys.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ys);let Br=Xe.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(gr),ht.style.left=`${Br.left+Br.width/2}px`,ht.style.top=`${Br.top-8}px`,ht.style.transform="translate(-50%, -100%)",Gs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Wt.addEventListener("mouseenter",hn),Wt.addEventListener("mouseleave",$n),Xe.addEventListener("focus",hn),Xe.addEventListener("blur",$n),Wt._cleanupTooltip=()=>{$n(),Wt&&(Wt.removeEventListener("mouseenter",hn),Wt.removeEventListener("mouseleave",$n)),Xe&&(Xe.removeEventListener("focus",hn),Xe.removeEventListener("blur",$n))}}}}let dn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ac],mo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wa.message,Wa.messageAndClick];M=Tc({parsers:dn,handlers:mo,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),he=eg(o,M,Y),$.updateConfig(o),Er(tt,$.getMessages(),he),io.render(o.suggestionChips,$,te,void 0,o.suggestionChipsConfig),Us(),os($.isStreaming());let eo=((du=o.voiceRecognition)==null?void 0:du.enabled)===!0,Mr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Lr=((uu=(pu=o.voiceRecognition)==null?void 0:pu.provider)==null?void 0:uu.type)==="runtype";if(eo&&(Mr||Lr))if(!G||!xt){let Q=So(o.voiceRecognition,o.sendButton);Q&&(G=Q.micButton,xt=Q.micButtonWrapper,Kt.insertBefore(xt,Fn),G.addEventListener("click",ri),G.disabled=$.isStreaming())}else{let Q=(mu=o.voiceRecognition)!=null?mu:{},Et=(fu=o.sendButton)!=null?fu:{},zt=(gu=Q.iconName)!=null?gu:"mic",ft=(hu=Et.size)!=null?hu:"40px",Bt=(bu=Q.iconSize)!=null?bu:ft,gn=parseFloat(Bt)||24;G.style.width=Bt,G.style.height=Bt,G.style.minWidth=Bt,G.style.minHeight=Bt;let kn=(vu=(yu=Q.iconColor)!=null?yu:Et.textColor)!=null?vu:"currentColor";G.innerHTML="";let Ao=Me(zt,gn,kn,2);Ao?G.appendChild(Ao):G.textContent="\u{1F3A4}";let Hn=(xu=Q.backgroundColor)!=null?xu:Et.backgroundColor;Hn?G.style.backgroundColor=Hn:G.style.backgroundColor="",kn?G.style.color=kn:G.style.color="var(--persona-text, #111827)",Q.borderWidth?(G.style.borderWidth=Q.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Q.borderColor?G.style.borderColor=Q.borderColor:G.style.borderColor="",Q.paddingX?(G.style.paddingLeft=Q.paddingX,G.style.paddingRight=Q.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Q.paddingY?(G.style.paddingTop=Q.paddingY,G.style.paddingBottom=Q.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let on=xt==null?void 0:xt.querySelector(".persona-send-button-tooltip"),to=(wu=Q.tooltipText)!=null?wu:"Start voice recognition";if(((Cu=Q.showTooltip)!=null?Cu:!1)&&to)if(on)on.textContent=to,on.style.display="";else{let hn=document.createElement("div");hn.className="persona-send-button-tooltip",hn.textContent=to,xt==null||xt.insertBefore(hn,G)}else on&&(on.style.display="none");xt.style.display="",G.disabled=$.isStreaming()}else G&&xt&&(xt.style.display="none",((Au=(Su=o.voiceRecognition)==null?void 0:Su.provider)==null?void 0:Au.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():ct&&Ut());if(((Tu=o.attachments)==null?void 0:Tu.enabled)===!0)if(!Se||!st){let Q=(ku=o.attachments)!=null?ku:{},zt=(Mu=((Eu=o.sendButton)!=null?Eu:{}).size)!=null?Mu:"40px";et||(et=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),et.style.display="none",Dt.insertBefore(et,te)),ce||(ce=document.createElement("input"),ce.type="file",ce.accept=((Lu=Q.allowedTypes)!=null?Lu:Jo).join(","),ce.multiple=((Iu=Q.maxFiles)!=null?Iu:4)>1,ce.style.display="none",ce.setAttribute("aria-label","Attach files"),Dt.insertBefore(ce,te)),Se=b("div","persona-send-button-wrapper"),st=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),st.type="button",st.setAttribute("aria-label",(Ru=Q.buttonTooltipText)!=null?Ru:"Attach file");let ft=(Pu=Q.buttonIconName)!=null?Pu:"paperclip",Bt=zt,gn=parseFloat(Bt)||40,kn=Math.round(gn*.6);st.style.width=Bt,st.style.height=Bt,st.style.minWidth=Bt,st.style.minHeight=Bt,st.style.fontSize="18px",st.style.lineHeight="1",st.style.backgroundColor="transparent",st.style.color="var(--persona-primary, #111827)",st.style.border="none",st.style.borderRadius="6px",st.style.transition="background-color 0.15s ease",st.addEventListener("mouseenter",()=>{st.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),st.addEventListener("mouseleave",()=>{st.style.backgroundColor="transparent"});let Ao=Me(ft,kn,"currentColor",1.5);Ao?st.appendChild(Ao):st.textContent="\u{1F4CE}",st.addEventListener("click",to=>{to.preventDefault(),ce==null||ce.click()}),Se.appendChild(st);let Hn=(Wu=Q.buttonTooltipText)!=null?Wu:"Attach file",on=b("div","persona-send-button-tooltip");on.textContent=Hn,Se.appendChild(on),Pt.append(Se),!At&&ce&&et&&(At=va.fromConfig(Q),At.setPreviewsContainer(et),ce.addEventListener("change",async()=>{At&&(ce!=null&&ce.files)&&(await At.handleFileSelect(ce.files),ce.value="")})),j.querySelector(".persona-attachment-drop-overlay")||j.appendChild(tg(Q.dropOverlay))}else{Se.style.display="";let Q=(Bu=o.attachments)!=null?Bu:{};ce&&(ce.accept=((Hu=Q.allowedTypes)!=null?Hu:Jo).join(","),ce.multiple=((Du=Q.maxFiles)!=null?Du:4)>1),At&&At.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Se&&(Se.style.display="none"),At&&At.clearAttachments(),(Fu=j.querySelector(".persona-attachment-drop-overlay"))==null||Fu.remove();let Xt=(Ou=o.sendButton)!=null?Ou:{},Ir=(Nu=Xt.useIcon)!=null?Nu:!1,ur=(_u=Xt.iconText)!=null?_u:"\u2191",mr=Xt.iconName,Xo=(Vu=Xt.tooltipText)!=null?Vu:"Send message",rt=($u=Xt.showTooltip)!=null?$u:!1,xn=(Uu=Xt.size)!=null?Uu:"40px",Wn=Xt.backgroundColor,sn=Xt.textColor;if(Ir){if(qe.style.width=xn,qe.style.height=xn,qe.style.minWidth=xn,qe.style.minHeight=xn,qe.style.fontSize="18px",qe.style.lineHeight="1",qe.innerHTML="",sn?qe.style.color=sn:qe.style.color="var(--persona-button-primary-fg, #ffffff)",mr){let Q=parseFloat(xn)||24,Et=(sn==null?void 0:sn.trim())||"currentColor",zt=Me(mr,Q,Et,2);zt?qe.appendChild(zt):qe.textContent=ur}else qe.textContent=ur;qe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(qe.style.backgroundColor=Wn,qe.classList.remove("persona-bg-persona-primary")):(qe.style.backgroundColor="",qe.classList.add("persona-bg-persona-primary"))}else qe.textContent=(qu=(zu=o.copy)==null?void 0:zu.sendButtonLabel)!=null?qu:"Send",qe.style.width="",qe.style.height="",qe.style.minWidth="",qe.style.minHeight="",qe.style.fontSize="",qe.style.lineHeight="",qe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(qe.style.backgroundColor=Wn,qe.classList.remove("persona-bg-persona-accent")):qe.classList.add("persona-bg-persona-accent"),sn?qe.style.color=sn:qe.classList.add("persona-text-white");Xt.borderWidth?(qe.style.borderWidth=Xt.borderWidth,qe.style.borderStyle="solid"):(qe.style.borderWidth="",qe.style.borderStyle=""),Xt.borderColor?qe.style.borderColor=Xt.borderColor:qe.style.borderColor="",Xt.paddingX?(qe.style.paddingLeft=Xt.paddingX,qe.style.paddingRight=Xt.paddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Xt.paddingY?(qe.style.paddingTop=Xt.paddingY,qe.style.paddingBottom=Xt.paddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let ut=Fn==null?void 0:Fn.querySelector(".persona-send-button-tooltip");if(rt&&Xo)if(ut)ut.textContent=Xo,ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Xo,Fn==null||Fn.insertBefore(Q,qe)}else ut&&(ut.style.display="none");let yt=(Xu=(ju=o.layout)==null?void 0:ju.contentMaxWidth)!=null?Xu:E()?(Yu=(Gu=(Ku=o.launcher)==null?void 0:Ku.composerBar)==null?void 0:Gu.contentMaxWidth)!=null?Yu:"720px":void 0;yt?(tt.style.maxWidth=yt,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%",Dt&&(Dt.style.maxWidth=yt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=yt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(tt.style.maxWidth="",tt.style.marginLeft="",tt.style.marginRight="",tt.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let mt=(Ju=o.statusIndicator)!=null?Ju:{},Vn=(Qu=mt.visible)!=null?Qu:!0;if(an.style.display=Vn?"":"none",$){let Q=$.getStatus();lt(an,(zt=>{var ft,Bt,gn,kn;return zt==="idle"?(ft=mt.idleText)!=null?ft:En.idle:zt==="connecting"?(Bt=mt.connectingText)!=null?Bt:En.connecting:zt==="connected"?(gn=mt.connectedText)!=null?gn:En.connected:zt==="error"?(kn=mt.errorText)!=null?kn:En.error:En[zt]})(Q),mt,Q)}an.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pn=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";an.classList.add(pn)},open(){S()&&Ot(!0,"api")},close(){S()&&Ot(!1,"api")},toggle(){S()&&Ot(!k,"api")},clearChat(){Rn=!1,$.clearMessages(),qo.clear(),Ho();try{localStorage.removeItem(Ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},M.syncFromMetadata(),ye==null||ye.clear(),be==null||be.reset(),K==null||K.update()},setMessage(c){return!te||$.isStreaming()?!1:(!k&&S()&&Ot(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let p=(c==null?void 0:c.trim())||te.value.trim();return p?(!k&&S()&&Ot(!0,"system"),te.value="",te.style.height="auto",$.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return $.isStreaming()?!1:((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!k&&S()&&Ot(!0,"system"),vt.manuallyDeactivated=!1,Nn(),$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),co("user"),$.isVoiceActive()&&zs()})),!0):ct?!0:Tn()?(!k&&S()&&Ot(!0,"system"),vt.manuallyDeactivated=!1,Nn(),fn("user"),!0):!1},stopVoiceRecognition(){var c,p;return((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,Nn(),co("user"),dr()}),!0):!1:ct?(vt.manuallyDeactivated=!0,Nn(),Ut("user"),!0):!1},injectMessage(c){return!k&&S()&&Ot(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!k&&S()&&Ot(!0,"system");let p=$.injectAssistantMessage(c);return V&&(V=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),p},injectUserMessage(c){return!k&&S()&&Ot(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!k&&S()&&Ot(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!k&&S()&&Ot(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!k&&S()&&Ot(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!k&&S()&&Ot(!0,"system"),$.injectTestEvent(c)},async connectStream(c,p){return $.connectStream(c,p)},__pushEventStreamEvent(c){ye&&(be==null||be.processEvent(c.type,c.payload),ye.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||!ye||Vo()},hideEventStream(){ae&&yo()},isEventStreamVisible(){return ae},showArtifacts(){bo(o)&&(Rn=!1,Yn(),Tt==null||Tt.setMobileOpen(!0))},hideArtifacts(){bo(o)&&(Rn=!0,Yn())},upsertArtifact(c){return bo(o)?(Rn=!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&&!k&&!E()||!te?!1:(te.focus(),!0)},async resolveApproval(c,p,h){let L=$.getMessages().find(N=>{var _;return N.variant==="approval"&&((_=N.approval)==null?void 0:_.id)===c});if(!(L!=null&&L.approval))throw new Error(`Approval not found: ${c}`);if(L.approval.toolType==="webmcp"){$.resolveWebMcpApproval(L.id,p);return}return $.resolveApproval(L.approval,p,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,p){return s.on(c,p)},off(c,p){s.off(c,p)},isOpen(){return S()&&k},isVoiceActive(){return vt.active},getState(){return{open:S()&&k,launcherEnabled:I,voiceActive:vt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!k&&S()&&Ot(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Jf({onSubmit:async(y,L)=>{var N;$.isClientTokenMode()&&await $.submitCSATFeedback(y,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!k&&S()&&Ot(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Qf({onSubmit:async(y,L)=>{var N;$.isClientTokenMode()&&await $.submitNPSFeedback(y,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,p){return $.submitCSATFeedback(c,p)},async submitNPSFeedback(c,p){return $.submitNPSFeedback(c,p)},destroy(){po!=null&&(clearInterval(po),po=null),bt.forEach(c=>c()),Le.remove(),Je==null||Je.remove(),tn==null||tn.destroy(),nn==null||nn.remove(),lo&&F.removeEventListener("click",lo)}};if((((Gd=n==null?void 0:n.debugTools)!=null?Gd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,p={controller:cn,getMessages:cn.getMessages,getStatus:cn.getStatus,getMetadata:cn.getPersistentMetadata,updateMetadata:cn.updatePersistentMetadata,clearHistory:()=>cn.clearChat(),setVoiceActive:h=>h?cn.startVoiceRecognition():cn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,bt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",p),bt.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ee){let q=Ce=>{let ge=Ce.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.showEventStream()},O=Ce=>{let ge=Ce.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",O),bt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",O)})}let h=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.showArtifacts()},y=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.hideArtifacts()},L=q=>{let O=q.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&cn.upsertArtifact(O.artifact)},N=q=>{let O=q.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&cn.selectArtifact(O.id)},_=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",_),bt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",_)})}let uo=rv(o.persistState);if(uo&&S()){let c=sv(uo.storage),p=`${uo.keyPrefix}widget-open`,h=`${uo.keyPrefix}widget-voice`,y=`${uo.keyPrefix}widget-voice-mode`;if(c){let L=((Yd=uo.persist)==null?void 0:Yd.openState)&&c.getItem(p)==="true",N=((Xd=uo.persist)==null?void 0:Xd.voiceState)&&c.getItem(h)==="true",_=((Jd=uo.persist)==null?void 0:Jd.voiceState)&&c.getItem(y)==="true";if(L&&setTimeout(()=>{cn.open(),setTimeout(()=>{var q;if(N||_)cn.startVoiceRecognition();else if((q=uo.persist)!=null&&q.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Qd=uo.persist)!=null&&Qd.openState&&(s.on("widget:opened",()=>{c.setItem(p,"true")}),s.on("widget:closed",()=>{c.setItem(p,"false")})),(Zd=uo.persist)!=null&&Zd.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(p),c.removeItem(h),c.removeItem(y)},O=()=>q();window.addEventListener("persona:clear-chat",O),bt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return f&&S()&&setTimeout(()=>{cn.open()},0),Yo(),cn};var av=(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},og=(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"},Rc=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=""},rg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Rc(e)},Mc=e=>{e.style.transition=""},Lc=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=""},Ic=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},dl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},iv=(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))},lv=(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)},sg=(e,t,n,o,r,s,a)=>{var C,v,M,I,R,P;let i=No(s),d=i.reveal==="push";iv(e,t,n,o,d),lv(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,f=(v=(C=s==null?void 0:s.launcher)==null?void 0:C.mobileFullscreen)!=null?v:!0,u=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,g=l!=null?l.innerWidth<=u:!1;if(f&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Lc(t),Mc(o),rg(o),Ic(n),dl(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((P=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?P:Mn),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"),rg(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Lc(t),Mc(o),Ic(n),dl(r,o);let D=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":W;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=D,o.style.transform=w,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",Mc(o),Rc(o),dl(r,o);let D=av(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${W+D}px`,t.style.transition=w,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Lc(t),Rc(o),Ic(n),dl(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${W}`,o.style.width=W,o.style.maxWidth=W,o.style.minWidth=W,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||x?"hidden":"visible",o.style.transition=w,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")}},cv=(e,t)=>{let n=e.ownerDocument.createElement("div");return og(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){og(n,o)},destroy(){n.remove()}}},dv=(e,t)=>{var R,P,D,W;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),f=n.createElement("div"),u=(P=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||P?(W=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",f.dataset.personaDockRole="host",l.appendChild(f),o.insertBefore(a,e),d.appendChild(e);let g=null,m=()=>{g==null||g.disconnect(),g=null},C=()=>{m(),No(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{sg(a,i,d,l,f,t,u)}),g.observe(a))},v=()=>{sg(a,i,d,l,f,t,u),C()},M=a.ownerDocument.defaultView,I=()=>{v()};return M==null||M.addEventListener("resize",I),No(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:f,shell:a,syncWidgetState(w){let x=w.launcherEnabled?w.open:!0;u!==x&&(u=x,v())},updateConfig(w){var x,E;t=w,((E=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?E:!0)===!1&&(u=!0),v()},destroy(){M==null||M.removeEventListener("resize",I),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},ag=(e,t)=>wn(t)?dv(e,t):cv(e,t);var Kr={desktop:{w:1280,h:800},mobile:{w:390,h:844}},pl=.15,ul=1.5,Ba="persona-preview-shell-theme",Pc={load:()=>null,save:()=>{},clear:()=>{}},Wc=["How do I get started?","Pricing & plans","Talk to support"];function Ha(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Bc(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 ml(e){let t=Bc(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 fl(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Ba);o||(o=n.createElement("style"),o.id=Ba,n.head.appendChild(o)),o.textContent=ml(t)}var Hc=`
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>`,Dc=`
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 gl(e,t,n,o){let r=`
164
+ ${Hc}
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
+ ${Dc}
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="${Ha(o)}">
185
+ <style id="${Ba}">${ml(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 pv={"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 ig(e){return pv[e]}function hl(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 lg(e,t){return[...e,hl(t,e.length)]}function Fc(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function cg(e,t,n){var d,l;let o=hl(e,t);if(!Fc(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 f=r;f<a.length;f+=r)i.push({message:{...o,content:a.slice(0,f),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var uv=()=>[{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()}],mv=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 Oc(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"&&mv(t)?[...uv(),...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 bl(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:Wc:e.suggestionChips,initialMessages:Oc(t,e,n),storageAdapter:Pc};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function xr(e,t){var s,a,i,d;let n=e.theme?mn(e.theme,{validate:!1}):mn(),o=(s=e.scene)!=null?s:"conversation",r={...It,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return bl(r,o,(d=e.appendedMessages)!=null?d:[])}function dg(e,t,n){var a,i,d;let o=e.theme?mn(e.theme,{validate:!1}):mn(),r=(a=e.scene)!=null?a:"conversation",s={...It,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return bl(s,r,t)}function pg(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:xr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:xr(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:xr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:xr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:xr(e,n),shellMode:n}]}function ug(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function f(){var R;return(R=n.device)!=null?R:"desktop"}function u(){var R;return(R=n.zoom)!=null?R:i}function g(){var k,V;let R=getComputedStyle(e),P=parseFloat(R.paddingLeft)+parseFloat(R.paddingRight),D=parseFloat(R.paddingTop)+parseFloat(R.paddingBottom),W=40,w=((k=n.compareMode)!=null?k:"off")!=="off",x=(e.clientWidth-P-W)/(w?2:1),E=e.clientHeight-D-W;if(x<=0||E<=0)return 1;let S=(V=Kr[f()])!=null?V:Kr.desktop;return Math.min(x/S.w,E/S.h,1)}function m(){var D,W,w;i=g();let R=Math.max(pl,Math.min(ul,u()));d=R;let P=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of P){let E=(D=x.dataset.device)!=null?D:"desktop",S=(W=Kr[E])!=null?W:Kr.desktop;x.style.width=`${S.w*R}px`,x.style.height=`${S.h*R}px`,E==="mobile"&&(x.style.borderRadius=`${32*R}px`);let k=x.querySelector("iframe");k&&(k.style.width=`${S.w}px`,k.style.height=`${S.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${R})`)}(w=n.onScaleChange)==null||w.call(n,R)}function C(){var R;(R=n.onBeforeDestroy)==null||R.call(n);for(let P of o)P.destroy();for(let P of r)P();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var de,Ee,xe,De;if(a)return;C();let R=++l,P=pg(n),D=f(),W=((de=n.compareMode)!=null?de:"off")!=="off",w=((Ee=n.scene)!=null?Ee:"conversation")==="minimized",x=(xe=n.widgetCssPath)!=null?xe:"/widget-dist/widget.css",E=(De=n.buildSrcdoc)!=null?De:gl,S=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=Ae=>`<div class="${S}" data-mount-id="${Ae.mountId}" data-device="${D}" data-shell-mode="${Ae.shellMode}">
194
+ ${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ha(Ae.label)}</span></div>`:""}
195
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Ae.mountId}"></iframe>
196
+ </div>`,V=W?`<div class="preview-compare-grid">${P.map(Ae=>`<div class="preview-compare-cell">${k(Ae)}</div>`).join("")}</div>`:`<div class="preview-single">${k(P[0])}</div>`;n.morphContainer?n.morphContainer(e,V):e.innerHTML=V,m();let z=v(),Y=0,he=z.length,me=()=>{var le,J,se,ye,be;if(a||R!==l)return;for(let K of z){let ae=K.dataset.mountId;if(!ae||!K.contentDocument)continue;let Re=P.find(lt=>lt.mountId===ae);if(!Re)continue;let oe=()=>{},ee=wn(Re.config),re=ee?(()=>{var j;let lt=(j=K.contentDocument)==null?void 0:j.getElementById(`preview-content-${ae}`);if(!lt)return null;let Le=ag(lt,Re.config),pe=K.contentDocument.createElement("div");pe.id=ae,pe.style.height="100%",pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1",pe.style.minHeight="0",Le.host.appendChild(pe);let Je=()=>Le.syncWidgetState(it.getState()),Be=oe;return oe=()=>{Le.destroy(),Be()},pe.__syncDock=Je,pe.__hostLayout=Le,pe})():K.contentDocument.getElementById(ae);if(!re)continue;let it=ng(re,Re.config);if(o.push(it),ee&&re.__syncDock){let lt=re.__syncDock,Le=it.on("widget:opened",lt),pe=it.on("widget:closed",lt),Je=oe;oe=()=>{Le(),pe(),Je()},lt()}r.push(oe),w&&it.close()}if(((le=n.scene)!=null?le:"conversation")==="artifact"||(ye=(se=(J=n.config)==null?void 0:J.features)==null?void 0:se.artifacts)!=null&&ye.enabled)for(let K of o)K.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`});(be=n.onAfterMount)==null||be.call(n,{iframes:z,controllers:[...o]})};for(let Ae of z){let le=Ae.dataset.mountId;if(!le)continue;let J=P.find(se=>se.mountId===le);J&&(Ae.addEventListener("load",()=>{Y++,Y>=he&&me()},{once:!0}),Ae.srcdoc=E(le,J.shellMode,wn(J.config),x))}he===0&&me()}function I(){var D;if(a)return;let R=pg(n);if(o.length!==R.length){M();return}if(R.some(W=>{let w=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!w||w.dataset.shellMode!==W.shellMode})){M();return}o.forEach((W,w)=>{var x;W.update(R[w].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&W.close()});for(let W of R){let w=e.querySelector(`iframe[data-mount-id="${W.mountId}"]`);w&&fl(w,W.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),M(),{update(R){if(a)return;let P=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},P?M():I()},destroy(){a||(a=!0,C(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return v()},getScale(){return d},setZoom(R){a||(n={...n,zoom:R},m())}}}function _o(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Oa={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"},fv=/^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 gv(e){return fv.test(e)}function Gr(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=Oa[t];if(n)return n;let o=ps(t);if(mi(o)||o==="transparent"||gv(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(Oa).slice(0,6).join(", ")}).`)}var vl=Qs.map(e=>e==="gray"?"neutral":e),hv={...Object.fromEntries(vl.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Na(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=hv[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 _a(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 Va(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 bv={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function $a(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=bv[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Ua(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=pi(t);return ui(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function xl(e){for(let t of Fr){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 mg=xl("typo-font-family"),Da=xl("typo-font-size"),Fa=xl("typo-font-weight"),yl=xl("typo-line-height"),fg={...mg,monospace:mg.mono},gg={...Da,small:Da.sm,md:Da.base,medium:Da.base,large:Da.lg},hg={...Fa,400:Fa.normal,500:Fa.medium,600:Fa.semibold,700:Fa.bold},bg={...yl,"1.25":yl.tight,"1.5":yl.normal,"1.625":yl.relaxed};function yg(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 vg="theme.palette.radius.";function yv(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Fr)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(vg)&&typeof i=="string"&&(s[a.slice(vg.length)]=i);e[r[1]]=s}return e}var Es=yv(),xg=["sm","md","lg","xl","full"];function Cl(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Cl(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Cl(e,r,n,o+1):null}function wl(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 Ms(e){return e.replace(/^role-/,"")}function vv(e){for(let[t,n]of Object.entries(Es))if(xg.every(o=>e[o]===n[o]))return t;return"custom"}function wr(e){var o,r;let t={};for(let s of xg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of fr)n[Ms(s.roleId)]=bi(a=>e.get(`theme.${a}`),s);return{brand:{primary:Nc(e.get("theme.palette.colors.primary.500")),secondary:Nc(e.get("theme.palette.colors.secondary.500")),accent:Nc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:wl(e,"theme.semantic.typography.fontFamily"),fontSize:wl(e,"theme.semantic.typography.fontSize"),fontWeight:wl(e,"theme.semantic.typography.fontWeight"),lineHeight:wl(e,"theme.semantic.typography.lineHeight")},roundness:{style:vv(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Nc(e){return typeof e=="string"&&e!==""?e:null}var ks=[{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 wg(e){let t=new Set(e.targets.map(n=>n.path));return ks.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var xv={AA:4.5,AAA:7};function wv(e){return Math.round(e*100)/100}function Cv(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=Dr.indexOf(a[2]),l=null,f=1/0;return Dr.forEach((u,g)=>{let m=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&Js(m,n)>=o){let C=d>=0?Math.abs(g-d):g;C<f&&(f=C,l=`palette.colors.${i}.${u}`)}}),l}function Ls(e,t="AA",n="both",o){let r=xv[t],s=n==="both"?["light","dark"]:[n],a=o?ks.filter(d=>o.includes(d.key)):ks,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let f of a){let u=Cl(e,f.fg,l),g=Cl(e,f.bg,l);if(!u||!g)continue;let m=wv(Js(u,g)),C=m>=r,v={pair:f.key,label:f.label,variant:d,fg:u,bg:g,ratio:m,threshold:r,passes:C};if(!C){let M=Cv(e,f.fg,g,r,l);M&&(v.suggestion=M)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Yr(e,t,n="light",o="AA"){return t.length===0?[]:Ls(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 bn={};for(let e of fr){let t=Ms(e.roleId);bn[t]=e,bn[e.roleId]=e}Object.assign(bn,{surface:bn.surfaces,background:bn.surfaces,backgrounds:bn.surfaces,user:bn["user-messages"],"user-message":bn["user-messages"],assistant:bn["assistant-messages"],"assistant-message":bn["assistant-messages"],actions:bn["primary-actions"],buttons:bn["primary-actions"],composer:bn.input,links:bn["links-focus"],focus:bn["links-focus"],border:bn.borders,dividers:bn.borders,scroll:bn["scroll-to-bottom"]});function Sv(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=bn[t];if(!n){let o=fr.map(r=>Ms(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Cg(){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 yi)t(n.sections);for(let n of da)t(n.sections);return e}var Av={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Tv={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},_c=["bottom-right","bottom-left","top-right","top-left"],Vc=["bubble","flat","minimal"],kv={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function $c(e,t){var W;let n=(W=t==null?void 0:t.editTarget)!=null?W:"both",o=null,r=w=>w&&typeof w=="object"?w:{},s=(w,x,E=n)=>{let S={};return(E==="light"||E==="both")&&(S[`theme.${w}`]=x),(E==="dark"||E==="both")&&(S[`darkTheme.${w}`]=x),S},a=w=>{if(n==="both")return w;let x={};for(let[E,S]of Object.entries(w))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(x[E]=S);return x},i=()=>n==="dark"?"dark":"light",d=(w,x=[])=>_o({ok:!0,summary:wr(e),warnings:x,applied:w});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(w){let{verbosity:x}=r(w),E={summary:wr(e),availableRoles:fr.map(S=>({role:Ms(S.roleId),helper:S.helper})),availableFamilies:vl,presets:ms.map(S=>{var k;return{id:S.id,name:S.name,description:S.description,tags:(k=S.tags)!=null?k:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=Cg()),E.fieldIndex=Array.from(o.values()).map(S=>{var k;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(k=S.options)==null?void 0:k.map(V=>V.value)}})),_o(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(w){let x=r(w),E=["primary","secondary","accent"],S={},k={};for(let z of E){if(x[z]===void 0)continue;let Y=Gr(x[z]);k[z]=Y;let he=gi(Y);for(let me of Dr){let de=he[me];de!==void 0&&Object.assign(S,s(`palette.colors.${z}.${me}`,de))}}if(Object.keys(k).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let V=Yr(e,["primary-button","user-message"],i());return d(k,V)}},{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:vl},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(w){let x=r(w),E=Sv(x.role),S=Na(x.family,!0),k=_a(x.intensity),V=a(la(S,k,E)),z=Object.keys(V).length;e.setBatch(V);let Y=Yr(e,wg(E),i());return d({role:Ms(E.roleId),family:S,intensity:k,tokensWritten:z},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(w){let x=r(w),E={},S={},k=(V,z)=>{var he;if(x[V]===void 0)return;let Y=yg(x[V],z,V);S[V]=(he=Y.split(".").pop())!=null?he:Y,Object.assign(E,s(`semantic.typography.${V}`,Y))};if(k("fontFamily",fg),k("fontSize",gg),k("fontWeight",hg),k("lineHeight",bg),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(w){let x=r(w),E={},S={};if(x.style!==void 0){let k=$a(x.style);S.style=k;for(let[V,z]of Object.entries(Es[k]))Object.assign(E,s(`palette.radius.${V}`,z))}if(x.radius!==void 0){let k=r(x.radius),V={};for(let z of["sm","md","lg","xl","full"]){if(k[z]===void 0)continue;let Y=Ua(k[z]);V[z]=Y,Object.assign(E,s(`palette.radius.${z}`,Y))}S.radius=V}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(w){let x=r(w),E={};if(x.scheme!==void 0){let S=Va(x.scheme);e.set("colorScheme",S),E.scheme=S}if(x.editTarget!==void 0){let S=String(x.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=S,E.editTarget=S}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return _o({ok:!0,summary:wr(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(w){let{presetId:x}=r(w),E=vi(String(x!=null?x:""));if(!E){let z=ms.map(Y=>Y.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${z}.`)}let S=mn(E.theme,{validate:!1}),k={...e.getConfig()};E.darkTheme&&(k.darkTheme=mn(E.darkTheme,{validate:!1})),E.toolCall&&(k.toolCall=E.toolCall),e.setFullConfig(k,S);let V=Yr(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.name}},V)}},{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:_c},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:Vc}},additionalProperties:!1}},additionalProperties:!1},execute(w){var z,Y,he;let x=r(w),E={},S={};if(x.launcherPosition!==void 0){let me=String(x.launcherPosition);if(!_c.includes(me))throw new Error(`Unknown launcherPosition "${me}". Valid: ${_c.join(", ")}.`);E["launcher.position"]=me,S.launcherPosition=me}let k=r(x.features);for(let[me,de]of Object.entries(Av))k[me]!==void 0&&(E[de]=!!k[me],(z=S.features)!=null||(S.features={}),S.features[me]=!!k[me]);let V=r(x.layout);for(let[me,de]of Object.entries(Tv))if(V[me]!==void 0)if(me==="messageStyle"){let Ee=String(V[me]);if(!Vc.includes(Ee))throw new Error(`Unknown messageStyle "${Ee}". Valid: ${Vc.join(", ")}.`);E[de]=Ee,(Y=S.layout)!=null||(S.layout={}),S.layout[me]=Ee}else E[de]=!!V[me],(he=S.layout)!=null||(S.layout={}),S.layout[me]=!!V[me];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(w){let x=r(w),E={},S={};for(let[k,V]of Object.entries(kv))x[k]!==void 0&&(E[V]=String(x[k]),S[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(V=>typeof V=="string");E.suggestionChips=k,S.suggestions=k}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(w){var V;let{updates:x}=r(w);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=Cg());let E={},S=[];for(let z of x){let Y=r(z),he=String((V=Y.field)!=null?V:"");try{let me=o.get(he),de=me?me.path:he;if(!me&&!/^(theme|darkTheme)\.|\./.test(de))throw new Error(`Unknown field "${he}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let Ee=Ev(me,Y.value);if(me&&de.startsWith("theme.")){let xe=s(de.slice(6),Ee);Object.assign(E,xe),S.push({field:he,resolvedPath:Object.keys(xe),ok:!0})}else E[de]=Ee,S.push({field:he,resolvedPath:de,ok:!0})}catch(me){S.push({field:he,ok:!1,error:me.message})}}let k=S.filter(z=>z.ok);return Object.keys(E).length>0&&e.setBatch(E),_o({ok:k.length>0,summary:wr(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(w){let x=r(w),E=x.level==="AAA"?"AAA":"AA",S=x.variant==="light"||x.variant==="dark"?x.variant:"both",k=Ls(e,E,S);return _o({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(w){let{action:x}=r(w);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 _o({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Ev(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(Gr(t)):Gr(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});