@runtypelabs/persona 3.31.0 → 3.33.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 (51) hide show
  1. package/README.md +2 -0
  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-quh7NmYD.d.cts → types-CthJFfNx.d.cts} +7 -0
  5. package/dist/animations/{types-quh7NmYD.d.ts → types-CthJFfNx.d.ts} +7 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +4 -4
  9. package/dist/codegen.js +3 -3
  10. package/dist/index.cjs +43 -43
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +288 -8
  13. package/dist/index.d.ts +288 -8
  14. package/dist/index.global.js +76 -79
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +43 -43
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js.map +1 -1
  19. package/dist/smart-dom-reader.d.cts +78 -2
  20. package/dist/smart-dom-reader.d.ts +78 -2
  21. package/dist/theme-editor.cjs +30 -30
  22. package/dist/theme-editor.d.cts +92 -5
  23. package/dist/theme-editor.d.ts +92 -5
  24. package/dist/theme-editor.js +30 -30
  25. package/dist/webmcp-polyfill.js +4 -0
  26. package/package.json +4 -3
  27. package/src/ask-user-question-tool.test.ts +148 -0
  28. package/src/ask-user-question-tool.ts +138 -0
  29. package/src/client.ts +43 -9
  30. package/src/components/messages.ts +10 -0
  31. package/src/components/suggestions.ts +49 -6
  32. package/src/index-core.ts +15 -0
  33. package/src/index-global.ts +39 -0
  34. package/src/runtime/host-layout.test.ts +158 -3
  35. package/src/runtime/host-layout.ts +95 -1
  36. package/src/session.ts +188 -32
  37. package/src/session.webmcp.test.ts +48 -0
  38. package/src/suggest-replies-tool.test.ts +445 -0
  39. package/src/suggest-replies-tool.ts +152 -0
  40. package/src/theme-editor/index.ts +2 -0
  41. package/src/theme-editor/webmcp/index.ts +2 -0
  42. package/src/theme-editor/webmcp/types.ts +16 -3
  43. package/src/types.ts +79 -2
  44. package/src/ui.suggest-replies.test.ts +237 -0
  45. package/src/ui.ts +57 -13
  46. package/src/utils/dock.test.ts +23 -1
  47. package/src/utils/dock.ts +2 -0
  48. package/src/version.ts +5 -2
  49. package/src/webmcp-bridge.test.ts +60 -0
  50. package/src/webmcp-bridge.ts +34 -1
  51. package/src/webmcp-polyfill.ts +16 -0
@@ -1,18 +1,18 @@
1
- var ku=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function $s(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];ku(s)&&ku(r)?n[o]=$s(s,r):n[o]=r}return n}var fo="min(440px, calc(100vw - 24px))",Fa="440px",Lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:fo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},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 Eu(e,t){if(!(!e&&!t))return e?t?$s(e,t):e:t}function Mu(e){var t,n,o,r,s,a,i,d,l,f,u,g,m,C,v,E,L,I,R,H,P;return e?{...Lt,...e,theme:Eu(Lt.theme,e.theme),darkTheme:Eu(Lt.darkTheme,e.darkTheme),launcher:{...Lt.launcher,...e.launcher,dock:{...(t=Lt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Lt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Lt.copy,...e.copy},sendButton:{...Lt.sendButton,...e.sendButton},statusIndicator:{...Lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Lt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ie,X,re,be,he,j,se,Ie,ne,Z;let w=(ie=Lt.features)==null?void 0:ie.artifacts,x=(X=e.features)==null?void 0:X.artifacts,k=(re=Lt.features)==null?void 0:re.scrollToBottom,S=(be=e.features)==null?void 0:be.scrollToBottom,T=(he=Lt.features)==null?void 0:he.scrollBehavior,_=(j=e.features)==null?void 0:j.scrollBehavior,U=(se=Lt.features)==null?void 0:se.streamAnimation,G=(Ie=e.features)==null?void 0:Ie.streamAnimation,ge=(ne=Lt.features)==null?void 0:ne.askUserQuestion,ue=(Z=e.features)==null?void 0:Z.askUserQuestion,ce=w===void 0&&x===void 0?void 0:{...w,...x,layout:{...w==null?void 0:w.layout,...x==null?void 0:x.layout}},ke=k===void 0&&S===void 0?void 0:{...k,...S},ve=T===void 0&&_===void 0?void 0:{...T,..._},He=U===void 0&&G===void 0?void 0:{...U,...G},Se=ge===void 0&&ue===void 0?void 0:{...ge,...ue,styles:{...ge==null?void 0:ge.styles,...ue==null?void 0:ue.styles}};return{...Lt.features,...e.features,...ke!==void 0?{scrollToBottom:ke}:{},...ve!==void 0?{scrollBehavior:ve}:{},...ce!==void 0?{artifacts:ce}:{},...He!==void 0?{streamAnimation:He}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Lt.suggestionChips,suggestionChipsConfig:{...Lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Lt.layout,...e.layout,header:{...(a=Lt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Lt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(f=Lt.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=Lt.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(L=(E=e.layout)==null?void 0:E.messages)==null?void 0:L.timestamp}},slots:{...(I=Lt.layout)==null?void 0:I.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...Lt.markdown,...e.markdown,options:{...(H=Lt.markdown)==null?void 0:H.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Lt.messageActions,...e.messageActions}}:Lt}var ng={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"}},og={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"}},rg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:fo,maxWidth:Fa,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 ns(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."))?ns(e,o):o}function Lu(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=ns(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 sg(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 Iu(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]=Iu(s,r):n[o]=r}return n}function ag(e,t){return t?Iu(e,t):e}function un(e,t={}){var r,s,a,i,d,l,f,u,g,m,C,v,E;let n={palette:ng,semantic:og,components:rg},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,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:ag(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let L=sg(o);if(!L.valid)throw new Error(`Theme validation failed: ${L.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let L of t.plugins)o=L.transform(o);return o}function Ru(e){var v,E,L,I,R,H,P,w,x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se,ie,X,re,be,he,j,se,Ie,ne,Z,oe,at,it,Me,de,Xe,We,q,me,et,Et,ee,ze,Dn,Ht,sn,no,ko,D,pe,De,je,Ne,Ve,nt,Rt,jt,Xt,K,vt,rt,Ce,le,Ze,Jt,Kt,Ln,yn,ft,Mt,Je,zt,an,wn,Cn,bn,Eo,St,$n,Un,No,bo,xt,br,Mo,yr,Fn,Ur,Qo,_o,At,zn,qn,In,It,oo,ro,jn,Zo,Vo,er,Kn,Dt,Rn,so,tr,$o,nr,Lo,Gn,yo,ht,Qt,Zt,Yn,or;let t=Lu(e),n={};for(let[xe,ao]of Object.entries(t)){let io=xe.replace(/\./g,"-");n[`--persona-${io}`]=ao.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(L=n["--persona-semantic-colors-accent"])!=null?L:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(R=n["--persona-semantic-colors-background"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(H=n["--persona-semantic-colors-container"])!=null?H:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P: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"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(T=n["--persona-components-voice-recording-indicator"])!=null?T:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(_=n["--persona-components-voice-recording-background"])!=null?_:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(U=n["--persona-components-voice-processing-icon"])!=null?U:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(G=n["--persona-components-voice-speaking-icon"])!=null?G:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ge=n["--persona-components-approval-requested-background"])!=null?ge:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ue=n["--persona-components-approval-requested-border"])!=null?ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ce=n["--persona-components-approval-requested-text"])!=null?ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ke=n["--persona-components-approval-requested-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(ve=n["--persona-components-approval-approve-background"])!=null?ve:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(He=n["--persona-components-approval-deny-background"])!=null?He:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ie=n["--persona-components-attachment-image-border"])!=null?ie:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(be=n["--persona-semantic-typography-fontWeight"])!=null?be:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(he=n["--persona-semantic-typography-lineHeight"])!=null?he: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"]=(j=n["--persona-palette-radius-sm"])!=null?j:"0.125rem",n["--persona-radius-md"]=(se=n["--persona-palette-radius-md"])!=null?se:"0.375rem",n["--persona-radius-lg"]=(Ie=n["--persona-palette-radius-lg"])!=null?Ie:"0.5rem",n["--persona-radius-xl"]=(ne=n["--persona-palette-radius-xl"])!=null?ne:"0.75rem",n["--persona-radius-full"]=(Z=n["--persona-palette-radius-full"])!=null?Z:"9999px",n["--persona-launcher-radius"]=(at=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?at:"9999px",n["--persona-launcher-bg"]=(it=n["--persona-components-launcher-background"])!=null?it:n["--persona-primary"],n["--persona-launcher-fg"]=(Me=n["--persona-components-launcher-foreground"])!=null?Me:n["--persona-text-inverse"],n["--persona-launcher-border"]=(de=n["--persona-components-launcher-border"])!=null?de:n["--persona-border"],n["--persona-button-primary-bg"]=(Xe=n["--persona-components-button-primary-background"])!=null?Xe:n["--persona-primary"],n["--persona-button-primary-fg"]=(We=n["--persona-components-button-primary-foreground"])!=null?We:n["--persona-text-inverse"],n["--persona-button-radius"]=(me=(q=n["--persona-components-button-primary-borderRadius"])!=null?q:n["--persona-palette-radius-full"])!=null?me:"9999px",n["--persona-panel-radius"]=(Et=(et=n["--persona-components-panel-borderRadius"])!=null?et:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(ee=n["--persona-components-panel-border"])!=null?ee:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Dn=(ze=n["--persona-components-panel-shadow"])!=null?ze:n["--persona-palette-shadows-xl"])!=null?Dn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Ht=n["--persona-components-launcher-shadow"])!=null?Ht:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(no=(sn=n["--persona-components-input-borderRadius"])!=null?sn:n["--persona-radius-lg"])!=null?no:"0.5rem",n["--persona-message-user-radius"]=(D=(ko=n["--persona-components-message-user-borderRadius"])!=null?ko:n["--persona-radius-lg"])!=null?D:"0.5rem",n["--persona-message-assistant-radius"]=(De=(pe=n["--persona-components-message-assistant-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?De:"0.5rem",n["--persona-header-bg"]=(je=n["--persona-components-header-background"])!=null?je:n["--persona-surface"],n["--persona-header-border"]=(Ne=n["--persona-components-header-border"])!=null?Ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ve=n["--persona-components-header-iconBackground"])!=null?Ve:n["--persona-primary"],n["--persona-header-icon-fg"]=(nt=n["--persona-components-header-iconForeground"])!=null?nt:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Rt=n["--persona-components-header-titleForeground"])!=null?Rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(jt=n["--persona-components-header-subtitleForeground"])!=null?jt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Xt=n["--persona-components-header-actionIconForeground"])!=null?Xt:n["--persona-muted"];let o=(K=e.components)==null?void 0:K.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(vt=e.components)==null?void 0:vt.introCard;n["--persona-intro-card-bg"]=(rt=n["--persona-components-introCard-background"])!=null?rt:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ce=n["--persona-components-introCard-borderRadius"])!=null?Ce:"1rem",n["--persona-intro-card-padding"]=(le=n["--persona-components-introCard-padding"])!=null?le:"1.5rem",n["--persona-intro-card-shadow"]=(Jt=(Ze=r==null?void 0:r.shadow)!=null?Ze:n["--persona-components-introCard-shadow"])!=null?Jt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Kt=n["--persona-components-input-background"])!=null?Kt:n["--persona-surface"],n["--persona-input-placeholder"]=(Ln=n["--persona-components-input-placeholder"])!=null?Ln:n["--persona-text-muted"],n["--persona-message-user-bg"]=(yn=n["--persona-components-message-user-background"])!=null?yn:n["--persona-accent"],n["--persona-message-user-text"]=(ft=n["--persona-components-message-user-text"])!=null?ft:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Mt=n["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Je=n["--persona-components-message-assistant-background"])!=null?Je:n["--persona-surface"],n["--persona-message-assistant-text"]=(zt=n["--persona-components-message-assistant-text"])!=null?zt:n["--persona-text"],n["--persona-message-assistant-border"]=(an=n["--persona-components-message-assistant-border"])!=null?an:n["--persona-border"],n["--persona-message-assistant-shadow"]=(wn=n["--persona-components-message-assistant-shadow"])!=null?wn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(bn=(Cn=n["--persona-components-scrollToBottom-background"])!=null?Cn:n["--persona-button-primary-bg"])!=null?bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(St=(Eo=n["--persona-components-scrollToBottom-foreground"])!=null?Eo:n["--persona-button-primary-fg"])!=null?St:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=($n=n["--persona-components-scrollToBottom-border"])!=null?$n:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Un=n["--persona-components-scrollToBottom-size"])!=null?Un:"40px",n["--persona-scroll-to-bottom-radius"]=(xt=(bo=(No=n["--persona-components-scrollToBottom-borderRadius"])!=null?No:n["--persona-button-radius"])!=null?bo:n["--persona-radius-full"])!=null?xt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Mo=(br=n["--persona-components-scrollToBottom-shadow"])!=null?br:n["--persona-palette-shadows-sm"])!=null?Mo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(yr=n["--persona-components-scrollToBottom-padding"])!=null?yr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Fn=n["--persona-components-scrollToBottom-gap"])!=null?Fn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Qo=(Ur=n["--persona-components-scrollToBottom-fontSize"])!=null?Ur:n["--persona-palette-typography-fontSize-sm"])!=null?Qo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(_o=n["--persona-components-scrollToBottom-iconSize"])!=null?_o:"14px",n["--persona-tool-bubble-shadow"]=(At=n["--persona-components-toolBubble-shadow"])!=null?At:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(zn=n["--persona-components-reasoningBubble-shadow"])!=null?zn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(qn=n["--persona-components-composer-shadow"])!=null?qn:"none",n["--persona-md-inline-code-bg"]=(In=n["--persona-components-markdown-inlineCode-background"])!=null?In:n["--persona-container"],n["--persona-md-inline-code-color"]=(It=n["--persona-components-markdown-inlineCode-foreground"])!=null?It:n["--persona-text"],n["--persona-md-link-color"]=(ro=(oo=n["--persona-components-markdown-link-foreground"])!=null?oo:n["--persona-accent"])!=null?ro:"#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"]=(jn=n["--persona-components-markdown-codeBlock-background"])!=null?jn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Zo=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Zo:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Vo=n["--persona-components-markdown-codeBlock-textColor"])!=null?Vo:"inherit",n["--persona-md-table-header-bg"]=(er=n["--persona-components-markdown-table-headerBackground"])!=null?er:n["--persona-container"],n["--persona-md-table-border-color"]=(Kn=n["--persona-components-markdown-table-borderColor"])!=null?Kn:n["--persona-border"],n["--persona-md-hr-color"]=(Dt=n["--persona-components-markdown-hr-color"])!=null?Dt:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Rn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Rn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(so=n["--persona-components-markdown-blockquote-background"])!=null?so:"transparent",n["--persona-md-blockquote-text-color"]=(tr=n["--persona-components-markdown-blockquote-textColor"])!=null?tr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=($o=n["--persona-components-collapsibleWidget-container"])!=null?$o:n["--persona-surface"],n["--cw-surface"]=(nr=n["--persona-components-collapsibleWidget-surface"])!=null?nr:n["--persona-surface"],n["--cw-border"]=(Lo=n["--persona-components-collapsibleWidget-border"])!=null?Lo:n["--persona-border"],n["--persona-message-border"]=(Gn=n["--persona-components-message-border"])!=null?Gn: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 xe=C.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(yo=n["--persona-dropdown-bg"])!=null?yo:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(ht=n["--persona-dropdown-border"])!=null?ht:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(Qt=n["--persona-dropdown-shadow"])!=null?Qt:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Zt=n["--persona-dropdown-radius"])!=null?Zt:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Yn=n["--persona-dropdown-item-hover-bg"])!=null?Yn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(C!=null&&C.tab){let xe=C.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(C!=null&&C.pane){let xe=C.pane;if(xe.toolbarBackground){let ao=(or=ns(e,xe.toolbarBackground))!=null?or:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ao}}return n}var ig={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"}}},Pu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},il=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},lg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":il()},cg=e=>lg(e),dg=e=>un(e),pg=e=>{var n;let t=un(void 0,{validate:!1});return un({...e,palette:{...t.palette,colors:{...ig.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Oa=e=>{let t=cg(e),n=Pu(e==null?void 0:e.theme),o=Pu(e==null?void 0:e.darkTheme);return t==="dark"?pg($s(n!=null?n:{},o!=null?o:{})):dg(n)},ug=e=>Ru(e),os=(e,t)=>{let n=Oa(t),o=ug(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},Wu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(il())});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(il());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 Ir(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]:Ir((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var cl=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?{...Lt,...n}:n!=null?n:Lt,this.theme=un(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=Ir(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:un();this.config={...this.config,darkTheme:Ir(s,r,n)}}else this.config=Ir(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=Ir(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:un();this.config={...this.config,darkTheme:Ir(l,d,i)},o=!0}else this.config=Ir(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=un((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=un(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Lt},this.theme=un(),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=un(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function dl(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 pl(e,t){return t==="rem"?`${e}rem`:`${e}px`}function mg(e,t){return t==="rem"?e*16:e}function fg(e,t){return t==="rem"?e/16:e}function Us(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 ul(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function ml(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 Na(e,t){let n=s=>{var l;let a=Us(s),i=a.startsWith("rgb")?(l=ml(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 Bu(e){var g;let t=Us(e),n=t.startsWith("rgb")?(g=ml(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 Hu(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 fl(e){let{h:t,s:n,l:o}=Bu(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]=Hu(t,l,d)}return a}var rs=["50","100","200","300","400","500","600","700","800","900","950"],gl=["primary","secondary","accent","gray","success","warning","error","info"];function gg(e,t){return`palette.colors.${e}.${t}`}function Du(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.")?Du(e,`theme.${o}`,n+1):"#cbd5e1"}function hg(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 Do=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],_a=["primary","secondary","accent","gray"],bg={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Va={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:Do,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},$a={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:Do,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"}]},Ua={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:Do,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},za={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:Do,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},qa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:Do,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"}]},ja={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:Do,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Ka={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:Do,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"}]},Ga={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:Do,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"}]},Ya={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:Do,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},Rr=[Va,$a,Ua,za,qa,ja,Ka,Ga,Ya];function Xa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=yg(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 yg(e,t,n,o){let r=t==="solid";if(o==="role-header")return vg(e,r,n);if(o==="role-input")return xg(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 vg(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 xg(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 wg=/^palette\.colors\.(\w+)\.(\d+)$/;function hl(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(wg);if(!r)return null;let s=r[1],a=_a.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let f=Xa(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 Cg={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"}]}]},Sg={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"}]},Ag={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"}}]},Tg={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},kg={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Eg={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"}}]},Mg={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Lg={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},as=[Sg,Ag,kg,Tg,Cg,Eg,Mg,Lg];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:gl.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"}}]},Ig=Ou(),Rg=Nu,Pg=[Ou(),Nu],Wg={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:fo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Fa},{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"}]}]},Bg={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"}]}]},Hg={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"}]}]},Dg={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"}]}]},Fg={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"}]}]},Og={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"}}]},Ng={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"}}]},_g={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"}}]},Vg={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"}}]},$g={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"}]},ss=[{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"}],bl="0 5px 15px rgba(15, 23, 42, 0.08)",Fu=[{value:bl,label:"Default"},...ss],Ug={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:ss},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:ss},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:ss},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:ss},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:bl,options:Fu},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:bl,options:Fu},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:ss}]},_u=[Wg,Bg,Hg,Dg,Fg,Ug],Vu=[Og,Ng,_g,Vg,$g],$u=[..._u,...Vu],yl=1024*1024,zg=["What can you help me with?","Tell me about your features","How does this work?"],zs={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function qg(e){return Number(e)*yl}function jg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/yl)):String(t):"10"}function Kg(e){var t;return(t=zs[String(e)])!=null?t:zs.images}function Gg(e){let t=Array.isArray(e)?e:zs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(zs)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var Yg={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"}]},Xg={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:zg}]},Jg={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:""}]},Qg={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}]},Zg={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"}]}]},eh={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"}]}]},th={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:fo},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},nh={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:""}]},oh={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"}]},rh={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"}]},sh={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"}]},ah={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"}]},ih={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:""}]},lh={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)}]},ch={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*yl,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:jg,parseValue:qg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:zs.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Gg,parseValue:Kg}]},dh={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"}]}]},ph={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}]},uh={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"}]}]},mh={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}]},fh={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}]},Ja=[{label:"Content",sections:[Yg,Xg]},{label:"Layout",sections:[Jg,Qg,Zg,eh]},{label:"Widget",sections:[th,nh,oh,rh,sh,ah]},{label:"Features",sections:[ih,lh,ch,dh,ph]},{label:"Developer",collapsedByDefault:!0,sections:[uh,mh,fh]}],Uu=Ja.flatMap(e=>e.sections),zu={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"}]}]},qu={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"}]},ju={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"}]},Ku={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:Va},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:$a},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ua},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:za},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:qa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:ja},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ka},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Ga},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Ya}]},Gu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},Yu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},gh=[zu,qu,ju,Ku,Gu,Yu],vl=[{id:"style",label:"Style",sections:as},{id:"design-system",label:"Design System",sections:$u},{id:"configure",label:"Configure",sections:Uu}];function Xu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function hh(e,t,n){return{...e,id:`${n}-${e.id}`,path:Xu(e.path,t)}}function bh(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function yh(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=>hh(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])=>[Xu(d,t),l]))}))}}var Ju=[{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"]}],qs=[...Ju];function xl(e){return qs.find(t=>t.id===e)}import{Marked as vh}from"marked";var xh=e=>{if(e)return e},wl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new vh({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=xh(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},Qa=e=>e?wl({markedOptions:e.options,renderer:e.renderer}):wl(),Kw=wl();var js=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");import wh from"dompurify";var Ch={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"]},Sh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ah=()=>{let e=wh(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:")&&!Sh.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Ch)},Za=e=>e===!1?null:typeof e=="function"?e:Ah();var Pr="webmcp:",Cl=new Map,Qu=e=>{var t;Cl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Cl.set(n.name,o)}},Sl=e=>Cl.get(tm(e)),ei={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function em(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}:${Th(t.join(""))}`}function Zu(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 Th(e){let t=Zu(e,0).toString(36),n=Zu(e,2654435761).toString(36);return`${t}.${n}`}var ti=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 ei.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}Qu(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=Eh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return Ao(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=tm(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return Ao(`Failed to read WebMCP registry: ${v}`)}Qu(a);let i=a.find(C=>C.name===s);if(!i)return Ao(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ao(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let d=Sl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("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,Rh(n),{signal:f.signal});return Mh(C)}catch(C){if(u)return Ao(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return Ao(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){ei.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,ei.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:Lh;try{return await n(t)}catch(r){return ei.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=>kh(t,o))}},tm=e=>e.startsWith(Pr)?e.slice(Pr.length):e,is=e=>e.startsWith(Pr),kh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Eh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Mh=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:Ph(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),Lh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ih(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var Ru=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Us(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Ru(s)&&Ru(r)?n[o]=Us(s,r):n[o]=r}return n}var mo="min(440px, calc(100vw - 24px))",_a="440px",Mt={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:mo,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 Pu(e,t){if(!(!e&&!t))return e?t?Us(e,t):e:t}function Wu(e){var t,n,o,r,s,a,i,d,l,u,g,f,m,x,v,E,L,I,W,H,R;return e?{...Mt,...e,theme:Pu(Mt.theme,e.theme),darkTheme:Pu(Mt.darkTheme,e.darkTheme),launcher:{...Mt.launcher,...e.launcher,dock:{...(t=Mt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Mt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Mt.copy,...e.copy},sendButton:{...Mt.sendButton,...e.sendButton},statusIndicator:{...Mt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Mt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ie,X,re,be,he,j,se,Re,ne,Z;let w=(ie=Mt.features)==null?void 0:ie.artifacts,C=(X=e.features)==null?void 0:X.artifacts,k=(re=Mt.features)==null?void 0:re.scrollToBottom,A=(be=e.features)==null?void 0:be.scrollToBottom,S=(he=Mt.features)==null?void 0:he.scrollBehavior,_=(j=e.features)==null?void 0:j.scrollBehavior,V=(se=Mt.features)==null?void 0:se.streamAnimation,K=(Re=e.features)==null?void 0:Re.streamAnimation,fe=(ne=Mt.features)==null?void 0:ne.askUserQuestion,ue=(Z=e.features)==null?void 0:Z.askUserQuestion,ce=w===void 0&&C===void 0?void 0:{...w,...C,layout:{...w==null?void 0:w.layout,...C==null?void 0:C.layout}},ke=k===void 0&&A===void 0?void 0:{...k,...A},ve=S===void 0&&_===void 0?void 0:{...S,..._},He=V===void 0&&K===void 0?void 0:{...V,...K},Se=fe===void 0&&ue===void 0?void 0:{...fe,...ue,styles:{...fe==null?void 0:fe.styles,...ue==null?void 0:ue.styles}};return{...Mt.features,...e.features,...ke!==void 0?{scrollToBottom:ke}:{},...ve!==void 0?{scrollBehavior:ve}:{},...ce!==void 0?{artifacts:ce}:{},...He!==void 0?{streamAnimation:He}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Mt.suggestionChips,suggestionChipsConfig:{...Mt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Mt.layout,...e.layout,header:{...(a=Mt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Mt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(g=(u=Mt.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(v=(x=Mt.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(L=(E=e.layout)==null?void 0:E.messages)==null?void 0:L.timestamp}},slots:{...(I=Mt.layout)==null?void 0:I.slots,...(W=e.layout)==null?void 0:W.slots}},markdown:{...Mt.markdown,...e.markdown,options:{...(H=Mt.markdown)==null?void 0:H.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Mt.messageActions,...e.messageActions}}:Mt}var mf={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"}},gf={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"}},ff={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:mo,maxWidth:_a,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 ss(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."))?ss(e,o):o}function Bu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=ss(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 hf(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Hu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Hu(s,r):n[o]=r}return n}function bf(e,t){return t?Hu(e,t):e}function pn(e,t={}){var r,s,a,i,d,l,u,g,f,m,x,v,E;let n={palette:mf,semantic:gf,components:ff},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(f=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:bf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let L=hf(o);if(!L.valid)throw new Error(`Theme validation failed: ${L.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let L of t.plugins)o=L.transform(o);return o}function Du(e){var v,E,L,I,W,H,R,w,C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se,ie,X,re,be,he,j,se,Re,ne,Z,oe,at,it,Le,de,Xe,We,q,me,tt,Tt,te,ze,Nn,Bt,an,ro,Eo,D,pe,De,Ke,Ne,Ve,ot,It,qt,Qt,G,yt,st,Ce,le,Ze,Zt,jt,Rn,xn,ut,kt,Qe,Ut,ln,Sn,An,bn,Mo,Ct,zn,qn,No,ho,vt,yr,Lo,vr,_n,qr,Zo,_o,St,jn,Kn,Pn,Lt,so,ao,Gn,er,Vo,tr,Yn,Ht,Wn,io,nr,$o,or,Io,Xn,bo,gt,en,tn,Qn,rr;let t=Bu(e),n={};for(let[xe,yo]of Object.entries(t)){let lo=xe.replace(/\./g,"-");n[`--persona-${lo}`]=yo.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(L=n["--persona-semantic-colors-accent"])!=null?L:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(W=n["--persona-semantic-colors-background"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(H=n["--persona-semantic-colors-container"])!=null?H:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(R=n["--persona-semantic-colors-text"])!=null?R: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"]=(C=n["--persona-semantic-colors-text-inverse"])!=null?C:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(A=n["--persona-semantic-colors-divider"])!=null?A:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(S=n["--persona-components-voice-recording-indicator"])!=null?S:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(_=n["--persona-components-voice-recording-background"])!=null?_:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(V=n["--persona-components-voice-processing-icon"])!=null?V: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"]=(ue=n["--persona-components-approval-requested-border"])!=null?ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ce=n["--persona-components-approval-requested-text"])!=null?ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ke=n["--persona-components-approval-requested-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(ve=n["--persona-components-approval-approve-background"])!=null?ve:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(He=n["--persona-components-approval-deny-background"])!=null?He:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ie=n["--persona-components-attachment-image-border"])!=null?ie:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(be=n["--persona-semantic-typography-fontWeight"])!=null?be:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(he=n["--persona-semantic-typography-lineHeight"])!=null?he: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"]=(j=n["--persona-palette-radius-sm"])!=null?j:"0.125rem",n["--persona-radius-md"]=(se=n["--persona-palette-radius-md"])!=null?se:"0.375rem",n["--persona-radius-lg"]=(Re=n["--persona-palette-radius-lg"])!=null?Re:"0.5rem",n["--persona-radius-xl"]=(ne=n["--persona-palette-radius-xl"])!=null?ne:"0.75rem",n["--persona-radius-full"]=(Z=n["--persona-palette-radius-full"])!=null?Z:"9999px",n["--persona-launcher-radius"]=(at=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?at:"9999px",n["--persona-launcher-bg"]=(it=n["--persona-components-launcher-background"])!=null?it:n["--persona-primary"],n["--persona-launcher-fg"]=(Le=n["--persona-components-launcher-foreground"])!=null?Le:n["--persona-text-inverse"],n["--persona-launcher-border"]=(de=n["--persona-components-launcher-border"])!=null?de:n["--persona-border"],n["--persona-button-primary-bg"]=(Xe=n["--persona-components-button-primary-background"])!=null?Xe:n["--persona-primary"],n["--persona-button-primary-fg"]=(We=n["--persona-components-button-primary-foreground"])!=null?We:n["--persona-text-inverse"],n["--persona-button-radius"]=(me=(q=n["--persona-components-button-primary-borderRadius"])!=null?q:n["--persona-palette-radius-full"])!=null?me:"9999px",n["--persona-panel-radius"]=(Tt=(tt=n["--persona-components-panel-borderRadius"])!=null?tt:n["--persona-radius-xl"])!=null?Tt:"0.75rem",n["--persona-panel-border"]=(te=n["--persona-components-panel-border"])!=null?te:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Nn=(ze=n["--persona-components-panel-shadow"])!=null?ze:n["--persona-palette-shadows-xl"])!=null?Nn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Bt=n["--persona-components-launcher-shadow"])!=null?Bt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(ro=(an=n["--persona-components-input-borderRadius"])!=null?an:n["--persona-radius-lg"])!=null?ro:"0.5rem",n["--persona-message-user-radius"]=(D=(Eo=n["--persona-components-message-user-borderRadius"])!=null?Eo:n["--persona-radius-lg"])!=null?D:"0.5rem",n["--persona-message-assistant-radius"]=(De=(pe=n["--persona-components-message-assistant-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?De:"0.5rem",n["--persona-header-bg"]=(Ke=n["--persona-components-header-background"])!=null?Ke:n["--persona-surface"],n["--persona-header-border"]=(Ne=n["--persona-components-header-border"])!=null?Ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ve=n["--persona-components-header-iconBackground"])!=null?Ve: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"]=(It=n["--persona-components-header-titleForeground"])!=null?It:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(qt=n["--persona-components-header-subtitleForeground"])!=null?qt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Qt=n["--persona-components-header-actionIconForeground"])!=null?Qt: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=(yt=e.components)==null?void 0:yt.introCard;n["--persona-intro-card-bg"]=(st=n["--persona-components-introCard-background"])!=null?st:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ce=n["--persona-components-introCard-borderRadius"])!=null?Ce:"1rem",n["--persona-intro-card-padding"]=(le=n["--persona-components-introCard-padding"])!=null?le:"1.5rem",n["--persona-intro-card-shadow"]=(Zt=(Ze=r==null?void 0:r.shadow)!=null?Ze:n["--persona-components-introCard-shadow"])!=null?Zt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(jt=n["--persona-components-input-background"])!=null?jt:n["--persona-surface"],n["--persona-input-placeholder"]=(Rn=n["--persona-components-input-placeholder"])!=null?Rn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(xn=n["--persona-components-message-user-background"])!=null?xn:n["--persona-accent"],n["--persona-message-user-text"]=(ut=n["--persona-components-message-user-text"])!=null?ut: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"]=(Qe=n["--persona-components-message-assistant-background"])!=null?Qe:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ut=n["--persona-components-message-assistant-text"])!=null?Ut: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"]=(Sn=n["--persona-components-message-assistant-shadow"])!=null?Sn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(bn=(An=n["--persona-components-scrollToBottom-background"])!=null?An:n["--persona-button-primary-bg"])!=null?bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Ct=(Mo=n["--persona-components-scrollToBottom-foreground"])!=null?Mo:n["--persona-button-primary-fg"])!=null?Ct:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zn=n["--persona-components-scrollToBottom-border"])!=null?zn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(qn=n["--persona-components-scrollToBottom-size"])!=null?qn:"40px",n["--persona-scroll-to-bottom-radius"]=(vt=(ho=(No=n["--persona-components-scrollToBottom-borderRadius"])!=null?No:n["--persona-button-radius"])!=null?ho:n["--persona-radius-full"])!=null?vt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Lo=(yr=n["--persona-components-scrollToBottom-shadow"])!=null?yr:n["--persona-palette-shadows-sm"])!=null?Lo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(_n=n["--persona-components-scrollToBottom-gap"])!=null?_n:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Zo=(qr=n["--persona-components-scrollToBottom-fontSize"])!=null?qr: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"]=(St=n["--persona-components-toolBubble-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(jn=n["--persona-components-reasoningBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Kn=n["--persona-components-composer-shadow"])!=null?Kn:"none",n["--persona-md-inline-code-bg"]=(Pn=n["--persona-components-markdown-inlineCode-background"])!=null?Pn:n["--persona-container"],n["--persona-md-inline-code-color"]=(Lt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Lt:n["--persona-text"],n["--persona-md-link-color"]=(ao=(so=n["--persona-components-markdown-link-foreground"])!=null?so:n["--persona-accent"])!=null?ao:"#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"]=(Gn=n["--persona-components-markdown-codeBlock-background"])!=null?Gn: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"]=(Vo=n["--persona-components-markdown-codeBlock-textColor"])!=null?Vo:"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"]=(Yn=n["--persona-components-markdown-table-borderColor"])!=null?Yn:n["--persona-border"],n["--persona-md-hr-color"]=(Ht=n["--persona-components-markdown-hr-color"])!=null?Ht:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Wn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Wn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(io=n["--persona-components-markdown-blockquote-background"])!=null?io:"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"]=($o=n["--persona-components-collapsibleWidget-container"])!=null?$o:n["--persona-surface"],n["--cw-surface"]=(or=n["--persona-components-collapsibleWidget-surface"])!=null?or:n["--persona-surface"],n["--cw-border"]=(Io=n["--persona-components-collapsibleWidget-border"])!=null?Io:n["--persona-border"],n["--persona-message-border"]=(Xn=n["--persona-components-message-border"])!=null?Xn:n["--persona-border"];let u=e.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(n["--persona-icon-btn-bg"]=g.background),g.border&&(n["--persona-icon-btn-border"]=g.border),g.color&&(n["--persona-icon-btn-color"]=g.color),g.padding&&(n["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(n["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(n["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(n["--persona-icon-btn-active-border"]=g.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let xe=x.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(bo=n["--persona-dropdown-bg"])!=null?bo:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(gt=n["--persona-dropdown-border"])!=null?gt:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(en=n["--persona-dropdown-shadow"])!=null?en:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tn=n["--persona-dropdown-radius"])!=null?tn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Qn=n["--persona-dropdown-item-hover-bg"])!=null?Qn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let yo=(rr=ss(e,xe.toolbarBackground))!=null?rr:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=yo}}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"}}},Ou=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},cl=()=>{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"},vf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":cl()},xf=e=>vf(e),wf=e=>pn(e),Cf=e=>{var n;let t=pn(void 0,{validate:!1});return pn({...e,palette:{...t.palette,colors:{...yf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Va=e=>{let t=xf(e),n=Ou(e==null?void 0:e.theme),o=Ou(e==null?void 0:e.darkTheme);return t==="dark"?Cf(Us(n!=null?n:{},o!=null?o:{})):wf(n)},Sf=e=>Du(e),as=(e,t)=>{let n=Va(t),o=Sf(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},Fu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(cl())});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(cl());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 dl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Pr(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]:Pr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var pl=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?{...Mt,...n}:n!=null?n:Mt,this.theme=pn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?dl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?dl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):dl(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=Pr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:pn();this.config={...this.config,darkTheme:Pr(s,r,n)}}else this.config=Pr(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=Pr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:pn();this.config={...this.config,darkTheme:Pr(l,d,i)},o=!0}else this.config=Pr(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=pn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=pn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Mt},this.theme=pn(),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=pn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function ul(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 ml(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Af(e,t){return t==="rem"?e*16:e}function Tf(e,t){return t==="rem"?e/16:e}function zs(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 gl(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function fl(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),u=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(u)?Math.max(0,Math.min(255,Math.round(l?u/100*255:u))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function $a(e,t){let n=s=>{var l;let a=zs(s),i=a.startsWith("rgb")?(l=fl(a))!=null?l:"#000000":a,d=[1,3,5].map(u=>{let g=parseInt(i.slice(u,u+2),16)/255;return g<=.03928?g/12.92:Math.pow((g+.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 Nu(e){var f;let t=zs(e),n=t.startsWith("rgb")?(f=fl(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,u=d>.5?l/(2-a-i):l/(a+i),g;switch(a){case o:g=((r-s)/l+(r<s?6:0))/6;break;case r:g=((s-o)/l+2)/6;break;default:g=((o-r)/l+4)/6;break}return{h:g*360,s:u,l:d}}function _u(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let u=g=>{let f=Math.round((g+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${u(i)}${u(d)}${u(l)}`}function hl(e){let{h:t,s:n,l:o}=Nu(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]=_u(t,l,d)}return a}var is=["50","100","200","300","400","500","600","700","800","900","950"],bl=["primary","secondary","accent","gray","success","warning","error","info"];function kf(e,t){return`palette.colors.${e}.${t}`}function Vu(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.")?Vu(e,`theme.${o}`,n+1):"#cbd5e1"}function Ef(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 Oo=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ua=["primary","secondary","accent","gray"],Mf={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},za={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:Oo,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},qa={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:Oo,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"}]},ja={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:Oo,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Ka={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:Oo,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Ga={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:Oo,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"}]},Ya={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:Oo,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Xa={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:Oo,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"}]},Qa={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:Oo,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"}]},Ja={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:Oo,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},Wr=[za,qa,ja,Ka,Ga,Ya,Xa,Qa,Ja];function Za(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Lf(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 Lf(e,t,n,o){let r=t==="solid";if(o==="role-header")return If(e,r,n);if(o==="role-input")return Rf(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 If(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 Rf(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 Pf=/^palette\.colors\.(\w+)\.(\d+)$/;function yl(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(Pf);if(!r)return null;let s=r[1],a=Ua.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=Za(a,l,t);if(t.targets.every(f=>{var x;return String((x=e(f.path))!=null?x:"")===u[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var Wf={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"}]}]},Bf={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"}]},Hf={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"}}]},Df={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)"}]}]},Of={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"}]}]},Ff={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"}}]},Nf={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)"}]},_f={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"}]}]},cs=[Bf,Hf,Of,Df,Wf,Ff,Nf,_f];function Uu(){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:bl.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 zu={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"}}]},Vf=Uu(),$f=zu,Uf=[Uu(),zu],zf={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:mo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:_a},{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"}]}]},qf={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"}]}]},jf={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"}]}]},Kf={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"}]}]},Gf={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"}]}]},Yf={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"}}]},Xf={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"}}]},Qf={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"}}]},Jf={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"}}]},Zf={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"}]},ls=[{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"}],vl="0 5px 15px rgba(15, 23, 42, 0.08)",$u=[{value:vl,label:"Default"},...ls],eh={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:ls},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:ls},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:ls},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:ls},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:vl,options:$u},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:vl,options:$u},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:ls}]},qu=[zf,qf,jf,Kf,Gf,eh],ju=[Yf,Xf,Qf,Jf,Zf],Ku=[...qu,...ju],xl=1024*1024,th=["What can you help me with?","Tell me about your features","How does this work?"],qs={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 nh(e){return Number(e)*xl}function oh(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/xl)):String(t):"10"}function rh(e){var t;return(t=qs[String(e)])!=null?t:qs.images}function sh(e){let t=Array.isArray(e)?e:qs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(qs)){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 ah={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"}]},ih={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:th}]},lh={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:""}]},ch={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}]},dh={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"}]}]},ph={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"}]}]},uh={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:mo},{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"}]},mh={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:""}]},gh={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"}]},fh={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"}]},hh={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"}]},bh={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"}]},yh={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:""}]},vh={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)}]},xh={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*xl,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:oh,parseValue:nh},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:qs.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:sh,parseValue:rh}]},wh={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"}]}]},Ch={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},Sh={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},Ah={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},Th={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}]},ei=[{label:"Content",sections:[ah,ih]},{label:"Layout",sections:[lh,ch,dh,ph]},{label:"Widget",sections:[uh,mh,gh,fh,hh,bh]},{label:"Features",sections:[yh,vh,xh,wh,Ch]},{label:"Developer",collapsedByDefault:!0,sections:[Sh,Ah,Th]}],Gu=ei.flatMap(e=>e.sections),Yu={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"}]}]},Xu={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"}]},Qu={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"}]},Ju={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:za},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:qa},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:ja},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ka},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Ga},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Ya},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Xa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Qa},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Ja}]},Zu={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"}}]},em={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},kh=[Yu,Xu,Qu,Ju,Zu,em],wl=[{id:"style",label:"Style",sections:cs},{id:"design-system",label:"Design System",sections:Ku},{id:"configure",label:"Configure",sections:Gu}];function tm(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Eh(e,t,n){return{...e,id:`${n}-${e.id}`,path:tm(e.path,t)}}function Mh(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Lh(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=>Eh(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])=>[tm(d,t),l]))}))}}var nm=[{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"]}],js=[...nm];function Cl(e){return js.find(t=>t.id===e)}import{Marked as Ih}from"marked";var Rh=e=>{if(e)return e},Sl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Ih({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=Rh(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},ti=e=>e?Sl({markedOptions:e.options,renderer:e.renderer}):Sl(),uC=Sl();var Ks=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");import Ph from"dompurify";var Wh={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"]},Bh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Hh=()=>{let e=Ph(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:")&&!Bh.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Wh)},ni=e=>e===!1?null:typeof e=="function"?e:Hh();var Br="webmcp:",Al=new Map,om=e=>{var t;Al.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Al.set(n.name,o)}},Tl=e=>Al.get(im(e)),oi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},rm=null;function am(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}:${Dh(t.join(""))}`}function sm(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 Dh(e){let t=sm(e,0).toString(36),n=sm(e,2654435761).toString(36);return`${t}.${n}`}var ri=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 oi.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}om(n);let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Fh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let x=typeof document!="undefined"&&!!document.modelContext;return Ao(x?"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=im(t),a;try{a=await r.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return Ao(`Failed to read WebMCP registry: ${v}`)}om(a);let i=a.find(x=>x.name===s);if(!i)return Ao(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ao(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let d=Tl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let u=new AbortController,g=!1,f=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await r.executeTool(i,$h(n),{signal:u.signal});return Nh(x)}catch(x){if(g)return Ao(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return Ao(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(rm?await rm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){oi.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,oi.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:_h;try{return await n(t)}catch(r){return oi.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=>Oh(t,o))}},im=e=>e.startsWith(Br)?e.slice(Br.length):e,Gs=e=>e.startsWith(Br),Oh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Fh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Nh=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:Uh(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),_h=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Vh(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)},Ih=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Rh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ph=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Wh,STR as Bh,OBJ as Hh}from"partial-json";var nm=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ls=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)}},Dh=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`},om=e=>e.status==="complete"?Dh(e):e.status==="pending"?"Waiting":"",Fh=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 rm=e=>e.status==="complete"?Fh(e):"Using tool...",ni=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Gs=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 ni(t)},oi=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 ni(t)},Al=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Gs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ri=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ks(o,n.slice(s,a.index),[]),a[1]!==void 0?Ks(o,a[1],["bold"]):a[2]!==void 0?Ks(o,a[2],["italic"]):a[3]!==void 0&&Ks(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ks(o,n.slice(s),[]),o},Ks=(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})},Oh=()=>{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)},Vh=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)}},$h=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Uh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as zh,ARR as qh,OBJ as jh,STR as Kh}from"partial-json";var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Fo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var kl="ask_user_question",Ys=8,ds="data-persona-ask-sheet-for",Gh="Other",Yh="Other\u2026",cm="Type your own answer here",dm="Send",Xh="Next",Qh="Back",Jh="Submit all",Zh="Skip",eb=3,El="data-ask-current-index",Ml="data-ask-question-count",pm="data-ask-answers",Ll="data-ask-grouped",um="data-ask-layout",tb=e=>e.layout==="pills"?"pills":"rows",nb=e=>e.getAttribute(um)==="pills"?"pills":"rows",lm=!1,mm=e=>e.replace(/["\\]/g,"\\$&"),Hr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===kl,Il=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ps=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=zh(r,Kh|jh|qh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Xs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Ys&&!lm&&(lm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ys}.`)),t.slice(0,Ys)},ob=e=>{var t;return(t=Xs(e)[0])!=null?t:null},rb=(e,t)=>{var n;return(n=Xs(e)[t])!=null?n:null},sb=(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))},gm=(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},ab=(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=gm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ib=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},lb=(e,t,n,o)=>{var u,g,f;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<eb;m++)s.appendChild(ib(o));return s}if(d.forEach((m,x)=>{s.appendChild(ab(m,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Gh:Yh;if(o==="rows"){let x=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(u=t.freeTextPlaceholder)!=null?u:cm,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),v.appendChild(E),x.appendChild(v);let L=gm(o,a,d.length);L&&x.appendChild(L),s.appendChild(x)}else{let x=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:m,s.appendChild(x)}}return s},fm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:cm,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:dm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},cb=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:dm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},db=(e,t,n)=>{var l,u,g,f;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:Qh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:Zh,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?(g=n.submitAllLabel)!=null?g:Jh:(f=n.nextLabel)!=null?f:Xh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Dr=e=>{let t=e.getAttribute(pm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},hm=(e,t)=>{e.setAttribute(pm,JSON.stringify(t))},go=e=>{var n;let t=Number((n=e.getAttribute(El))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},pb=(e,t)=>{e.setAttribute(El,String(Math.max(0,Math.floor(t))))},us=e=>{var n;let t=Number((n=e.getAttribute(Ml))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},gr=e=>e.getAttribute(Ll)==="true",ub=(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},mb=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},si=(e,t)=>{let{payload:n}=ps(t),o=Xs(n),r=Dr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},bm=e=>{let t=Dr(e),n=go(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 g;let l=(g=d.getAttribute("data-option-label"))!=null?g:"",u=r.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},ym=e=>{if(!gr(e))return;let t=Dr(e),n=go(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}},Rl=(e,t,n)=>{let o=Il(n),r=nb(e),{payload:s,complete:a}=ps(t),i=gr(e),d=go(e),l=us(e),u=i?rb(s,d):ob(s),g=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let I=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=I,x.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=lb(u,o,a,r);v.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(fm(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!E?e.appendChild(cb(o)):(!g||i)&&E&&E.remove(),e.setAttribute("data-multi-select",g?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=db(d,l,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();bm(e),ym(e)},gb=(e,t,n)=>{let o=Il(t),r=tb(o),s=e.toolCall.id,a=Xs(n),i=Math.max(1,a.length),d=i>1,l=ub(e,a),u=d?mb(e,i):0,g=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ds,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Ml,String(i)),g.setAttribute(El,String(u)),g.setAttribute(Ll,d?"true":"false"),g.setAttribute(um,r),hm(g,l),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),sb(g,o);let f=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="",f.appendChild(m);let x=b("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),g.appendChild(f);let E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),g.appendChild(E),r!=="rows"&&g.appendChild(fm(o,r)),Rl(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},fb=(e,t,n)=>{let{payload:o}=ps(t),r=Math.max(1,Xs(o).length);r>us(e)&&(e.setAttribute(Ml,String(r)),r>1&&!gr(e)&&e.setAttribute(Ll,"true")),Rl(e,t,n)};var ai=(e,t,n)=>{if(!n||!Hr(e)||Il(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ds}]`).forEach(l=>{l.getAttribute(ds)!==r&&l.remove()});let a=n.querySelector(`[${ds}="${mm(r)}"]`);if(a){fb(a,e,t);return}let{payload:i}=ps(e),d=gb(e,t,i);n.appendChild(d)},ms=(e,t)=>{if(!e)return;let n=t?`[${ds}="${mm(t)}"]`:`[${ds}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Pl=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),fr=(e,t)=>{let n=Dr(e),o=go(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,hm(e,n),bm(e),ym(e)},ii=(e,t,n,o)=>{let r=us(e),s=Math.max(0,Math.min(r-1,o));pb(e,s),Rl(e,t,n)};var Yo="suggest_replies";var hb={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},vm={name:Yo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown \u2014 do not add further commentary after calling this tool; end your turn.`,parametersSchema:hb,origin:"sdk",annotations:{readOnlyHint:!0}},Wl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Bl=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Yo},bb=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},xm=e=>{var t;for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return null;if(!Bl(o))continue;let r=bb((t=o.toolCall)==null?void 0:t.args);return r.length>0?r:null}return null},wm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var yb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ys,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option \u2014 free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},vb={name:kl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make \u2014 a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:yb,origin:"sdk",annotations:{readOnlyHint:!0}},Hl=e=>{var o;let t=[],n=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(vb),wm(e)&&t.push(vm),t};import{parse as xb,STR as wb,OBJ as Cb}from"partial-json";var Cm=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),gs=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)}},Sb=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`},Sm=e=>e.status==="complete"?Sb(e):e.status==="pending"?"Waiting":"",Ab=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 Am=e=>e.status==="complete"?Ab(e):"Using tool...",li=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=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 li(t)},ci=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 li(t)},Dl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Js(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},di=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Qs(o,n.slice(s,a.index),[]),a[1]!==void 0?Qs(o,a[1],["bold"]):a[2]!==void 0?Qs(o,a[2],["italic"]):a[3]!==void 0&&Qs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Qs(o,n.slice(s),[]),o},Qs=(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()=>{}}},Wr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},am=()=>{var t;let e=Oh();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)}},im=()=>{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=Wh(n,Bh|Hh);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?nm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=nm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var lm=()=>{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 si=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 Nh="https://api.runtype.com/v1/dispatch",ai="https://api.runtype.com";function _h(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 Tl=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 Vh(e){switch(e){case"json":return im;case"regex-json":return am;case"xml":return lm;default:return sm}}var cm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function $h(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=cm(n);if(!cm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Wr(e);return Wr(t)!==null&&a===null?t:e}var Ys=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:Nh,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Vh(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 ti(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$/,""))||ai}/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$/,""))||ai}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),f=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Tl).map(H=>{var P,w,x;return{id:H.id,role:H.role,content:(x=(w=(P=H.contentParts)!=null?P:H.llmContent)!=null?w:H.rawContent)!=null?x:H.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?em(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===C,L=!1,I=null,R;for(let H=0;;H++){let w={...u,...m&&(L||!E)&&g?{clientTools:g}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),R=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),R.status===409&&H===0&&m){let x=await R.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=x!=null?x:{error:"Chat request failed"}}break}if(!R.ok){let H=I!=null?I:await R.json().catch(()=>({error:"Chat request failed"}));if(R.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(R.status===429){let w=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let P=new Error(H.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!R.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=C!=null?C:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(R.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$/,""))||ai}/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(/\/+$/,""))||ai}/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(Tl).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(Tl).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 Ht,sn,no,ko;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,f=D=>{let pe=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,De=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,je=D.tools?D.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...D,reasoning:pe,toolCall:De,tools:je}},u=D=>{if(D.role!=="assistant"||D.variant)return!0;let pe=Array.isArray(D.contentParts)&&D.contentParts.length>0,De=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||pe||De||!!D.stopReason},g=D=>{u(D)&&n({type:"message",message:f(D)})},m=null,C=null,v={current:null},E={current:null},L=!1,I=new Map,R=new Map,H=new Map,P=new Map,w={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(D,pe,De="")=>`${D}::${pe}::${De}`,S=(D,pe)=>`${D}::${pe}::`,T=(D,pe,De,je)=>{let Ne=k(D,pe,De),Ve=H.get(Ne);if(Ve)return Ve;let nt=De?`-${De}`:"",Rt={id:`nested-${D}-${pe}${nt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:je,parentToolId:D,parentStepId:pe}};return H.set(Ne,Rt),g(Rt),Rt},_=D=>{if(D==null)return null;try{return String(D)}catch{return null}},U=D=>{var pe,De,je,Ne,Ve;return _((Ve=(Ne=(je=(De=(pe=D.stepId)!=null?pe:D.step_id)!=null?De:D.step)!=null?je:D.parentId)!=null?Ne:D.flowStepId)!=null?Ve:D.flow_step_id)},G=D=>{var pe,De,je,Ne,Ve,nt,Rt;return _((Rt=(nt=(Ve=(Ne=(je=(De=(pe=D.callId)!=null?pe:D.call_id)!=null?De:D.requestId)!=null?je:D.request_id)!=null?Ne:D.toolCallId)!=null?Ve:D.tool_call_id)!=null?nt:D.stepId)!=null?Rt:D.step_id)},ge=o,ue=!1,ce=()=>{if(m)return m;let D;return!ue&&ge?(D=ge,ue=!0):ge&&E.current?D=`${ge}_${E.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(m),m},ke=(D,pe)=>{w.lastId=pe,D&&w.byStep.set(D,pe)},ve=(D,pe)=>{var Ve;let De=(Ve=D.reasoningId)!=null?Ve:D.id,je=U(D);if(De){let nt=String(De);return ke(je,nt),nt}if(je){let nt=w.byStep.get(je);if(nt)return w.lastId=nt,nt}if(w.lastId&&!pe)return w.lastId;if(!pe)return null;let Ne=`reason-${l()}`;return ke(je,Ne),Ne},He=D=>{let pe=I.get(D);if(pe)return pe;let De={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:D,status:"streaming",chunks:[]}};return I.set(D,De),g(De),De},Se=(D,pe)=>{x.lastId=pe,D&&x.byCall.set(D,pe)},ie=new Set,X=new Map,re=new Set,be=new Map,he=D=>{if(!D)return!1;let pe=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},j=(D,pe)=>{var Ve;let De=(Ve=D.toolId)!=null?Ve:D.id,je=G(D);if(De){let nt=String(De);return Se(je,nt),nt}if(je){let nt=x.byCall.get(je);if(nt)return x.lastId=nt,nt}if(x.lastId&&!pe)return x.lastId;if(!pe)return null;let Ne=`tool-${l()}`;return Se(je,Ne),Ne},se=D=>{let pe=R.get(D);if(pe)return pe;let De={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:D,status:"pending"}};return R.set(D,De),g(De),De},Ie=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let pe=Number(D);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let De=Date.parse(D);if(!Number.isNaN(De))return De}return Date.now()},ne=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Z=new Map,oe=new Map,at=new Map,it=new Map,Me=null,de=(D,pe,De)=>{var Rt;let je=at.get(D);je||(je=[],at.set(D,je));let Ne=0,Ve=je.length;for(;Ne<Ve;){let jt=Ne+Ve>>>1;je[jt].seq<pe?Ne=jt+1:Ve=jt}((Rt=je[Ne])==null?void 0:Rt.seq)===pe?je[Ne]={seq:pe,text:De}:je.splice(Ne,0,{seq:pe,text:De});let nt="";for(let jt=0;jt<je.length;jt++)nt+=je[jt].text;return nt},Xe=(D,pe)=>{let De=ne(pe),je=oe.get(D.id),Ne=$h(je,De);D.rawContent=Ne;let Ve=Z.get(D.id),nt=vt=>{var Ce;let rt=(Ce=D.content)!=null?Ce:"";vt.trim()!==""&&(rt.trim().length===0||vt.startsWith(rt)||vt.trimStart().startsWith(rt.trim()))&&(D.content=vt)},Rt=()=>{var vt;if(Ve){let rt=(vt=Ve.close)==null?void 0:vt.call(Ve);rt instanceof Promise&&rt.catch(()=>{})}Z.delete(D.id),oe.delete(D.id),D.streaming=!1,g(D)};if(!Ve){nt(De),Rt();return}let jt=Wr(Ne);if(jt!==null&&jt.trim()!==""){nt(jt),Rt();return}let Xt=vt=>{var le;let rt=typeof vt=="string"?vt:(le=vt==null?void 0:vt.text)!=null?le:null;if(rt!==null&&rt.trim()!=="")return rt;let Ce=Ve.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:De},K;try{K=Ve.processChunk(Ne)}catch{nt(De),Rt();return}if(K instanceof Promise){K.then(vt=>{nt(Xt(vt)),Rt()}).catch(()=>{nt(De),Rt()});return}nt(Xt(K)),Rt()},We=[],q=!1,me,et=()=>{q||(q=!0,queueMicrotask(()=>{q=!1,me()}))},Et=new si((D,pe)=>{We.push({payloadType:D,payload:pe}),et()}),ee=null,ze=new Map,Dn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(me=()=>{var D,pe,De,je,Ne,Ve,nt,Rt,jt,Xt,K,vt,rt,Ce,le,Ze,Jt,Kt,Ln,yn,ft,Mt,Je,zt,an,wn,Cn,bn,Eo,St,$n,Un,No,bo,xt,br,Mo,yr,Fn,Ur,Qo,_o,At,zn,qn,In,It,oo,ro,jn,Zo,Vo,er,Kn,Dt,Rn,so,tr,$o,nr,Lo,Gn,yo,ht,Qt,Zt,Yn,or,xe,ao,io,V,Io,Uo,zo,Ro,vo,Cs,Xn,Jn,xo,wo,vr,qo,Sn,Po,zr,xr,qr,xa,jr,wa,Kr,yt,Ss,lo,On,Ca,Sa,Gr,jo,As,rr,Ts,ks,Es,Ms,Nn,Yr,Wo,Bo,Ls,Aa,Is,Rs,wr,Ta,ka,Ea,Ma,nl,Cr,sr,La,Ps,ar,Ia,Ws,ir,Bs,Ra,Ko,Pa,lr,Ft,Xr,Jr,Hs;for(let co=0;co<We.length;co++){let Ke=We[co].payloadType,A=We[co].payload;if(Ke==="reason_start"){let $=(D=ve(A,!0))!=null?D:`reason-${l()}`,W=He($);W.reasoning=(pe=W.reasoning)!=null?pe:{id:$,status:"streaming",chunks:[]},W.reasoning.startedAt=(je=W.reasoning.startedAt)!=null?je:Ie((De=A.startedAt)!=null?De:A.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",g(W)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let $=(Ve=(Ne=ve(A,!1))!=null?Ne:ve(A,!0))!=null?Ve:`reason-${l()}`,W=He($);W.reasoning=(nt=W.reasoning)!=null?nt:{id:$,status:"streaming",chunks:[]},W.reasoning.startedAt=(jt=W.reasoning.startedAt)!=null?jt:Ie((Rt=A.startedAt)!=null?Rt:A.timestamp);let Q=(vt=(K=(Xt=A.reasoningText)!=null?Xt:A.text)!=null?K:A.delta)!=null?vt:"";if(Q&&A.hidden!==!0){let ae=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ae!==void 0){let Y=de($,ae,String(Q));W.reasoning.chunks=[Y]}else W.reasoning.chunks.push(String(Q))}if(W.reasoning.status=A.done?"complete":"streaming",A.done){W.reasoning.completedAt=Ie((rt=A.completedAt)!=null?rt:A.timestamp);let ae=(Ce=W.reasoning.startedAt)!=null?Ce:Date.now();W.reasoning.durationMs=Math.max(0,((le=W.reasoning.completedAt)!=null?le:Date.now())-ae)}W.streaming=W.reasoning.status!=="complete",g(W)}else if(Ke==="reason_complete"){let $=(Jt=(Ze=ve(A,!1))!=null?Ze:ve(A,!0))!=null?Jt:`reason-${l()}`,W=I.get($);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Ie((Kt=A.completedAt)!=null?Kt:A.timestamp);let ae=(Ln=W.reasoning.startedAt)!=null?Ln:Date.now();W.reasoning.durationMs=Math.max(0,((yn=W.reasoning.completedAt)!=null?yn:Date.now())-ae),W.streaming=!1,g(W)}let Q=U(A);Q&&w.byStep.delete(Q)}else if(Ke==="tool_start"){let $=(ft=j(A,!0))!=null?ft:`tool-${l()}`,W=(Mt=A.toolName)!=null?Mt:A.name;if(he(W)){ie.add($);continue}let Q=se($),ae=(Je=Q.toolCall)!=null?Je:{id:$,status:"pending"};ae.name=W!=null?W:ae.name,ae.status="running",A.args!==void 0?ae.args=A.args:A.parameters!==void 0&&(ae.args=A.parameters),ae.startedAt=(an=ae.startedAt)!=null?an:Ie((zt=A.startedAt)!=null?zt:A.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,Q.toolCall=ae,Q.streaming=!0;let Y=A.agentContext;(Y||A.executionId)&&(Q.agentMetadata={executionId:(wn=Y==null?void 0:Y.executionId)!=null?wn:A.executionId,iteration:(Cn=Y==null?void 0:Y.iteration)!=null?Cn:A.iteration}),g(Q)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let $=(Eo=(bn=j(A,!1))!=null?bn:j(A,!0))!=null?Eo:`tool-${l()}`;if(ie.has($))continue;let W=se($),Q=(St=W.toolCall)!=null?St:{id:$,status:"running"};Q.startedAt=(Un=Q.startedAt)!=null?Un:Ie(($n=A.startedAt)!=null?$n:A.timestamp);let ae=(xt=(bo=(No=A.text)!=null?No:A.delta)!=null?bo:A.message)!=null?xt:"";ae&&(Q.chunks=(br=Q.chunks)!=null?br:[],Q.chunks.push(String(ae))),Q.status="running",W.toolCall=Q,W.streaming=!0;let Y=A.agentContext;(Y||A.executionId)&&(W.agentMetadata=(Fn=W.agentMetadata)!=null?Fn:{executionId:(Mo=Y==null?void 0:Y.executionId)!=null?Mo:A.executionId,iteration:(yr=Y==null?void 0:Y.iteration)!=null?yr:A.iteration}),g(W)}else if(Ke==="tool_complete"){let $=(Qo=(Ur=j(A,!1))!=null?Ur:j(A,!0))!=null?Qo:`tool-${l()}`;if(ie.has($)){ie.delete($);continue}let W=se($),Q=(_o=W.toolCall)!=null?_o:{id:$,status:"running"};Q.status="complete",A.result!==void 0&&(Q.result=A.result),typeof A.duration=="number"&&(Q.duration=A.duration),Q.completedAt=Ie((At=A.completedAt)!=null?At:A.timestamp);let ae=(zn=A.duration)!=null?zn:A.executionTime;if(typeof ae=="number")Q.durationMs=ae;else{let Oe=(qn=Q.startedAt)!=null?qn:Date.now();Q.durationMs=Math.max(0,((In=Q.completedAt)!=null?In:Date.now())-Oe)}W.toolCall=Q,W.streaming=!1;let Y=A.agentContext;(Y||A.executionId)&&(W.agentMetadata=(ro=W.agentMetadata)!=null?ro:{executionId:(It=Y==null?void 0:Y.executionId)!=null?It:A.executionId,iteration:(oo=Y==null?void 0:Y.iteration)!=null?oo:A.iteration}),g(W);let Re=G(A);Re&&x.byCall.delete(Re)}else if(Ke==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let $=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,W=(jn=$!=null?$:A.toolId)!=null?jn:`local-${l()}`,Q=se(W),ae=A.toolName,Y=is(ae),Re=(Zo=Q.toolCall)!=null?Zo:{id:W,status:"pending"};Re.name=ae,Re.args=A.parameters,Re.status=Y?"running":"complete",Re.chunks=(Vo=Re.chunks)!=null?Vo:[],Re.startedAt=(Kn=Re.startedAt)!=null?Kn:Ie((er=A.startedAt)!=null?er:A.timestamp),Y?(Re.completedAt=void 0,Re.duration=void 0,Re.durationMs=void 0):Re.completedAt=(Dt=Re.completedAt)!=null?Dt:Re.startedAt,Q.toolCall=Re,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(so=A.executionId)!=null?so:(Rn=Q.agentMetadata)==null?void 0:Rn.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},g(Q)}else if(Ke==="text_start"){if((tr=A.toolContext)!=null&&tr.toolId)continue;let $=A.partId;if($!==void 0&&E.current!==null&&$!==E.current){let W=m;W&&(W.streaming=!1,g(W),Me=W,m=null,L=!0)}$!==void 0&&(E.current=$)}else if(Ke==="text_end"){if(($o=A.toolContext)!=null&&$o.toolId)continue;let $=m;$&&($.streaming=!1,g($),Me=$,m=null,L=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let $=A.stepType,W=A.executionType;if($==="tool"||W==="context")continue;let Q=A.toolContext;if(Q!=null&&Q.toolId){let Oe=String((Lo=(nr=A.id)!=null?nr:Q.stepId)!=null?Lo:`step-${l()}`),st=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Qe=`${Q.toolId}::${Oe}`,Bt=P.get(Qe);if(st!==""&&Bt!==void 0&&Bt!==""&&Bt!==st){let lt=H.get(k(Q.toolId,Oe,Bt));lt&&lt.streaming!==!1&&(lt.streaming=!1,g(lt))}st!==""&&P.set(Qe,st);let Vt=T(Q.toolId,Oe,st,Q.executionId),Nt=(Qt=(ht=(yo=(Gn=A.text)!=null?Gn:A.delta)!=null?yo:A.content)!=null?ht:A.chunk)!=null?Qt:"";Nt&&(Vt.content+=String(Nt),Vt.streaming=!0,g(Vt)),A.isComplete&&(Vt.streaming=!1,g(Vt));continue}let ae=A.partId;if(ae!==void 0&&E.current!==null&&ae!==E.current){let Oe=m;Oe&&(Oe.streaming=!1,g(Oe),Me=Oe,m=null,L=!0)}ae!==void 0&&(E.current=ae);let Y=ae!==void 0&&(Zt=it.get(ae))!=null?Zt:ce();ae!==void 0&&(Y.partId||(Y.partId=ae),it.set(ae,Y));let Re=(ao=(xe=(or=(Yn=A.text)!=null?Yn:A.delta)!=null?or:A.content)!=null?xe:A.chunk)!=null?ao:"";if(Re){let Oe=typeof A.seq=="number"?A.seq:void 0,st=ae!=null?ae:Y.id,Qe=Oe!==void 0?de(st,Oe,String(Re)):((io=oe.get(Y.id))!=null?io:"")+Re;Y.rawContent=Qe,Z.has(Y.id)||Z.set(Y.id,this.createStreamParser());let Bt=Z.get(Y.id),Vt=Qe.trim().startsWith("{")||Qe.trim().startsWith("[");if(Vt&&oe.set(Y.id,Qe),Bt.__isPlainTextParser===!0){Y.content=Oe!==void 0?Qe:Y.content+Re,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,g(Y);continue}let lt=Bt.processChunk(Qe);if(lt instanceof Promise)lt.then(Tt=>{var An;let $e=typeof Tt=="string"?Tt:(An=Tt==null?void 0:Tt.text)!=null?An:null;if($e!==null&&$e.trim()!=="")Y.content=$e,g(Y);else if(!Vt&&!Qe.trim().startsWith("<")){let mn=m,$t=mn&&mn.id===Y.id?mn:Y;$t.id===Y.id&&($t.content=Oe!==void 0?Qe:$t.content+Re,oe.delete($t.id),Z.delete($t.id),$t.rawContent=void 0,g($t))}}).catch(()=>{Y.content=Oe!==void 0?Qe:Y.content+Re,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,g(Y)});else{let Tt=typeof lt=="string"?lt:(V=lt==null?void 0:lt.text)!=null?V:null;Tt!==null&&Tt.trim()!==""?(Y.content=Tt,g(Y)):!Vt&&!Qe.trim().startsWith("<")&&(Y.content=Oe!==void 0?Qe:Y.content+Re,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,g(Y))}}if(A.isComplete){let Oe=(Uo=(Io=A.result)==null?void 0:Io.response)!=null?Uo:Y.content;if(Oe){let st=oe.get(Y.id),Qe=st!=null?st:ne(Oe);Y.rawContent=Qe;let Bt=Z.get(Y.id),Vt=null,Nt=!1;if(Bt&&(Vt=Bt.getExtractedText(),Vt===null&&(Vt=Wr(Qe)),Vt===null)){let lt=Bt.processChunk(Qe);lt instanceof Promise?(Nt=!0,lt.then(Tt=>{var An;let $e=typeof Tt=="string"?Tt:(An=Tt==null?void 0:Tt.text)!=null?An:null;if($e!==null){let mn=m;mn&&mn.id===Y.id&&(mn.content=$e,mn.streaming=!1,Z.delete(mn.id),oe.delete(mn.id),g(mn))}})):Vt=typeof lt=="string"?lt:(zo=lt==null?void 0:lt.text)!=null?zo:null}if(!Nt){Vt!==null&&Vt.trim()!==""?Y.content=Vt:oe.has(Y.id)||(Y.content=ne(Oe));let lt=Z.get(Y.id);if(lt){let Tt=(Ro=lt.close)==null?void 0:Ro.call(lt);Tt instanceof Promise&&Tt.catch(()=>{}),Z.delete(Y.id)}oe.delete(Y.id),Y.streaming=!1,g(Y)}}}}else if(Ke==="step_complete"){let $=A.stepType,W=A.executionType;if($==="tool"||W==="context")continue;let Q=A.toolContext;if(Q!=null&&Q.toolId){let Oe=String((Cs=(vo=A.id)!=null?vo:Q.stepId)!=null?Cs:"");if(Oe){let st=S(Q.toolId,Oe);for(let[Qe,Bt]of H)Qe.startsWith(st)&&Bt.streaming!==!1&&(Bt.streaming=!1,g(Bt));P.delete(`${Q.toolId}::${Oe}`)}continue}let ae=A.stopReason;if(L){if(m!==null){let Qe=m;ae&&(Qe.stopReason=ae),Z.delete(Qe.id),oe.delete(Qe.id),Qe.streaming!==!1&&(Qe.streaming=!1,g(Qe))}let Oe=(Xn=A.result)==null?void 0:Xn.response,st=Me;st&&(ae&&(st.stopReason=ae),Oe!=null?Xe(st,Oe):(Z.delete(st.id),oe.delete(st.id))),Me=null;continue}let Y=(Jn=A.result)==null?void 0:Jn.response,Re=ce();if(ae&&(Re.stopReason=ae),Y!=null){let Oe=Z.get(Re.id),st=!1,Qe=!1;if(Oe){let Bt=Oe.getExtractedText(),Vt=oe.get(Re.id),Nt=Vt!=null?Vt:ne(Y);if(Re.rawContent=Nt,Bt!==null&&Bt.trim()!=="")Re.content=Bt,st=!0;else{let lt=Wr(Nt);if(lt!==null)Re.content=lt,st=!0;else{let Tt=Oe.processChunk(Nt);if(Tt instanceof Promise)Qe=!0,Tt.then($e=>{var mn;let An=typeof $e=="string"?$e:(mn=$e==null?void 0:$e.text)!=null?mn:null;if(An!==null&&An.trim()!==""){let $t=m;$t&&$t.id===Re.id&&($t.content=An,$t.streaming=!1,Z.delete($t.id),oe.delete($t.id),g($t))}else{let $t=Oe.getExtractedText(),Co=m;Co&&Co.id===Re.id&&($t!==null&&$t.trim()!==""?Co.content=$t:oe.has(Co.id)||(Co.content=ne(Y)),Co.streaming=!1,Z.delete(Co.id),oe.delete(Co.id),g(Co))}});else{let $e=typeof Tt=="string"?Tt:(xo=Tt==null?void 0:Tt.text)!=null?xo:null;if($e!==null&&$e.trim()!=="")Re.content=$e,st=!0;else{let An=Oe.getExtractedText();An!==null&&An.trim()!==""&&(Re.content=An,st=!0)}}}}}if(!Qe){if(!Re.rawContent){let Bt=oe.get(Re.id);Re.rawContent=Bt!=null?Bt:ne(Y)}if(!st&&!oe.has(Re.id)&&(Re.content=ne(Y)),Oe){let Bt=(wo=Oe.close)==null?void 0:wo.call(Oe);Bt instanceof Promise&&Bt.catch(()=>{})}Z.delete(Re.id),oe.delete(Re.id),Re.streaming=!1,g(Re)}}else Z.delete(Re.id),oe.delete(Re.id),Re.streaming=!1,g(Re)}else if(Ke==="flow_complete"){let $=(vr=A.result)==null?void 0:vr.response;if(L){if(m!==null){let W=m;Z.delete(W.id),oe.delete(W.id),W.streaming!==!1&&(W.streaming=!1,g(W))}}else if($!=null){let W=ce(),Q=oe.get(W.id),ae=Q!=null?Q:ne($);W.rawContent=ae;let Y=ne($),Re=Z.get(W.id);if(Re){let Qe=Wr(ae);if(Qe!==null)Y=Qe;else{let Bt=Re.processChunk(ae);Bt instanceof Promise&&Bt.then(Nt=>{var Tt;let lt=typeof Nt=="string"?Nt:(Tt=Nt==null?void 0:Nt.text)!=null?Tt:null;lt!==null&&(W.content=lt,W.streaming=!1,g(W))});let Vt=Re.getExtractedText();Vt!==null&&(Y=Vt)}}Z.delete(W.id),oe.delete(W.id);let Oe=Y!==W.content,st=W.streaming!==!1;Oe&&(W.content=Y),W.streaming=!1,(Oe||st)&&g(W)}else if(m!==null){let W=m;Z.delete(W.id),oe.delete(W.id),W.streaming!==!1&&(W.streaming=!1,g(W))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")ee={executionId:A.executionId,agentId:(qo=A.agentId)!=null?qo:"virtual",agentName:(Sn=A.agentName)!=null?Sn:"",status:"running",currentIteration:0,maxTurns:(Po=A.maxTurns)!=null?Po:1,startedAt:Ie(A.startedAt)};else if(Ke==="agent_iteration_start"){if(ee&&(ee.currentIteration=A.iteration),Dn==="separate"&&A.iteration>1){let $=m;$&&($.streaming=!1,g($),ze.set(A.iteration-1,$),m=null)}}else if(Ke==="agent_turn_start")C=null;else if(Ke==="agent_turn_delta"){if(A.contentType==="text"){let $=ce();$.content+=(zr=A.delta)!=null?zr:"",$.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ee==null?void 0:ee.agentName},C=$,g($)}else if(A.contentType==="thinking"){let $=(xr=A.turnId)!=null?xr:`agent-think-${A.iteration}`,W=He($);W.reasoning=(qr=W.reasoning)!=null?qr:{id:$,status:"streaming",chunks:[]},W.reasoning.chunks.push((xa=A.delta)!=null?xa:""),W.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(W)}else if(A.contentType==="tool_input"){let $=(jr=A.toolCallId)!=null?jr:x.lastId;if($){let W=R.get($);W!=null&&W.toolCall&&(W.toolCall.chunks=(wa=W.toolCall.chunks)!=null?wa:[],W.toolCall.chunks.push((Kr=A.delta)!=null?Kr:""),g(W))}}}else if(Ke==="agent_turn_complete"){let $=A.turnId;if($){let ae=I.get($);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=Ie(A.completedAt);let Y=(yt=ae.reasoning.startedAt)!=null?yt:Date.now();ae.reasoning.durationMs=Math.max(0,((Ss=ae.reasoning.completedAt)!=null?Ss:Date.now())-Y),ae.streaming=!1,g(ae)}}let W=A.stopReason,Q=m!=null?m:C;if(W&&Q!==null){let ae=A.turnId;(!ae||((lo=Q.agentMetadata)==null?void 0:lo.turnId)===ae)&&(Q.stopReason=W,g(Q))}}else if(Ke==="agent_tool_start"){m&&(m.streaming=!1,g(m),m=null);let $=(On=A.toolCallId)!=null?On:`agent-tool-${l()}`;Se(G(A),$);let W=se($),Q=(Ca=W.toolCall)!=null?Ca:{id:$,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};Q.name=(Gr=(Sa=A.toolName)!=null?Sa:A.name)!=null?Gr:Q.name,Q.status="running",A.parameters!==void 0&&(Q.args=A.parameters),Q.startedAt=Ie((jo=A.startedAt)!=null?jo:A.timestamp),W.toolCall=Q,W.streaming=!0,W.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(W)}else if(Ke==="agent_tool_delta"){let $=(As=A.toolCallId)!=null?As:x.lastId;if($){let W=(rr=R.get($))!=null?rr:se($);W.toolCall&&(W.toolCall.chunks=(Ts=W.toolCall.chunks)!=null?Ts:[],W.toolCall.chunks.push((ks=A.delta)!=null?ks:""),W.toolCall.status="running",W.streaming=!0,g(W))}}else if(Ke==="agent_tool_complete"){let $=(Es=A.toolCallId)!=null?Es:x.lastId;if($){let W=(Ms=R.get($))!=null?Ms:se($);if(W.toolCall){W.toolCall.status="complete",A.result!==void 0&&(W.toolCall.result=A.result),typeof A.executionTime=="number"&&(W.toolCall.durationMs=A.executionTime),W.toolCall.completedAt=Ie((Nn=A.completedAt)!=null?Nn:A.timestamp),W.streaming=!1,g(W);let Q=G(A);Q&&x.byCall.delete(Q)}}}else if(Ke==="agent_media"){let $=Array.isArray(A.media)?A.media:[],W=[];for(let Q of $){if(!Q||typeof Q!="object")continue;let ae=Q,Y=typeof ae.type=="string"?ae.type:void 0,Re=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Oe=null,st="";if(Y==="media"){let Qe=typeof ae.data=="string"?ae.data:void 0;if(!Qe)continue;st=Re.length>0?Re:"application/octet-stream",Oe=`data:${st};base64,${Qe}`}else if(Y==="image-url"){let Qe=typeof ae.url=="string"?ae.url:void 0;if(!Qe)continue;st=Re,Oe=Qe}else if(Y==="file-url"){let Qe=typeof ae.url=="string"?ae.url:void 0;if(!Qe)continue;st=Re,Oe=Qe}else continue;if(Oe)if(Y==="image-url"||st.startsWith("image/"))W.push({type:"image",image:Oe,...st?{mimeType:st}:{}});else if(st.startsWith("audio/"))W.push({type:"audio",audio:Oe,mimeType:st});else if(st.startsWith("video/"))W.push({type:"video",video:Oe,mimeType:st});else{let Qe=st||"application/octet-stream";W.push({type:"file",data:Oe,mimeType:Qe,filename:_h(Qe)})}}if(W.length>0){let Q=l(),ae=A.toolCallId,Re={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${Q}`:String(Q)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Q,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(Re);let Oe=m;Oe&&(Oe.streaming=!1,g(Oe)),m=null,v.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let $=`agent-reflection-${A.executionId}-${A.iteration}`,W={id:$,role:"assistant",content:(Yr=A.reflection)!=null?Yr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(Wo=A.reflection)!=null?Wo:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(W)}else if(Ke==="agent_complete"){ee&&(ee.status=A.success?"complete":"error",ee.completedAt=Ie(A.completedAt),ee.stopReason=A.stopReason);let $=m;$&&($.streaming=!1,g($)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let $=typeof A.error=="string"?A.error:(Ls=(Bo=A.error)==null?void 0:Bo.message)!=null?Ls:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let $=(Aa=A.approvalId)!=null?Aa:`approval-${l()}`,W={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Is=ee==null?void 0:ee.agentId)!=null?Is:"virtual",executionId:(wr=(Rs=A.executionId)!=null?Rs:ee==null?void 0:ee.executionId)!=null?wr:"",toolName:(Ta=A.toolName)!=null?Ta:"",toolType:A.toolType,description:(Ea=A.description)!=null?Ea:`Execute ${(ka=A.toolName)!=null?ka:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(W)}else if(Ke==="step_await"&&A.awaitReason==="approval_required"){let $=(Ma=A.approvalId)!=null?Ma:`approval-${l()}`,W={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(nl=ee==null?void 0:ee.agentId)!=null?nl:"virtual",executionId:(sr=(Cr=A.executionId)!=null?Cr:ee==null?void 0:ee.executionId)!=null?sr:"",toolName:(La=A.toolName)!=null?La:"",toolType:A.toolType,description:(ar=A.description)!=null?ar:`Execute ${(Ps=A.toolName)!=null?Ps:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(W)}else if(Ke==="agent_approval_complete"){let $=A.approvalId;if($){let Q={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(Ia=A.decision)!=null?Ia:"approved",agentId:(Ws=ee==null?void 0:ee.agentId)!=null?Ws:"virtual",executionId:(Bs=(ir=A.executionId)!=null?ir:ee==null?void 0:ee.executionId)!=null?Bs:"",toolName:(Ra=A.toolName)!=null?Ra:"",description:(Ko=A.description)!=null?Ko:"",resolvedAt:Date.now()}};g(Q)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let $=A.artifactType,W=String(A.id),Q=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:W,artifactType:$,title:Q,component:typeof A.component=="string"?A.component:void 0}),be.set(W,{markdown:"",title:Q}),!re.has(W)){re.add(W);let ae={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Q,artifactType:$,status:"streaming"}})};X.set(W,ae),g(ae)}}else if(Ke==="artifact_delta"){let $=String(A.id),W=typeof A.delta=="string"?A.delta:String((Pa=A.delta)!=null?Pa:"");n({type:"artifact_delta",id:$,artDelta:W});let Q=be.get($);Q&&(Q.markdown+=W)}else if(Ke==="artifact_update"){let $=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:$,component:typeof A.component=="string"?A.component:void 0})}else if(Ke==="artifact_complete"){let $=String(A.id);n({type:"artifact_complete",id:$});let W=X.get($);if(W){W.streaming=!1;try{let Q=JSON.parse((lr=W.rawContent)!=null?lr:"{}");if(Q.props){Q.props.status="complete";let ae=be.get($);ae!=null&&ae.markdown&&(Q.props.markdown=ae.markdown)}W.rawContent=JSON.stringify(Q)}catch{}be.delete($),g(W),X.delete($)}}}else if(Ke==="transcript_insert"){let $=A.message;if(!$||typeof $!="object")continue;let W=String((Ft=$.id)!=null?Ft:`msg-${l()}`),Q=$.role,Y={id:W,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(g(Y),Y.rawContent)try{let Re=JSON.parse(Y.rawContent),Oe=(Xr=Re==null?void 0:Re.props)==null?void 0:Xr.artifactId;typeof Oe=="string"&&re.add(Oe)}catch{}m=null,v.current=null,Z.delete(W),oe.delete(W)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let $=null;if(A.error instanceof Error)$=A.error;else if(Ke==="dispatch_error"){let W=(Jr=A.message)!=null?Jr:A.error;W!=null&&W!==""&&($=new Error(String(W)))}else if(Ke==="step_error"||Ke==="flow_error"){let W=A.error;typeof W=="string"&&W!==""?$=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&($=new Error(String((Hs=W.message)!=null?Hs:W)))}else Ke==="error"&&A.error!=null&&A.error!==""&&($=new Error(String(A.error)));if($){n({type:"error",error:$});let W=m;W&&W.streaming&&(W.streaming=!1,g(W)),n({type:"status",status:"idle"})}}}}}We.length=0};;){let{done:D,value:pe}=await r.read();if(D)break;a+=s.decode(pe,{stream:!0});let De=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Or=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},km=()=>{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)}},Em=()=>{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=xb(n,wb|Cb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mm=()=>{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 pi=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 kb="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function Eb(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 Ol=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 Mb(e){switch(e){case"json":return Em;case"regex-json":return km;case"xml":return Mm;default:return Tm}}var Lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lb(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=Lm(n);if(!Lm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Or(e);return Or(t)!==null&&a===null?t:e}var Zs=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:kb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Mb(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 ri(t.webmcp):null}updateConfig(t){this.config=t}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$/,""))||ui}/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$/,""))||ui}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,g={sessionId:d.sessionId,messages:t.messages.filter(Ol).map(H=>{var R,w,C;return{id:H.id,role:H.role,content:(C=(w=(R=H.contentParts)!=null?R:H.llmContent)!=null?w:H.rawContent)!=null?C:H.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),x=m?am(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===x,L=!1,I=null,W;for(let H=0;;H++){let w={...g,...m&&(L||!E)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),W=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),W.status===409&&H===0&&m){let C=await W.json().catch(()=>null);if((C==null?void 0:C.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=C!=null?C:{error:"Chat request failed"}}break}if(!W.ok){let H=I!=null?I:await W.json().catch(()=>({error:"Chat request failed"}));if(W.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(W.status===429){let w=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let R=new Error(H.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!W.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(W.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Ol).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...Hl(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(t){var s,a;let o={messages:t.slice().filter(Ol).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=[...Hl(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let d=i;return o.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=o.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=g,r(g),g},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Bt,an,ro,Eo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=D=>{let pe=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,De=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,Ke=D.tools?D.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...D,reasoning:pe,toolCall:De,tools:Ke}},g=D=>{if(D.role!=="assistant"||D.variant)return!0;let pe=Array.isArray(D.contentParts)&&D.contentParts.length>0,De=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||pe||De||!!D.stopReason},f=D=>{g(D)&&n({type:"message",message:u(D)})},m=null,x=null,v={current:null},E={current:null},L=!1,I=new Map,W=new Map,H=new Map,R=new Map,w={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},k=(D,pe,De="")=>`${D}::${pe}::${De}`,A=(D,pe)=>`${D}::${pe}::`,S=(D,pe,De,Ke)=>{let Ne=k(D,pe,De),Ve=H.get(Ne);if(Ve)return Ve;let ot=De?`-${De}`:"",It={id:`nested-${D}-${pe}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ke,parentToolId:D,parentStepId:pe}};return H.set(Ne,It),f(It),It},_=D=>{if(D==null)return null;try{return String(D)}catch{return null}},V=D=>{var pe,De,Ke,Ne,Ve;return _((Ve=(Ne=(Ke=(De=(pe=D.stepId)!=null?pe:D.step_id)!=null?De:D.step)!=null?Ke:D.parentId)!=null?Ne:D.flowStepId)!=null?Ve:D.flow_step_id)},K=D=>{var pe,De,Ke,Ne,Ve,ot,It;return _((It=(ot=(Ve=(Ne=(Ke=(De=(pe=D.callId)!=null?pe:D.call_id)!=null?De:D.requestId)!=null?Ke:D.request_id)!=null?Ne:D.toolCallId)!=null?Ve:D.tool_call_id)!=null?ot:D.stepId)!=null?It:D.step_id)},fe=o,ue=!1,ce=()=>{if(m)return m;let D;return!ue&&fe?(D=fe,ue=!0):fe&&E.current?D=`${fe}_${E.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},ke=(D,pe)=>{w.lastId=pe,D&&w.byStep.set(D,pe)},ve=(D,pe)=>{var Ve;let De=(Ve=D.reasoningId)!=null?Ve:D.id,Ke=V(D);if(De){let ot=String(De);return ke(Ke,ot),ot}if(Ke){let ot=w.byStep.get(Ke);if(ot)return w.lastId=ot,ot}if(w.lastId&&!pe)return w.lastId;if(!pe)return null;let Ne=`reason-${l()}`;return ke(Ke,Ne),Ne},He=D=>{let pe=I.get(D);if(pe)return pe;let De={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:D,status:"streaming",chunks:[]}};return I.set(D,De),f(De),De},Se=(D,pe)=>{C.lastId=pe,D&&C.byCall.set(D,pe)},ie=new Set,X=new Map,re=new Set,be=new Map,he=D=>{if(!D)return!1;let pe=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},j=(D,pe)=>{var Ve;let De=(Ve=D.toolId)!=null?Ve:D.id,Ke=K(D);if(De){let ot=String(De);return Se(Ke,ot),ot}if(Ke){let ot=C.byCall.get(Ke);if(ot)return C.lastId=ot,ot}if(C.lastId&&!pe)return C.lastId;if(!pe)return null;let Ne=`tool-${l()}`;return Se(Ke,Ne),Ne},se=D=>{let pe=W.get(D);if(pe)return pe;let De={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:D,status:"pending"}};return W.set(D,De),f(De),De},Re=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let pe=Number(D);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let De=Date.parse(D);if(!Number.isNaN(De))return De}return Date.now()},ne=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Z=new Map,oe=new Map,at=new Map,it=new Map,Le=null,de=(D,pe,De)=>{var It;let Ke=at.get(D);Ke||(Ke=[],at.set(D,Ke));let Ne=0,Ve=Ke.length;for(;Ne<Ve;){let qt=Ne+Ve>>>1;Ke[qt].seq<pe?Ne=qt+1:Ve=qt}((It=Ke[Ne])==null?void 0:It.seq)===pe?Ke[Ne]={seq:pe,text:De}:Ke.splice(Ne,0,{seq:pe,text:De});let ot="";for(let qt=0;qt<Ke.length;qt++)ot+=Ke[qt].text;return ot},Xe=(D,pe)=>{let De=ne(pe),Ke=oe.get(D.id),Ne=Lb(Ke,De);D.rawContent=Ne;let Ve=Z.get(D.id),ot=yt=>{var Ce;let st=(Ce=D.content)!=null?Ce:"";yt.trim()!==""&&(st.trim().length===0||yt.startsWith(st)||yt.trimStart().startsWith(st.trim()))&&(D.content=yt)},It=()=>{var yt;if(Ve){let st=(yt=Ve.close)==null?void 0:yt.call(Ve);st instanceof Promise&&st.catch(()=>{})}Z.delete(D.id),oe.delete(D.id),D.streaming=!1,f(D)};if(!Ve){ot(De),It();return}let qt=Or(Ne);if(qt!==null&&qt.trim()!==""){ot(qt),It();return}let Qt=yt=>{var le;let st=typeof yt=="string"?yt:(le=yt==null?void 0:yt.text)!=null?le:null;if(st!==null&&st.trim()!=="")return st;let Ce=Ve.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:De},G;try{G=Ve.processChunk(Ne)}catch{ot(De),It();return}if(G instanceof Promise){G.then(yt=>{ot(Qt(yt)),It()}).catch(()=>{ot(De),It()});return}ot(Qt(G)),It()},We=[],q=!1,me,tt=()=>{q||(q=!0,queueMicrotask(()=>{q=!1,me()}))},Tt=new pi((D,pe)=>{We.push({payloadType:D,payload:pe}),tt()}),te=null,ze=new Map,Nn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(me=()=>{var D,pe,De,Ke,Ne,Ve,ot,It,qt,Qt,G,yt,st,Ce,le,Ze,Zt,jt,Rn,xn,ut,kt,Qe,Ut,ln,Sn,An,bn,Mo,Ct,zn,qn,No,ho,vt,yr,Lo,vr,_n,qr,Zo,_o,St,jn,Kn,Pn,Lt,so,ao,Gn,er,Vo,tr,Yn,Ht,Wn,io,nr,$o,or,Io,Xn,bo,gt,en,tn,Qn,rr,xe,yo,lo,$,jr,Ro,Uo,zo,Po,vo,As,Jn,Zn,xo,wo,xr,qo,Tn,Wo,Kr,wr,Gr,Aa,Yr,Ta,Xr,bt,Ts,co,Vn,ka,Ea,Qr,jo,ks,sr,Es,Ms,Ls,Is,$n,Jr,Bo,Ho,Rs,Ma,Ps,Ws,Cr,La,Ia,Ra,Pa,rl,Sr,ar,Wa,Bs,ir,Ba,Hs,lr,Ds,Ha,Ko,Da,cr,Dt,Zr,es;for(let Ar=0;Ar<We.length;Ar++){let $e=We[Ar].payloadType,T=We[Ar].payload;if($e==="reason_start"){let U=(D=ve(T,!0))!=null?D:`reason-${l()}`,P=He(U);P.reasoning=(pe=P.reasoning)!=null?pe:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(Ke=P.reasoning.startedAt)!=null?Ke:Re((De=T.startedAt)!=null?De:T.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",f(P)}else if($e==="reason_delta"||$e==="reason_chunk"){let U=(Ve=(Ne=ve(T,!1))!=null?Ne:ve(T,!0))!=null?Ve:`reason-${l()}`,P=He(U);P.reasoning=(ot=P.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(qt=P.reasoning.startedAt)!=null?qt:Re((It=T.startedAt)!=null?It:T.timestamp);let J=(yt=(G=(Qt=T.reasoningText)!=null?Qt:T.text)!=null?G:T.delta)!=null?yt:"";if(J&&T.hidden!==!0){let ae=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ae!==void 0){let Y=de(U,ae,String(J));P.reasoning.chunks=[Y]}else P.reasoning.chunks.push(String(J))}if(P.reasoning.status=T.done?"complete":"streaming",T.done){P.reasoning.completedAt=Re((st=T.completedAt)!=null?st:T.timestamp);let ae=(Ce=P.reasoning.startedAt)!=null?Ce:Date.now();P.reasoning.durationMs=Math.max(0,((le=P.reasoning.completedAt)!=null?le:Date.now())-ae)}P.streaming=P.reasoning.status!=="complete",f(P)}else if($e==="reason_complete"){let U=(Zt=(Ze=ve(T,!1))!=null?Ze:ve(T,!0))!=null?Zt:`reason-${l()}`,P=I.get(U);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=Re((jt=T.completedAt)!=null?jt:T.timestamp);let ae=(Rn=P.reasoning.startedAt)!=null?Rn:Date.now();P.reasoning.durationMs=Math.max(0,((xn=P.reasoning.completedAt)!=null?xn:Date.now())-ae),P.streaming=!1,f(P)}let J=V(T);J&&w.byStep.delete(J)}else if($e==="tool_start"){let U=(ut=j(T,!0))!=null?ut:`tool-${l()}`,P=(kt=T.toolName)!=null?kt:T.name;if(he(P)){ie.add(U);continue}let J=se(U),ae=(Qe=J.toolCall)!=null?Qe:{id:U,status:"pending"};ae.name=P!=null?P:ae.name,ae.status="running",T.args!==void 0?ae.args=T.args:T.parameters!==void 0&&(ae.args=T.parameters),ae.startedAt=(ln=ae.startedAt)!=null?ln:Re((Ut=T.startedAt)!=null?Ut:T.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,J.toolCall=ae,J.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(J.agentMetadata={executionId:(Sn=Y==null?void 0:Y.executionId)!=null?Sn:T.executionId,iteration:(An=Y==null?void 0:Y.iteration)!=null?An:T.iteration}),f(J)}else if($e==="tool_chunk"||$e==="tool_delta"){let U=(Mo=(bn=j(T,!1))!=null?bn:j(T,!0))!=null?Mo:`tool-${l()}`;if(ie.has(U))continue;let P=se(U),J=(Ct=P.toolCall)!=null?Ct:{id:U,status:"running"};J.startedAt=(qn=J.startedAt)!=null?qn:Re((zn=T.startedAt)!=null?zn:T.timestamp);let ae=(vt=(ho=(No=T.text)!=null?No:T.delta)!=null?ho:T.message)!=null?vt:"";ae&&(J.chunks=(yr=J.chunks)!=null?yr:[],J.chunks.push(String(ae))),J.status="running",P.toolCall=J,P.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(_n=P.agentMetadata)!=null?_n:{executionId:(Lo=Y==null?void 0:Y.executionId)!=null?Lo:T.executionId,iteration:(vr=Y==null?void 0:Y.iteration)!=null?vr:T.iteration}),f(P)}else if($e==="tool_complete"){let U=(Zo=(qr=j(T,!1))!=null?qr:j(T,!0))!=null?Zo:`tool-${l()}`;if(ie.has(U)){ie.delete(U);continue}let P=se(U),J=(_o=P.toolCall)!=null?_o:{id:U,status:"running"};J.status="complete",T.result!==void 0&&(J.result=T.result),typeof T.duration=="number"&&(J.duration=T.duration),J.completedAt=Re((St=T.completedAt)!=null?St:T.timestamp);let ae=(jn=T.duration)!=null?jn:T.executionTime;if(typeof ae=="number")J.durationMs=ae;else{let Fe=(Kn=J.startedAt)!=null?Kn:Date.now();J.durationMs=Math.max(0,((Pn=J.completedAt)!=null?Pn:Date.now())-Fe)}P.toolCall=J,P.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(ao=P.agentMetadata)!=null?ao:{executionId:(Lt=Y==null?void 0:Y.executionId)!=null?Lt:T.executionId,iteration:(so=Y==null?void 0:Y.iteration)!=null?so:T.iteration}),f(P);let Me=K(T);Me&&C.byCall.delete(Me)}else if($e==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,P=(Gn=U!=null?U:T.toolId)!=null?Gn:`local-${l()}`,J=se(P),ae=T.toolName,Y=Gs(ae),Me=(er=J.toolCall)!=null?er:{id:P,status:"pending"};Me.name=ae,Me.args=T.parameters,Me.status=Y?"running":"complete",Me.chunks=(Vo=Me.chunks)!=null?Vo:[],Me.startedAt=(Yn=Me.startedAt)!=null?Yn:Re((tr=T.startedAt)!=null?tr:T.timestamp),Y?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Ht=Me.completedAt)!=null?Ht:Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(io=T.executionId)!=null?io:(Wn=J.agentMetadata)==null?void 0:Wn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(J)}else if($e==="text_start"){if((nr=T.toolContext)!=null&&nr.toolId)continue;let U=T.partId;if(U!==void 0&&E.current!==null&&U!==E.current){let P=m;P&&(P.streaming=!1,f(P),Le=P,m=null,L=!0)}U!==void 0&&(E.current=U)}else if($e==="text_end"){if(($o=T.toolContext)!=null&&$o.toolId)continue;let U=m;U&&(U.streaming=!1,f(U),Le=U,m=null,L=!0)}else if($e==="step_chunk"||$e==="step_delta"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((Io=(or=T.id)!=null?or:J.stepId)!=null?Io:`step-${l()}`),lt=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Je=`${J.toolId}::${Fe}`,Wt=R.get(Je);if(lt!==""&&Wt!==void 0&&Wt!==""&&Wt!==lt){let rt=H.get(k(J.toolId,Fe,Wt));rt&&rt.streaming!==!1&&(rt.streaming=!1,f(rt))}lt!==""&&R.set(Je,lt);let _t=S(J.toolId,Fe,lt,J.executionId),un=(en=(gt=(bo=(Xn=T.text)!=null?Xn:T.delta)!=null?bo:T.content)!=null?gt:T.chunk)!=null?en:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),T.isComplete&&(_t.streaming=!1,f(_t));continue}let ae=T.partId;if(ae!==void 0&&E.current!==null&&ae!==E.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),Le=Fe,m=null,L=!0)}ae!==void 0&&(E.current=ae);let Y=ae!==void 0&&(tn=it.get(ae))!=null?tn:ce();ae!==void 0&&(Y.partId||(Y.partId=ae),it.set(ae,Y));let Me=(yo=(xe=(rr=(Qn=T.text)!=null?Qn:T.delta)!=null?rr:T.content)!=null?xe:T.chunk)!=null?yo:"";if(Me){let Fe=typeof T.seq=="number"?T.seq:void 0,lt=ae!=null?ae:Y.id,Je=Fe!==void 0?de(lt,Fe,String(Me)):((lo=oe.get(Y.id))!=null?lo:"")+Me;Y.rawContent=Je,Z.has(Y.id)||Z.set(Y.id,this.createStreamParser());let Wt=Z.get(Y.id),_t=Je.trim().startsWith("{")||Je.trim().startsWith("[");if(_t&&oe.set(Y.id,Je),Wt.__isPlainTextParser===!0){Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y);continue}let rt=Wt.processChunk(Je);if(rt instanceof Promise)rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null&&Jt.trim()!=="")Y.content=Jt,f(Y);else if(!_t&&!Je.trim().startsWith("<")){let wn=m,Gt=wn&&wn.id===Y.id?wn:Y;Gt.id===Y.id&&(Gt.content=Fe!==void 0?Je:Gt.content+Me,oe.delete(Gt.id),Z.delete(Gt.id),Gt.rawContent=void 0,f(Gt))}}).catch(()=>{Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y)});else{let ft=typeof rt=="string"?rt:($=rt==null?void 0:rt.text)!=null?$:null;ft!==null&&ft.trim()!==""?(Y.content=ft,f(Y)):!_t&&!Je.trim().startsWith("<")&&(Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y))}}if(T.isComplete){let Fe=(Ro=(jr=T.result)==null?void 0:jr.response)!=null?Ro:Y.content;if(Fe){let lt=oe.get(Y.id),Je=lt!=null?lt:ne(Fe);Y.rawContent=Je;let Wt=Z.get(Y.id),_t=null,un=!1;if(Wt&&(_t=Wt.getExtractedText(),_t===null&&(_t=Or(Je)),_t===null)){let rt=Wt.processChunk(Je);rt instanceof Promise?(un=!0,rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null){let wn=m;wn&&wn.id===Y.id&&(wn.content=Jt,wn.streaming=!1,Z.delete(wn.id),oe.delete(wn.id),f(wn))}})):_t=typeof rt=="string"?rt:(Uo=rt==null?void 0:rt.text)!=null?Uo:null}if(!un){_t!==null&&_t.trim()!==""?Y.content=_t:oe.has(Y.id)||(Y.content=ne(Fe));let rt=Z.get(Y.id);if(rt){let ft=(zo=rt.close)==null?void 0:zo.call(rt);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(Y.id)}oe.delete(Y.id),Y.streaming=!1,f(Y)}}}}else if($e==="step_complete"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((vo=(Po=T.id)!=null?Po:J.stepId)!=null?vo:"");if(Fe){let lt=A(J.toolId,Fe);for(let[Je,Wt]of H)Je.startsWith(lt)&&Wt.streaming!==!1&&(Wt.streaming=!1,f(Wt));R.delete(`${J.toolId}::${Fe}`)}continue}let ae=T.stopReason;if(L){if(m!==null){let Je=m;ae&&(Je.stopReason=ae),Z.delete(Je.id),oe.delete(Je.id),Je.streaming!==!1&&(Je.streaming=!1,f(Je))}let Fe=(As=T.result)==null?void 0:As.response,lt=Le;lt&&(ae&&(lt.stopReason=ae),Fe!=null?Xe(lt,Fe):(Z.delete(lt.id),oe.delete(lt.id))),Le=null;continue}let Y=(Jn=T.result)==null?void 0:Jn.response,Me=ce();if(ae&&(Me.stopReason=ae),Y!=null){let Fe=Z.get(Me.id),lt=!1,Je=!1;if(Fe){let Wt=Fe.getExtractedText(),_t=oe.get(Me.id),un=_t!=null?_t:ne(Y);if(Me.rawContent=un,Wt!==null&&Wt.trim()!=="")Me.content=Wt,lt=!0;else{let rt=Or(un);if(rt!==null)Me.content=rt,lt=!0;else{let ft=Fe.processChunk(un);if(ft instanceof Promise)Je=!0,ft.then(Jt=>{var wn;let je=typeof Jt=="string"?Jt:(wn=Jt==null?void 0:Jt.text)!=null?wn:null;if(je!==null&&je.trim()!==""){let Gt=m;Gt&&Gt.id===Me.id&&(Gt.content=je,Gt.streaming=!1,Z.delete(Gt.id),oe.delete(Gt.id),f(Gt))}else{let Gt=Fe.getExtractedText(),yn=m;yn&&yn.id===Me.id&&(Gt!==null&&Gt.trim()!==""?yn.content=Gt:oe.has(yn.id)||(yn.content=ne(Y)),yn.streaming=!1,Z.delete(yn.id),oe.delete(yn.id),f(yn))}});else{let Jt=typeof ft=="string"?ft:(Zn=ft==null?void 0:ft.text)!=null?Zn:null;if(Jt!==null&&Jt.trim()!=="")Me.content=Jt,lt=!0;else{let je=Fe.getExtractedText();je!==null&&je.trim()!==""&&(Me.content=je,lt=!0)}}}}}if(!Je){if(!Me.rawContent){let Wt=oe.get(Me.id);Me.rawContent=Wt!=null?Wt:ne(Y)}if(!lt&&!oe.has(Me.id)&&(Me.content=ne(Y)),Fe){let Wt=(xo=Fe.close)==null?void 0:xo.call(Fe);Wt instanceof Promise&&Wt.catch(()=>{})}Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}}else Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}else if($e==="flow_complete"){let U=(wo=T.result)==null?void 0:wo.response;if(L){if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}}else if(U!=null){let P=ce(),J=oe.get(P.id),ae=J!=null?J:ne(U);P.rawContent=ae;let Y=ne(U),Me=Z.get(P.id);if(Me){let Je=Or(ae);if(Je!==null)Y=Je;else{let Wt=Me.processChunk(ae);Wt instanceof Promise&&Wt.then(un=>{var ft;let rt=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;rt!==null&&(P.content=rt,P.streaming=!1,f(P))});let _t=Me.getExtractedText();_t!==null&&(Y=_t)}}Z.delete(P.id),oe.delete(P.id);let Fe=Y!==P.content,lt=P.streaming!==!1;Fe&&(P.content=Y),P.streaming=!1,(Fe||lt)&&f(P)}else if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}n({type:"status",status:"idle"})}else if($e==="agent_start")te={executionId:T.executionId,agentId:(xr=T.agentId)!=null?xr:"virtual",agentName:(qo=T.agentName)!=null?qo:"",status:"running",currentIteration:0,maxTurns:(Tn=T.maxTurns)!=null?Tn:1,startedAt:Re(T.startedAt)};else if($e==="agent_iteration_start"){if(te&&(te.currentIteration=T.iteration),Nn==="separate"&&T.iteration>1){let U=m;U&&(U.streaming=!1,f(U),ze.set(T.iteration-1,U),m=null)}}else if($e==="agent_turn_start")x=null;else if($e==="agent_turn_delta"){if(T.contentType==="text"){let U=ce();U.content+=(Wo=T.delta)!=null?Wo:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:te==null?void 0:te.agentName},x=U,f(U)}else if(T.contentType==="thinking"){let U=(Kr=T.turnId)!=null?Kr:`agent-think-${T.iteration}`,P=He(U);P.reasoning=(wr=P.reasoning)!=null?wr:{id:U,status:"streaming",chunks:[]},P.reasoning.chunks.push((Gr=T.delta)!=null?Gr:""),P.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},f(P)}else if(T.contentType==="tool_input"){let U=(Aa=T.toolCallId)!=null?Aa:C.lastId;if(U){let P=W.get(U);P!=null&&P.toolCall&&(P.toolCall.chunks=(Yr=P.toolCall.chunks)!=null?Yr:[],P.toolCall.chunks.push((Ta=T.delta)!=null?Ta:""),f(P))}}}else if($e==="agent_turn_complete"){let U=T.turnId;if(U){let ae=I.get(U);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=Re(T.completedAt);let Y=(Xr=ae.reasoning.startedAt)!=null?Xr:Date.now();ae.reasoning.durationMs=Math.max(0,((bt=ae.reasoning.completedAt)!=null?bt:Date.now())-Y),ae.streaming=!1,f(ae)}}let P=T.stopReason,J=m!=null?m:x;if(P&&J!==null){let ae=T.turnId;(!ae||((Ts=J.agentMetadata)==null?void 0:Ts.turnId)===ae)&&(J.stopReason=P,f(J))}}else if($e==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let U=(co=T.toolCallId)!=null?co:`agent-tool-${l()}`;Se(K(T),U);let P=se(U),J=(Vn=P.toolCall)!=null?Vn:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(Ea=(ka=T.toolName)!=null?ka:T.name)!=null?Ea:J.name,J.status="running",T.parameters!==void 0&&(J.args=T.parameters),J.startedAt=Re((Qr=T.startedAt)!=null?Qr:T.timestamp),P.toolCall=J,P.streaming=!0,P.agentMetadata={executionId:T.executionId,iteration:T.iteration},f(P)}else if($e==="agent_tool_delta"){let U=(jo=T.toolCallId)!=null?jo:C.lastId;if(U){let P=(ks=W.get(U))!=null?ks:se(U);P.toolCall&&(P.toolCall.chunks=(sr=P.toolCall.chunks)!=null?sr:[],P.toolCall.chunks.push((Es=T.delta)!=null?Es:""),P.toolCall.status="running",P.streaming=!0,f(P))}}else if($e==="agent_tool_complete"){let U=(Ms=T.toolCallId)!=null?Ms:C.lastId;if(U){let P=(Ls=W.get(U))!=null?Ls:se(U);if(P.toolCall){P.toolCall.status="complete",T.result!==void 0&&(P.toolCall.result=T.result),typeof T.executionTime=="number"&&(P.toolCall.durationMs=T.executionTime),P.toolCall.completedAt=Re((Is=T.completedAt)!=null?Is:T.timestamp),P.streaming=!1,f(P);let J=K(T);J&&C.byCall.delete(J)}}}else if($e==="agent_media"){let U=Array.isArray(T.media)?T.media:[],P=[];for(let J of U){if(!J||typeof J!="object")continue;let ae=J,Y=typeof ae.type=="string"?ae.type:void 0,Me=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Fe=null,lt="";if(Y==="media"){let Je=typeof ae.data=="string"?ae.data:void 0;if(!Je)continue;lt=Me.length>0?Me:"application/octet-stream",Fe=`data:${lt};base64,${Je}`}else if(Y==="image-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else if(Y==="file-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else continue;if(Fe)if(Y==="image-url"||lt.startsWith("image/"))P.push({type:"image",image:Fe,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))P.push({type:"audio",audio:Fe,mimeType:lt});else if(lt.startsWith("video/"))P.push({type:"video",video:Fe,mimeType:lt});else{let Je=lt||"application/octet-stream";P.push({type:"file",data:Fe,mimeType:Je,filename:Eb(Je)})}}if(P.length>0){let J=l(),ae=T.toolCallId,Me={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(Me);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,v.current=null}}else if($e!=="agent_iteration_complete"){if($e==="agent_reflection"||$e==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,P={id:U,role:"assistant",content:($n=T.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Jr=T.reflection)!=null?Jr:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(P)}else if($e==="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,f(U)),n({type:"status",status:"idle"})}else if($e==="agent_error"){let U=typeof T.error=="string"?T.error:(Ho=(Bo=T.error)==null?void 0:Bo.message)!=null?Ho:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if($e!=="agent_ping"){if($e==="agent_approval_start"){let U=(Rs=T.approvalId)!=null?Rs:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Ma=te==null?void 0:te.agentId)!=null?Ma:"virtual",executionId:(Ws=(Ps=T.executionId)!=null?Ps:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Cr=T.toolName)!=null?Cr:"",toolType:T.toolType,description:(Ia=T.description)!=null?Ia:`Execute ${(La=T.toolName)!=null?La:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="step_await"&&T.awaitReason==="approval_required"){let U=(Ra=T.approvalId)!=null?Ra:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Pa=te==null?void 0:te.agentId)!=null?Pa:"virtual",executionId:(Sr=(rl=T.executionId)!=null?rl:te==null?void 0:te.executionId)!=null?Sr:"",toolName:(ar=T.toolName)!=null?ar:"",toolType:T.toolType,description:(Bs=T.description)!=null?Bs:`Execute ${(Wa=T.toolName)!=null?Wa:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="agent_approval_complete"){let U=T.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ir=T.decision)!=null?ir:"approved",agentId:(Ba=te==null?void 0:te.agentId)!=null?Ba:"virtual",executionId:(lr=(Hs=T.executionId)!=null?Hs:te==null?void 0:te.executionId)!=null?lr:"",toolName:(Ds=T.toolName)!=null?Ds:"",description:(Ha=T.description)!=null?Ha:"",resolvedAt:Date.now()}};f(J)}}else if($e==="artifact_start"||$e==="artifact_delta"||$e==="artifact_update"||$e==="artifact_complete"){if($e==="artifact_start"){let U=T.artifactType,P=String(T.id),J=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:P,artifactType:U,title:J,component:typeof T.component=="string"?T.component:void 0}),be.set(P,{markdown:"",title:J}),!re.has(P)){re.add(P);let ae={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:J,artifactType:U,status:"streaming"}})};X.set(P,ae),f(ae)}}else if($e==="artifact_delta"){let U=String(T.id),P=typeof T.delta=="string"?T.delta:String((Ko=T.delta)!=null?Ko:"");n({type:"artifact_delta",id:U,artDelta:P});let J=be.get(U);J&&(J.markdown+=P)}else if($e==="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($e==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let P=X.get(U);if(P){P.streaming=!1;try{let J=JSON.parse((Da=P.rawContent)!=null?Da:"{}");if(J.props){J.props.status="complete";let ae=be.get(U);ae!=null&&ae.markdown&&(J.props.markdown=ae.markdown)}P.rawContent=JSON.stringify(J)}catch{}be.delete(U),f(P),X.delete(U)}}}else if($e==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let P=String((cr=U.id)!=null?cr:`msg-${l()}`),J=U.role,Y={id:P,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(Y),Y.rawContent)try{let Me=JSON.parse(Y.rawContent),Fe=(Dt=Me==null?void 0:Me.props)==null?void 0:Dt.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}m=null,v.current=null,Z.delete(P),oe.delete(P)}else if($e==="error"||$e==="step_error"||$e==="dispatch_error"||$e==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if($e==="dispatch_error"){let P=(Zr=T.message)!=null?Zr:T.error;P!=null&&P!==""&&(U=new Error(String(P)))}else if($e==="step_error"||$e==="flow_error"){let P=T.error;typeof P=="string"&&P!==""?U=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(U=new Error(String((es=P.message)!=null?es:P)))}else $e==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let P=m;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}}}}We.length=0};;){let{done:D,value:pe}=await r.read();if(D)break;a+=s.decode(pe,{stream:!0});let De=a.split(`
10
10
 
11
- `);a=(sn=De.pop())!=null?sn:"";for(let je of De){let Ne=je.split(`
12
- `),Ve="message",nt="";for(let Xt of Ne)Xt.startsWith("event:")?Ve=Xt.replace("event:","").trim():Xt.startsWith("data:")&&(nt+=Xt.replace("data:","").trim());if(!nt)continue;let Rt;try{Rt=JSON.parse(nt)}catch(Xt){n({type:"error",error:Xt instanceof Error?Xt:new Error("Failed to parse chat stream payload")});continue}let jt=Ve!=="message"?Ve:(no=Rt.type)!=null?no:"message";if((ko=this.onSSEEvent)==null||ko.call(this,jt,Rt),this.parseSSEEvent){v.current=m;let Xt=await this.handleCustomSSEEvent(Rt,n,v,g,l,E);if(v.current&&v.current!==m&&(m=v.current),Xt)continue}Et.push(jt,Rt),me()}}Et.flushPending(),me(),Et.destroy()}};function ii(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var li="[Image]";function kl(e){return{type:"text",text:e}}var dm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Uh=["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"],Yo=[...dm,...Uh];function zh(e){return dm.includes(e)||e.startsWith("image/")}function ci(e){return zh(e.type)}async function pm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ci(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 um(e,t=Yo,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 qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function mm(e,t){let n=qh(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 di=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 pi=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 Js=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 pi;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=L=>{C||(C=!0,clearTimeout(E),m(new Error(L)))},E=setTimeout(()=>v("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),g())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+f+"."+u)},{once:!0}),this.ws.addEventListener("close",L=>{if(!L.wasClean&&!C){let I=L.code!==1006?` (code ${L.code})`:"";v("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 di(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 Br=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 Qs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Js(e.runtype);case"browser":if(!Br.isSupported())throw new Error("Browser speech recognition not supported");return new Br(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function fm(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Qs({type:"runtype",runtype:e.runtype});if(Br.isSupported())return Qs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function El(e){try{return fm(e),!0}catch{return!1}}function gm(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=De.pop())!=null?an:"";for(let Ke of De){let Ne=Ke.split(`
12
+ `),Ve="message",ot="";for(let Qt of Ne)Qt.startsWith("event:")?Ve=Qt.replace("event:","").trim():Qt.startsWith("data:")&&(ot+=Qt.replace("data:","").trim());if(!ot)continue;let It;try{It=JSON.parse(ot)}catch(Qt){n({type:"error",error:Qt instanceof Error?Qt:new Error("Failed to parse chat stream payload")});continue}let qt=Ve!=="message"?Ve:(ro=It.type)!=null?ro:"message";if((Eo=this.onSSEEvent)==null||Eo.call(this,qt,It),this.parseSSEEvent){v.current=m;let Qt=await this.handleCustomSSEEvent(It,n,v,f,l,E);if(v.current&&v.current!==m&&(m=v.current),Qt)continue}Tt.push(qt,It),me()}}Tt.flushPending(),me(),Tt.destroy()}};function mi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var gi="[Image]";function Fl(e){return{type:"text",text:e}}var Im=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ib=["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"],Xo=[...Im,...Ib];function Rb(e){return Im.includes(e)||e.startsWith("image/")}function fi(e){return Rb(e.type)}async function Rm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;fi(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 Pm(e,t=Xo,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 Pb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wm(e,t){let n=Pb(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 hi=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 bi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var ta=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 bi;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${a}/ws/agents/${i}/voice?token=...`,g=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let x=!1,v=L=>{x||(x=!0,clearTimeout(E),m(new Error(L)))},E=setTimeout(()=>v("WebSocket connection timed out."+g),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+g)},{once:!0}),this.ws.addEventListener("close",L=>{if(!L.wasClean&&!x){let I=L.code!==1006?` (code ${L.code})`:"";v("WebSocket connection failed"+I+"."+g)}},{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 hi(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",g=new Blob(this.audioChunks,{type:u});await this.sendAudio(g),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 Fr=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 na(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ta(e.runtype);case"browser":if(!Fr.isSupported())throw new Error("Browser speech recognition not supported");return new Fr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bm(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return na({type:"runtype",runtype:e.runtype});if(Fr.isSupported())return na({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Nl(e){try{return Bm(e),!0}catch{return!1}}var Wb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Bb(e,t){return Wb.some(n=>e[n]!==t[n])}function Hm(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 Zs=e=>({isError:!0,content:[{type:"text",text:e}]}),hm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ui=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)&&is(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 Ys(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 El((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=Qs(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 E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(L=>L.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var 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 Ys(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"?ii():n==="assistant"?Xs():`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"?ii():r==="assistant"?Xs():`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=ii(),s=Xs(),a={id:r,role:"user",content:o||li,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let E=gm(C,this.config.errorMessage);if(E){let L={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(L)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(C instanceof Error?(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=Xs();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=gm(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 E=null;if(v instanceof Response){if(!v.ok){let L=await v.json().catch(()=>null);throw new Error((g=L==null?void 0:L.error)!=null?g:`Approval request failed: ${v.status}`)}E=v.body}else v instanceof ReadableStream&&(E=v);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(C=(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,E,L,I,R,H,P;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 k=typeof((E=x[0])==null?void 0:E.question)=="string"?x[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(L=this.abortController)==null||L.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([x,k])=>`${x}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((x,k)=>{let S=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!S)return;let T=w[S],_=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:_||"*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((R=x==null?void 0:x.error)!=null?R:`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||(P=(H=this.callbacks).onError)==null||P.call(H,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 H,P,w,x,k,S,T;let g=(H=u.toolCall)==null?void 0:H.name,m=(P=u.toolCall)==null?void 0:P.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),E=new AbortController;this.webMcpResolveControllers.add(E),r.push(E);let L=(x=(w=u.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?x:g,I=this.client.executeWebMcpToolCall(g,(k=u.toolCall)==null?void 0:k.args,E.signal),R;if(!I)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await I}catch(_){let U=_ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"));return U||(T=(S=this.callbacks).onError)==null||T.call(S,_ instanceof Error?_:new Error(String(_))),this.markWebMcpToolComplete(u,Zs(U?"Aborted by cancel()":hm(_)),v),this.webMcpInflightKeys.delete(C),null}return E.signal.aborted?(this.markWebMcpToolComplete(u,Zs("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:L,output:R,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,Zs("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,E,L,I,R,H,P,w,x,k;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){(L=(E=this.callbacks).onError)==null||L.call(E,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let S=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))return;this.webMcpInflightKeys.add(S);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(S)}catch(T){(R=(I=this.callbacks).onError)==null||R.call(I,T instanceof Error?T:new Error(String(T)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(H=t.toolCall)==null?void 0:H.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,Zs("Aborted by cancel()"),a);return}let T=(w=(P=t.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?w:o;u="resume",await this.resumeWithToolOutput(n,T,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,g)},signal:d})}catch(S){let T=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(u==="execute"||T||d.aborted)&&this.markWebMcpToolComplete(t,Zs(T||d.aborted?"Aborted by cancel()":hm(S)),a),T||(k=(x=this.callbacks).onError)==null||k.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,E,L,I,R,H,P,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,k=n.approval;a.approval={...x,...k,executionId:k.executionId||x.executionId,toolName:k.toolName||x.toolName,description:k.description||x.description,toolType:(u=k.toolType)!=null?u:x.toolType,reason:(g=k.reason)!=null?g:x.reason,parameters:(m=k.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=(E=n.toolCall)==null?void 0:E.id;if(i&&is(i)&&d&&l&&((L=n.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let x=`${d}:${l}`,k=this.webMcpInflightKeys.has(x),S=this.webMcpResolvedKeys.has(x),T=(I=r.toolCall)==null?void 0:I.name,_=((R=r.agentMetadata)==null?void 0:R.executionId)===d&&((H=r.toolCall)==null?void 0:H.id)===l&&T!==void 0&&is(T)&&((P=r.toolCall)==null?void 0:P.status)==="complete";(k||S||_)&&(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},Fo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as jh,ArrowDown as Kh,ArrowUp as Gh,ArrowUpRight as Yh,Bot as Xh,ChevronDown as Jh,ChevronUp as Qh,ChevronRight as Zh,ChevronLeft as eb,Check as tb,Clipboard as nb,ClipboardCopy as ob,Copy as rb,File as sb,FileCode as ab,FileSpreadsheet as ib,FileText as lb,ImagePlus as cb,Loader as db,LoaderCircle as pb,Mic as ub,Paperclip as mb,RefreshCw as fb,Search as gb,Send as hb,ShieldAlert as bb,ShieldCheck as yb,ShieldX as vb,Square as xb,ThumbsDown as wb,ThumbsUp as Cb,Upload as Sb,Volume2 as Ab,X as Tb,User as kb,Mail as Eb,Phone as Mb,Calendar as Lb,Clock as Ib,Building as Rb,MapPin as Pb,Lock as Wb,Key as Bb,CreditCard as Hb,AtSign as Db,Hash as Fb,Globe as Ob,Link as Nb,CircleCheck as _b,CircleX as Vb,TriangleAlert as $b,Info as Ub,Ban as zb,Shield as qb,ArrowLeft as jb,ArrowRight as Kb,ExternalLink as Gb,Ellipsis as Yb,EllipsisVertical as Xb,Menu as Jb,House as Qb,Plus as Zb,Minus as ey,Pencil as ty,Trash as ny,Trash2 as oy,Save as ry,Download as sy,Share as ay,Funnel as iy,Settings as ly,RotateCw as cy,Maximize as dy,Minimize as py,ShoppingCart as uy,ShoppingBag as my,Package as fy,Truck as gy,Tag as hy,Gift as by,Receipt as yy,Wallet as vy,Store as xy,DollarSign as wy,Percent as Cy,Play as Sy,Pause as Ay,VolumeX as Ty,Camera as ky,Image as Ey,Film as My,Headphones as Ly,MessageCircle as Iy,MessageSquare as Ry,Bell as Py,Heart as Wy,Star as By,Eye as Hy,EyeOff as Dy,Bookmark as Fy,CalendarDays as Oy,History as Ny,Timer as _y,Folder as Vy,FolderOpen as $y,Files as Uy,Sparkles as zy,Zap as qy,Sun as jy,Moon as Ky,Flag as Gy,Monitor as Yy,Smartphone as Xy}from"lucide";var Jy={activity:jh,"arrow-down":Kh,"arrow-up":Gh,"arrow-up-right":Yh,bot:Xh,"chevron-down":Jh,"chevron-up":Qh,"chevron-right":Zh,"chevron-left":eb,check:tb,clipboard:nb,"clipboard-copy":ob,copy:rb,file:sb,"file-code":ab,"file-spreadsheet":ib,"file-text":lb,"image-plus":cb,loader:db,"loader-circle":pb,mic:ub,paperclip:mb,"refresh-cw":fb,search:gb,send:hb,"shield-alert":bb,"shield-check":yb,"shield-x":vb,square:xb,"thumbs-down":wb,"thumbs-up":Cb,upload:Sb,"volume-2":Ab,x:Tb,user:kb,mail:Eb,phone:Mb,calendar:Lb,clock:Ib,building:Rb,"map-pin":Pb,lock:Wb,key:Bb,"credit-card":Hb,"at-sign":Db,hash:Fb,globe:Ob,link:Nb,"circle-check":_b,"circle-x":Vb,"triangle-alert":$b,info:Ub,ban:zb,shield:qb,"arrow-left":jb,"arrow-right":Kb,"external-link":Gb,ellipsis:Yb,"ellipsis-vertical":Xb,menu:Jb,house:Qb,plus:Zb,minus:ey,pencil:ty,trash:ny,"trash-2":oy,save:ry,download:sy,share:ay,funnel:iy,settings:ly,"rotate-cw":cy,maximize:dy,minimize:py,"shopping-cart":uy,"shopping-bag":my,package:fy,truck:gy,tag:hy,gift:by,receipt:yy,wallet:vy,store:xy,"dollar-sign":wy,percent:Cy,play:Sy,pause:Ay,"volume-x":Ty,camera:ky,image:Ey,film:My,headphones:Ly,"message-circle":Iy,"message-square":Ry,bell:Py,heart:Wy,star:By,eye:Hy,"eye-off":Dy,bookmark:Fy,"calendar-days":Oy,history:Ny,timer:_y,folder:Vy,"folder-open":$y,files:Uy,sparkles:zy,zap:qy,sun:jy,moon:Ky,flag:Gy,monitor:Yy,smartphone:Xy},Ee=(e,t=24,n="currentColor",o=2)=>{let r=Jy[e];return r?Qy(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 Qy(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 mi={allowedTypes:Yo,maxFileSize:10*1024*1024,maxFiles:4};function Zy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ev(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 ea=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:mi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:mi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:mi.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:mi.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=um(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 pm(l),g=ci(l)?URL.createObjectURL(l):null,m={id:Zy(),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=ci(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=ev(t.file.type),d=Ee(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=mm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Ee("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as tv}from"idiomorph";var fi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;tv.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 gi={index:-1,draft:""};function bm(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:{...gi}}}function ym(e,t){var n,o,r,s,a,i,d,l,f,u,g,m,C,v,E,L,I,R,H,P,w,x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se,ie,X,re;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:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(R=(I=(L=e.toolCall)==null?void 0:L.chunks)==null?void 0:I.length)!=null?R:0,(x=(w=(P=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?x:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,(U=(_=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:_.length)!=null?U:0,(ce=(ue=(ge=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:ge[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?ce:0,(Se=(He=(ve=(ke=e.reasoning)==null?void 0:ke.chunks)==null?void 0:ve[e.reasoning.chunks.length-1])==null?void 0:He.slice(-32))!=null?Se:"",(X=(ie=e.contentParts)==null?void 0:ie.length)!=null?X:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function vm(){return new Map}function xm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function wm(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Cm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function hi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Hr(e,t){return Xo(e)-e.scrollTop<=t}function bi(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 yi(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 Sm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Am(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 Tm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},En=1e5,mr=En+1;var ta={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},nv=["pre","code","a","script","style"],vi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:ta.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ta.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:ta.speed,duration:(r=e==null?void 0:e.duration)!=null?r:ta.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ta.buffer}},ov=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Em=new Map;for(let e of ov)Em.set(e.name,e);var na=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Em.get(e))!=null?o:null},xi=(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},rv=(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},sv=(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},Ml=/\s/,av=(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},iv=(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(Ml.test(s[i])){let l=i;for(;l<s.length&&Ml.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&&!Ml.test(s[f]);)l.appendChild(rv(o,s[f],t,n.value)),n.value+=1,f+=1;a.appendChild(l),i=f}r.replaceChild(a,e)},lv=(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(sv(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},oa=(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:nv).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)av(d,s)||i.push(d),d=a.nextNode();let l={value:(g=o==null?void 0:o.startIndex)!=null?g:0},f=t==="char"?iv:lv;for(let m of i)f(m,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},ra=(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},km=new WeakMap,cv=(e,t)=>{var s;if(!e.styles)return;let n=km.get(t);if(n||(n=new Set,km.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)},Ll=new WeakMap,dv=(e,t)=>{if(!e.onAttach)return;let n=Ll.get(t);if(n||(n=new Map,Ll.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Mm=e=>{let t=Ll.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Il=(e,t)=>{cv(e,t),dv(e,t)};function Rl(e,t=En){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 sa=0,fr=null;function Pl(e=document){var n;if(sa++,sa===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;fr={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,sa=Math.max(0,sa-1),sa===0&&fr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=fr.originalOverflow,r.style.position=fr.originalPosition,r.style.top=fr.originalTop,r.style.width=fr.originalWidth,s.scrollTo(0,fr.scrollY),fr=null}}}var Ci={side:"right",width:"420px",animate:!0,reveal:"resize"},xn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},aa=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Oo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Ci.side,width:(r=t==null?void 0:t.width)!=null?r:Ci.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ci.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ci.reveal}};var To={"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 ia=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:o}var oa=e=>({isError:!0,content:[{type:"text",text:e}]}),Dm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Om=e=>Gs(e)||e===Yo,yi=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,u,g;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall,m=!!(f!=null&&f.name)&&(Gs(f.name)||f.name===Yo&&((o=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:o.enabled)!==!1);((r=t.message.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.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:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i: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;((d=this.agentExecution)==null?void 0:d.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),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,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 Zs(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 Nl((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=na(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,g,f,m,x,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.transcript)!=null&&g.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(x=[...this.messages].reverse().find(L=>L.role==="assistant"))==null?void 0:x.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,g;this.voiceStatus=l,this.voiceActive=l==="listening",(g=(u=this.callbacks).onVoiceStatusChanged)==null||g.call(u,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Bb(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Zs(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:g}=t,m={id:a!=null?a:n==="user"?mi():n==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:g=!1,voiceProcessing:f,rawContent:m}=o,v={id:d!=null?d:r==="user"?mi():r==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...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,u,g,f,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=mi(),s=ea(),a={id:r,role:"user",content:o||gi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let E=Hm(x,this.config.errorMessage);if(E){let L={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(L)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(x))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=ea();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let g=Hm(l,this.config.errorMessage);if(g){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){var u,g,f,m,x;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:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(l?v=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let E=null;if(v instanceof Response){if(!v.ok){let L=await v.json().catch(()=>null);throw new Error((f=L==null?void 0:L.error)!=null?f:`Approval request failed: ${v.status}`)}E=v.body}else v instanceof ReadableStream&&(E=v);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(x=(m=this.callbacks).onError)==null||x.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 u,g,f,m,x,v,E,L,I,W,H,R;let o=this.messages.find(w=>w.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let r=(g=t.agentMetadata)==null?void 0:g.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(x=(m=this.callbacks).onError)==null||x.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,C=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(C.length===1){let k=typeof((E=C[0])==null?void 0:E.question)=="string"?C[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(L=this.abortController)==null||L.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([C,k])=>`${C}: ${Array.isArray(k)?k.join(", "):k}`).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((C,k)=>{let A=typeof(C==null?void 0:C.question)=="string"?C.question:"";if(!A)return;let S=w[A],_=Array.isArray(S)?S.join(", "):typeof S=="string"?S:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(r,{[s]:n});if(!w.ok){let C=await w.json().catch(()=>null);throw new Error((W=C==null?void 0:C.error)!=null?W:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let C=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,C||(R=(H=this.callbacks).onError)==null||R.call(H,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()}isSuggestRepliesAlreadyResolved(t){var o,r;if(((o=t.toolCall)==null?void 0:o.name)!==Yo)return!1;let n=this.messages.find(s=>s.id===t.id);return((r=(n!=null?n:t).agentMetadata)==null?void 0:r.suggestRepliesResolved)===!0}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(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},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,u,g;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var R,w,C,k,A,S,_;let m=(R=f.toolCall)==null?void 0:R.name,x=(w=f.toolCall)==null?void 0:w.id;if(!m||!x)return null;let v=`${t}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),o.push(v);let E=this.markWebMcpToolRunning(f),L=(k=(C=f.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?k:m;if(m===Yo)return{dedupeKey:v,resumeKey:L,output:Wl(),toolMessage:f,startedAt:E,completedAt:Date.now()};let I=new AbortController;this.webMcpResolveControllers.add(I),r.push(I);let W=this.client.executeWebMcpToolCall(m,(A=f.toolCall)==null?void 0:A.args,I.signal),H;if(!W)H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{H=await W}catch(V){let K=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return K||(_=(S=this.callbacks).onError)==null||_.call(S,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(f,oa(K?"Aborted by cancel()":Dm(V)),E),this.webMcpInflightKeys.delete(v),null}return I.signal.aborted?(this.markWebMcpToolComplete(f,oa("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:L,output:H,toolMessage:f,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let f={};for(let x of i)f[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,f,{signal:s.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((l=x.toolMessage.toolCall)==null?void 0:l.name)===Yo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,f instanceof Error?f:new Error(String(f)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,oa("Aborted by cancel()"),x.startedAt)}finally{for(let f of o)this.webMcpInflightKeys.delete(f);for(let f of r)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,v,E,L,I,W,H,R,w,C,k,A;let n=(x=t.agentMetadata)==null?void 0:x.executionId,o=(v=t.toolCall)==null?void 0:v.name,r=(E=t.toolCall)==null?void 0:E.id;if(!n){(I=(L=this.callbacks).onError)==null||I.call(L,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(_){(H=(W=this.callbacks).onError)==null||H.call(W,_ instanceof Error?_:new Error(String(_)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))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=o===Yo,u=(R=t.toolCall)==null?void 0:R.args,g=l?null:this.client.executeWebMcpToolCall(o,u,d),f="execute",m=a;try{let S;if(l?S=Wl():g?S=await g:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(t,oa("Aborted by cancel()"),a);return}let _=(C=(w=t.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?C:o;f="resume",await this.resumeWithToolOutput(n,_,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,m,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(S){let _=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(f==="execute"||_||d.aborted)&&this.markWebMcpToolComplete(t,oa(_||d.aborted?"Aborted by cancel()":Dm(S)),a),_||(A=(k=this.callbacks).onError)==null||A.call(k,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 u,g,f,m,x,v,E,L,I,W,H,R,w,C,k;if(s!==o)return r;let a={...r,...n};if(((u=r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=r.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let A=r.approval,S=n.approval;a.approval={...A,...S,executionId:S.executionId||A.executionId,toolName:S.toolName||A.toolName,description:S.description||A.description,toolType:(m=S.toolType)!=null?m:A.toolType,reason:(x=S.reason)!=null?x:A.reason,parameters:(v=S.parameters)!=null?v:A.parameters}}let i=(E=n.toolCall)==null?void 0:E.name,d=(L=n.agentMetadata)==null?void 0:L.executionId,l=(I=n.toolCall)==null?void 0:I.id;if(i&&Om(i)&&d&&l&&((W=n.agentMetadata)==null?void 0:W.awaitingLocalTool)===!0){let A=`${d}:${l}`,S=this.webMcpInflightKeys.has(A),_=this.webMcpResolvedKeys.has(A),V=(H=r.toolCall)==null?void 0:H.name,K=((R=r.agentMetadata)==null?void 0:R.executionId)===d&&((w=r.toolCall)==null?void 0:w.id)===l&&V!==void 0&&Om(V)&&((C=r.toolCall)==null?void 0:C.status)==="complete";(S||_||K)&&(a.agentMetadata={...(k=a.agentMetadata)!=null?k:{},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)})}};import{Activity as Hb,ArrowDown as Db,ArrowUp as Ob,ArrowUpRight as Fb,Bot as Nb,ChevronDown as _b,ChevronUp as Vb,ChevronRight as $b,ChevronLeft as Ub,Check as zb,Clipboard as qb,ClipboardCopy as jb,Copy as Kb,File as Gb,FileCode as Yb,FileSpreadsheet as Xb,FileText as Qb,ImagePlus as Jb,Loader as Zb,LoaderCircle as ey,Mic as ty,Paperclip as ny,RefreshCw as oy,Search as ry,Send as sy,ShieldAlert as ay,ShieldCheck as iy,ShieldX as ly,Square as cy,ThumbsDown as dy,ThumbsUp as py,Upload as uy,Volume2 as my,X as gy,User as fy,Mail as hy,Phone as by,Calendar as yy,Clock as vy,Building as xy,MapPin as wy,Lock as Cy,Key as Sy,CreditCard as Ay,AtSign as Ty,Hash as ky,Globe as Ey,Link as My,CircleCheck as Ly,CircleX as Iy,TriangleAlert as Ry,Info as Py,Ban as Wy,Shield as By,ArrowLeft as Hy,ArrowRight as Dy,ExternalLink as Oy,Ellipsis as Fy,EllipsisVertical as Ny,Menu as _y,House as Vy,Plus as $y,Minus as Uy,Pencil as zy,Trash as qy,Trash2 as jy,Save as Ky,Download as Gy,Share as Yy,Funnel as Xy,Settings as Qy,RotateCw as Jy,Maximize as Zy,Minimize as ev,ShoppingCart as tv,ShoppingBag as nv,Package as ov,Truck as rv,Tag as sv,Gift as av,Receipt as iv,Wallet as lv,Store as cv,DollarSign as dv,Percent as pv,Play as uv,Pause as mv,VolumeX as gv,Camera as fv,Image as hv,Film as bv,Headphones as yv,MessageCircle as vv,MessageSquare as xv,Bell as wv,Heart as Cv,Star as Sv,Eye as Av,EyeOff as Tv,Bookmark as kv,CalendarDays as Ev,History as Mv,Timer as Lv,Folder as Iv,FolderOpen as Rv,Files as Pv,Sparkles as Wv,Zap as Bv,Sun as Hv,Moon as Dv,Flag as Ov,Monitor as Fv,Smartphone as Nv}from"lucide";var _v={activity:Hb,"arrow-down":Db,"arrow-up":Ob,"arrow-up-right":Fb,bot:Nb,"chevron-down":_b,"chevron-up":Vb,"chevron-right":$b,"chevron-left":Ub,check:zb,clipboard:qb,"clipboard-copy":jb,copy:Kb,file:Gb,"file-code":Yb,"file-spreadsheet":Xb,"file-text":Qb,"image-plus":Jb,loader:Zb,"loader-circle":ey,mic:ty,paperclip:ny,"refresh-cw":oy,search:ry,send:sy,"shield-alert":ay,"shield-check":iy,"shield-x":ly,square:cy,"thumbs-down":dy,"thumbs-up":py,upload:uy,"volume-2":my,x:gy,user:fy,mail:hy,phone:by,calendar:yy,clock:vy,building:xy,"map-pin":wy,lock:Cy,key:Sy,"credit-card":Ay,"at-sign":Ty,hash:ky,globe:Ey,link:My,"circle-check":Ly,"circle-x":Iy,"triangle-alert":Ry,info:Py,ban:Wy,shield:By,"arrow-left":Hy,"arrow-right":Dy,"external-link":Oy,ellipsis:Fy,"ellipsis-vertical":Ny,menu:_y,house:Vy,plus:$y,minus:Uy,pencil:zy,trash:qy,"trash-2":jy,save:Ky,download:Gy,share:Yy,funnel:Xy,settings:Qy,"rotate-cw":Jy,maximize:Zy,minimize:ev,"shopping-cart":tv,"shopping-bag":nv,package:ov,truck:rv,tag:sv,gift:av,receipt:iv,wallet:lv,store:cv,"dollar-sign":dv,percent:pv,play:uv,pause:mv,"volume-x":gv,camera:fv,image:hv,film:bv,headphones:yv,"message-circle":vv,"message-square":xv,bell:wv,heart:Cv,star:Sv,eye:Av,"eye-off":Tv,bookmark:kv,"calendar-days":Ev,history:Mv,timer:Lv,folder:Iv,"folder-open":Rv,files:Pv,sparkles:Wv,zap:Bv,sun:Hv,moon:Dv,flag:Ov,monitor:Fv,smartphone:Nv},Ee=(e,t=24,n="currentColor",o=2)=>{let r=_v[e];return r?Vv(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 Vv(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),r.appendChild(d)}),r}var vi={allowedTypes:Xo,maxFileSize:10*1024*1024,maxFiles:4};function $v(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Uv(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 ra=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:vi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:vi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:vi.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:vi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let u=Pm(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(r=u.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,g);continue}try{let g=await Rm(l),f=fi(l)?URL.createObjectURL(l):null,m={id:$v(),file:l,previewUrl:f,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}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=fi(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=Uv(t.file.type),d=Ee(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Wm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Ee("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as zv}from"idiomorph";var xi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;zv.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 wi={index:-1,draft:""};function Fm(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:{...wi}}}function Nm(e,t){var n,o,r,s,a,i,d,l,u,g,f,m,x,v,E,L,I,W,H,R,w,C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se,ie,X,re;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(g=e.approval)==null?void 0:g.status)!=null?f:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(W=(I=(L=e.toolCall)==null?void 0:L.chunks)==null?void 0:I.length)!=null?W:0,(C=(w=(R=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?C:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(A=e.toolCall)!=null&&A.args?JSON.stringify(e.toolCall.args).length:0,(V=(_=(S=e.reasoning)==null?void 0:S.chunks)==null?void 0:_.length)!=null?V:0,(ce=(ue=(fe=(K=e.reasoning)==null?void 0:K.chunks)==null?void 0:fe[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?ce:0,(Se=(He=(ve=(ke=e.reasoning)==null?void 0:ke.chunks)==null?void 0:ve[e.reasoning.chunks.length-1])==null?void 0:He.slice(-32))!=null?Se:"",(X=(ie=e.contentParts)==null?void 0:ie.length)!=null?X:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function _m(){return new Map}function Vm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function $m(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Um(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ci(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 Nr(e,t){return Qo(e)-e.scrollTop<=t}function Si(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Ai(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function zm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function qm(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 jm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Ln=1e5,hr=Ln+1;var sa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},qv=["pre","code","a","script","style"],Ti=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:sa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:sa.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:sa.speed,duration:(r=e==null?void 0:e.duration)!=null?r:sa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:sa.buffer}},jv=[{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"}],Gm=new Map;for(let e of jv)Gm.set(e.name,e);var aa=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Gm.get(e))!=null?o:null},ki=(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},Kv=(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},Gv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},_l=/\s/,Yv=(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},Xv=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(_l.test(s[i])){let l=i;for(;l<s.length&&_l.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<s.length&&!_l.test(s[u]);)l.appendChild(Kv(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}r.replaceChild(a,e)},Qv=(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(Gv(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},ia=(e,t,n,o)=>{var g,f;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((g=o==null?void 0:o.skipTags)!=null?g:qv).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Yv(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},u=t==="char"?Xv:Qv;for(let m of i)u(m,n,l);return r.innerHTML},Ei=(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},la=(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},Km=new WeakMap,Jv=(e,t)=>{var s;if(!e.styles)return;let n=Km.get(t);if(n||(n=new Set,Km.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)},Vl=new WeakMap,Zv=(e,t)=>{if(!e.onAttach)return;let n=Vl.get(t);if(n||(n=new Map,Vl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Ym=e=>{let t=Vl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},$l=(e,t)=>{Jv(e,t),Zv(e,t)};function Ul(e,t=Ln){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 ca=0,br=null;function zl(e=document){var n;if(ca++,ca===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;br={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,ca=Math.max(0,ca-1),ca===0&&br)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=br.originalOverflow,r.style.position=br.originalPosition,r.style.top=br.originalTop,r.style.width=br.originalWidth,s.scrollTo(0,br.scrollY),br=null}}}var da={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Cn=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"},To=e=>{var n,o,r,s,a,i;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:da.side,width:(r=t==null?void 0:t.width)!=null?r:da.width,animate:(s=t==null?void 0:t.animate)!=null?s:da.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:da.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:da.maxHeight}};var ko={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var ua=(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 Zs=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 R,H,P,w,x,k,S,T,_,U,G,ge,ue;let a=(R=s.launcher)!=null?R:{},i=xn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ce=(H=a.title)!=null?H:"Chat Assistant";d.textContent=ce,d.setAttribute("title",ce)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ce=(P=a.subtitle)!=null?P:"Get answers fast";l.textContent=ce,l.setAttribute("title",ce)}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 ce=(w=a.agentIconSize)!=null?w:"40px";if(u.style.height=ce,u.style.width=ce,u.innerHTML="",a.agentIconName){let ke=parseFloat(ce)||24,ve=Ee(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);ve?(u.appendChild(ve),u.style.display=""):(u.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ce=(S=a.agentIconSize)!=null?S:"40px";g.style.height=ce,g.style.width=ce,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 ce=(T=a.callToActionIconSize)!=null?T:"32px";m.style.height=ce,m.style.width=ce,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 ke=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ke=(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 ve=parseFloat(ce)||24,He=Math.max(ve-ke,8),Se=Ee(a.callToActionIconName,He,"currentColor",2);Se?m.appendChild(Se):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}let C=a.position&&To[a.position]?To[a.position]:To["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${v} ${C}`,i||(n.style.zIndex=String((G=a.zIndex)!=null?G:En));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ge=a.border)!=null?ge:L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ue=a.collapsedMaxWidth)!=null?ue:"",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 pv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{var v,E,L,I,R,H;let{showClose:n=!0,wrapperClassName:o=pv,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=r!=null?r:a.closeButtonSize)!=null?E:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let f=(L=a.closeButtonTooltipText)!=null?L:"Close chat",u=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",f),l.style.display=n?"":"none";let g=(R=a.closeButtonIconName)!=null?R:"x",m=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||Hn.actionIconColor;let C=Ee(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 P=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${P} 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 P=null,w=()=>{if(P)return;let k=l.ownerDocument,S=k.body;if(!S)return;P=Fo(k,"div","persona-clear-chat-tooltip"),P.textContent=f;let T=Fo(k,"div");T.className="persona-clear-chat-tooltip-arrow",P.appendChild(T);let _=l.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(mr),P.style.left=`${_.left+_.width/2}px`,P.style.top=`${_.top-8}px`,P.style.transform="translate(-50%, -100%)",S.appendChild(P)},x=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=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}},uv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ai=(e,t={})=>{var P,w,x,k,S,T,_,U,G,ge,ue,ce,ke;let{wrapperClassName:n=uv,buttonSize:o,iconSize:r="20px"}=t,a=(w=((P=e==null?void 0:e.launcher)!=null?P:{}).clearChat)!=null?w:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(S=a.iconColor)!=null?S:"",f=(T=a.backgroundColor)!=null?T:"",u=(_=a.borderWidth)!=null?_:"",g=(U=a.borderColor)!=null?U:"",m=(G=a.borderRadius)!=null?G:"",C=(ge=a.paddingX)!=null?ge:"",v=(ue=a.paddingY)!=null?ue:"",E=(ce=a.tooltipText)!=null?ce:"Clear chat",L=(ke=a.showTooltip)!=null?ke:!0,I=b("div",n),R=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");R.style.height=i,R.style.width=i,R.type="button",R.setAttribute("aria-label",E),R.style.color=l||Hn.actionIconColor;let H=Ee(d,r,"currentColor",1);if(H&&(H.style.display="block",R.appendChild(H)),f&&(R.style.backgroundColor=f,R.classList.remove("hover:persona-bg-gray-100")),u||g){let ve=u||"0px",He=g||"transparent";R.style.border=`${ve} solid ${He}`,R.classList.remove("persona-border-none")}if(m&&(R.style.borderRadius=m,R.classList.remove("persona-rounded-full")),C&&(R.style.paddingLeft=C,R.style.paddingRight=C),v&&(R.style.paddingTop=v,R.style.paddingBottom=v),I.appendChild(R),L&&E){let ve=null,He=()=>{if(ve)return;let ie=R.ownerDocument,X=ie.body;if(!X)return;ve=Fo(ie,"div","persona-clear-chat-tooltip"),ve.textContent=E;let re=Fo(ie,"div");re.className="persona-clear-chat-tooltip-arrow",ve.appendChild(re);let be=R.getBoundingClientRect();ve.style.position="fixed",ve.style.zIndex=String(mr),ve.style.left=`${be.left+be.width/2}px`,ve.style.top=`${be.top-8}px`,ve.style.transform="translate(-50%, -100%)",X.appendChild(ve)},Se=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};I.addEventListener("mouseenter",He),I.addEventListener("mouseleave",Se),R.addEventListener("focus",He),R.addEventListener("blur",Se),I._cleanupTooltip=()=>{Se(),I.removeEventListener("mouseenter",He),I.removeEventListener("mouseleave",Se),R.removeEventListener("focus",He),R.removeEventListener("blur",Se)}}return{button:R,wrapper:I}};var Hn={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))"},Dr=e=>{var P,w,x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se;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=(P=t==null?void 0:t.launcher)!=null?P:{},s=(w=r.headerIconSize)!=null?w:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ie=parseFloat(s)||24,X=Ee(d,ie*.6,"currentColor",1);X?l.replaceChildren(X):l.textContent=(T=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?T:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let ie=b("img");ie.src=t.launcher.iconUrl,ie.alt="",ie.className="persona-rounded-xl persona-object-cover",ie.style.height=s,ie.style.width=s,l.replaceChildren(ie)}else l.textContent=(G=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?G:"\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=Hn.titleColor,u.textContent=(ue=(ge=t==null?void 0:t.launcher)==null?void 0:ge.title)!=null?ue:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Hn.subtitleColor,g.textContent=(ke=(ce=t==null?void 0:t.launcher)==null?void 0:ce.subtitle)!=null?ke:"Here to help you get answers fast",f.append(u,g),i?o.append(f):o.append(l,f);let m=(ve=r.clearChat)!=null?ve:{},C=(He=m.enabled)!=null?He:!0,v=(Se=m.placement)!=null?Se:"inline",E=null,L=null;if(C){let X=Ai(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=X.button,L=X.wrapper,v==="top-right"&&(L.style.right="48px"),v==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:H}=Si(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(H),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:R,closeButtonWrapper:H,clearChatButton:E,clearChatButtonWrapper:L}},la=(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 cs(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(mr)):(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 E=document.createElement("hr");a.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",m.id),m.destructive&&C.setAttribute("data-destructive",""),m.icon){let E=Ee(m.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let v=document.createElement("span");v.textContent=m.label,C.appendChild(v),C.addEventListener("click",E=>{E.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 Mn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ee(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[f,u]of Object.entries(i))d.setAttribute(f,u);return d}function Wl(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=Ee(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 Lm(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=Ee(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,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=cs({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 E=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"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 mv=e=>{var o;let t=Dr({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 fv(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Ee(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=cs({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 gv=e=>{var I,R,H,P,w,x,k,S,T;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,f;if(d)l=Lm({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Hn.titleColor,f=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),f=b("span","persona-text-base persona-font-semibold persona-truncate"),f.style.color=Hn.titleColor,f.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(f),fv(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 U=r.onTitleClick;l.addEventListener("click",G=>{G.target.closest("button")||U()}),l.addEventListener("keydown",G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),U())})}let _=r==null?void 0:r.titleRowHover;_&&(l.style.borderRadius=(x=_.borderRadius)!=null?x:"10px",l.style.padding=(k=_.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var U,G;l.style.backgroundColor=(U=_.background)!=null?U:"",l.style.borderColor=(G=_.border)!=null?G:""}),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||Hn.actionIconColor;let C=(T=a.closeButtonIconName)!=null?T:"x",v=Ee(C,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m),i.appendChild(g);let E=b("div");E.style.display="none";let L=b("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:f,headerSubtitle:L,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Im={default:mv,minimal:gv},hv=e=>{var t;return(t=Im[e])!=null?t:Im.default},Ti=(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=hv(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 ki=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}},Ei=e=>{var P,w,x,k,S,T,_,U,G,ge,ue,ce;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(w=t.useIcon)!=null?w:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(T=t.stopTooltipText)!=null?T:"Stop generating",d=(U=(_=e==null?void 0:e.copy)==null?void 0:_.sendButtonLabel)!=null?U:"Send",l=(ge=(G=e==null?void 0:e.copy)==null?void 0:G.stopButtonLabel)!=null?ge:"Stop",f=(ue=t.showTooltip)!=null?ue:!1,u=(ce=t.size)!=null?ce:"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 E=null,L=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 ke=parseFloat(u)||24,ve=(m==null?void 0:m.trim())||"currentColor";r?(E=Ee(r,ke,ve,2),E?v.appendChild(E):v.textContent=o):v.textContent=o,L=Ee(s,ke,ve,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 I=null;f&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,C.appendChild(I)),v.setAttribute("aria-label",a),C.appendChild(v);let R="send";return{button:v,wrapper:C,setMode:ke=>{if(ke===R)return;R=ke;let ve=ke==="stop"?i:a;if(v.setAttribute("aria-label",ve),I&&(I.textContent=ve),n){if(E&&L){let He=ke==="stop"?L:E;v.replaceChildren(He)}}else v.textContent=ke==="stop"?l:d}}},Mi=e=>{var I,R,H,P,w,x,k,S,T,_,U,G;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((R=t.provider)==null?void 0:R.type)==="runtype";if(!(o||r))return null;let a=(P=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?P:"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:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,m=(_=t.iconColor)!=null?_:(T=e==null?void 0:e.sendButton)==null?void 0:T.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=Ee(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 E=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((G=t.showTooltip)!=null?G:!1)&&E){let ge=b("div","persona-send-button-tooltip");ge.textContent=E,i.appendChild(ge)}return{button:d,wrapper:i}},Li=e=>{var C,v,E,L,I,R,H,P;let t=(C=e==null?void 0:e.attachments)!=null?C:{};if(t.enabled!==!0)return null;let n=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((L=t.allowedTypes)!=null?L:Yo).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",(R=t.buttonTooltipText)!=null?R:"Attach file");let i=(H=t.buttonIconName)!=null?H:"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=Ee(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=(P=t.buttonTooltipText)!=null?P:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=g,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},Ii=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},Ri=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Pi=e=>{var C,v,E,L,I,R;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=Ri(),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}=ki(t);a();let i=Ei(t),d=Mi(t),l=Li(t),f=Ii(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",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,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:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:u,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var Rm=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Ee("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Ee("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Pm=e=>{var C,v,E,L,I,R;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Ri();o.style.display="none";let r=Ii(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=ki(t);s.style.maxHeight="100px",a();let i=Ei(t),d=Mi(t),l=Li(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",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&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:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:m,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Wm=e=>{var f,u,g,m,C,v,E,L,I,R,H,P,w,x,k,S,T;let t=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.enabled)!=null?u:!0,n=xn(e);if(aa(e)){let _=(m=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?m:{},U=b("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(C=_.expandedSize)!=null?C:"anchored",U.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:En);let G=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");G.style.width="100%",U.appendChild(G);let ge=b("div","persona-widget-pill-root");return ge.setAttribute("data-persona-composer-bar",""),ge.dataset.state="collapsed",ge.dataset.expandedSize=(L=_.expandedSize)!=null?L:"anchored",ge.style.zIndex=String((R=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?R:En),{wrapper:U,panel:G,pillRoot:ge}}if(n){let _=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(U),{wrapper:_,panel:U}}if(!t){let _=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),G=(P=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?P:"100%";return _.style.width=G,U.style.width="100%",_.appendChild(U),{wrapper:_,panel:U}}let r=(w=e==null?void 0:e.launcher)!=null?w:{},s=r.position&&To[r.position]?To[r.position]:To["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:En);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(T=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?T:e==null?void 0:e.launcherWidth,l=d!=null?d:fo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},bv=(e,t)=>{var H,P,w,x,k,S,T,_,U;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Si(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=(P=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:P.enabled)!=null?w:!0,a=null,i=null;if(s){let G=Ai(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=G.button,i=G.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages"),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=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(T=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",f.append(u,g);let m=b("div","persona-flex persona-flex-col persona-gap-3"),C=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;C&&(m.style.maxWidth=C,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(f.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(f,m);let E=b("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let L=Pm({config:e}),{root:I,textNode:R}=Rm();return n.append(d,r,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:u,introSubtitle:g,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:R}},Bm=(e,t=!0)=>{var E,L,I,R,H,P,w,x,k;if(aa(e))return bv(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(E=e==null?void 0:e.layout)==null?void 0:E.header,r=((L=e==null?void 0:e.layout)==null?void 0:L.showHeader)!==!1,s=o?Ti(e,o,{showClose:t}):Dr({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=xn(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=(R=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?R:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(P=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?P:"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=Pi({config:e}),C=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?la(n,s,e):(s.header.style.display="none",la(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 yv=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}},vv=(e,t)=>{if(!e)return null;let n=yv(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},xv=(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},wv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Bl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Hl=320,Dm=320,Cv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Sv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Av=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Tv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),kv=(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=`${Hl}px`,l.style.maxHeight=`${Dm}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}),wv(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}},Ev=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Bl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Hl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Mv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Bl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Hl}px`,r.style.maxHeight=`${Dm}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}},Lv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Bl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ca=()=>{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},Iv=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ca};if(t){let r=t(o);if(r!==null)return r}return ca()},Rv=(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},Hm=(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},Pv=(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},Wv=(e,t,n)=>{var m,C,v,E,L,I;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 R=b("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(E=t.visibility)!=null?E:"hover",i=(L=t.align)!=null?L:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],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=(R,H,P)=>{let w=Mn({icon:R,label:H,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",P),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},Dl=(e,t,n,o,r,s)=>{var ie,X,re,be,he,j,se,Ie,ne,Z,oe,at,it,Me,de,Xe,We;let a=n!=null?n:{},i=(ie=a.layout)!=null?ie:"bubble",d=a.avatar,l=a.timestamp,f=(X=d==null?void 0:d.show)!=null?X:!1,u=(re=l==null?void 0:l.show)!=null?re:!1,g=(be=d==null?void 0:d.position)!=null?be:"left",m=(he=l==null?void 0:l.position)!=null?he:"below",C=Pv(e.role,i),v=b("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Cv(e),L=(se=(j=e.content)==null?void 0:j.trim())!=null?se:"",R=E.length>0&&L===li,H=vi((ne=(Ie=s==null?void 0:s.widgetConfig)==null?void 0:Ie.features)==null?void 0:ne.streamAnimation),P=(at=(oe=(Z=s==null?void 0:s.widgetConfig)==null?void 0:Z.features)==null?void 0:oe.streamAnimation)==null?void 0:at.plugins,w=e.role==="assistant"&&H.type!=="none"?na(H.type,P):null,x=e.role==="assistant"&&((it=w==null?void 0:w.isAnimating)==null?void 0:it.call(w,e))===!0,k=e.role==="assistant"&&w!==null&&(!!e.streaming||x);k&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),k&&w&&(w.containerClass&&S.classList.add(w.containerClass),S.style.setProperty("--persona-stream-step",`${H.speed}ms`),S.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let T=k?xi((Me=e.content)!=null?Me:"",H.buffer,w,e,!!e.streaming):(de=e.content)!=null?de:"",_=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=_;k&&(w==null?void 0:w.wrap)==="char"?U=oa(_,"char",e.id,{skipTags:w.skipTags}):k&&(w==null?void 0:w.wrap)==="word"&&(U=oa(_,"word",e.id,{skipTags:w.skipTags}));let G=null;if(R?(G=document.createElement("div"),G.innerHTML=U,G.style.display="none",S.appendChild(G)):S.innerHTML=U,k&&(w!=null&&w.useCaret)&&!R&&L){let q=wi(),me=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),et=me[me.length-1];if(et!=null&&et.parentNode)et.parentNode.insertBefore(q,et.nextSibling);else{let Et=S.lastElementChild;Et?Et.appendChild(q):S.appendChild(q)}}if(u&&m==="inline"&&e.createdAt){let q=Hm(e,l);q.classList.add("persona-ml-2","persona-inline"),S.appendChild(q)}if(E.length>0){let q=kv(E,!R&&!!L,()=>{R&&G&&(G.style.display="")});q?v.appendChild(q):R&&G&&(G.style.display="")}let ge=Sv(e);if(ge.length>0){let q=Ev(ge);q&&v.appendChild(q)}let ue=Av(e);if(ue.length>0){let q=Mv(ue);q&&v.appendChild(q)}let ce=Tv(e);if(ce.length>0){let q=Lv(ce);q&&v.appendChild(q)}if(v.appendChild(S),u&&m==="below"&&e.createdAt){let q=Hm(e,l);q.classList.add("persona-mt-1"),v.appendChild(q)}let ke=e.role==="assistant"?vv(e.stopReason,(We=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:We.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let q=!!(T&&T.trim()),me=H.placeholder==="skeleton",et=me&&H.buffer==="line"&&q;if(q)et&&v.appendChild(ra());else if(me)v.appendChild(ra());else{let Et=Iv("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Et&&v.appendChild(Et)}}if(ke&&e.stopReason&&!e.streaming&&(L||(S.style.display="none"),v.appendChild(xv(e.stopReason,ke))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let q=Wv(e,o,r);v.appendChild(q)}if(!f||e.role==="system")return v;let He=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Se=Rv(d,e.role);return g==="right"||g==="left"&&e.role==="user"?He.append(v,Se):He.append(Se,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),He};var ds=new Set,Bv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Hv=(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
- `):""},Fm=(e,t)=>{let n=ds.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ee(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Fl=(e,t)=>{var ue,ce,ke,ve,He,Se,ie,X,re,be,he;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(ce=(ue=t==null?void 0:t.features)==null?void 0:ue.reasoningDisplay)!=null?ce:{},s=r.expandable!==!1,a=s&&ds.has(e.id),i=n.status!=="complete",d=Hv(e,(ke=r.previewMaxLines)!=null?ke:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=(ve=t==null?void 0:t.reasoning)!=null?ve:{},C=String((He=n.startedAt)!=null?He:Date.now()),v=()=>{let j=b("span","");return j.setAttribute("data-tool-elapsed",C),j.textContent=oi(n),j},E=(Se=m.renderCollapsedSummary)==null?void 0:Se.call(m,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:oi(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(u.textContent=E,f.appendChild(u)):E instanceof HTMLElement?f.appendChild(E):(u.textContent=g,f.appendChild(u));let L=b("span","persona-text-xs persona-text-persona-primary");L.textContent=om(n),f.appendChild(L);let I=(ie=r.loadingAnimation)!=null?ie:"none",R=m.activeTextTemplate,H=m.completeTextTemplate,P=i?R:H,w=E instanceof HTMLElement,x=(j,se,Ie)=>{let ne=Ie;for(let Z of se){let oe=b("span","persona-tool-char");oe.style.setProperty("--char-index",String(ne)),oe.textContent=Z===" "?"\xA0":Z,j.appendChild(oe),ne++}return ne},k=(j,se)=>{u.textContent="";let Ie=ri(j,""),ne=0;for(let Z of Ie){let oe=Z.styles.length>0?(()=>{let at=b("span",Z.styles.map(it=>`persona-tool-text-${it}`).join(" "));return u.appendChild(at),at})():u;if(Z.isDuration&&i)oe.appendChild(v());else{let at=Z.isDuration?oi(n):Z.text;se?ne=x(oe,at,ne):oe.appendChild(document.createTextNode(at))}}};if(!w&&P)if(L.style.display="none",u.style.display="",i&&I!=="none"){let j=(X=m.loadingAnimationDuration)!=null?X:2e3;u.setAttribute("data-preserve-animation","true"),I==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),k(P,!1)):(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="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)),k(P,!0))}else k(P,!1);else if(!w&&i&&I!=="none"){u.style.display="";let j=(re=m.loadingAnimationDuration)!=null?re:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="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 se=u.textContent||g;u.textContent="",x(u,se,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 se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?S.appendChild(se):S.textContent=a?"Hide":"Show";let Ie=b("div","persona-flex persona-items-center persona-ml-auto");Ie.append(S),l.append(f,Ie)}else l.append(f);let T=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(T.setAttribute("data-persona-collapsed-preview","reasoning"),T.style.display="none",T.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let j=(he=(be=t==null?void 0:t.reasoning)==null?void 0:be.renderCollapsedPreview)==null?void 0:he.call(be,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Bv(T,j)||(T.textContent=d),T.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,T),o;let _=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let U=n.chunks.join(""),G=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=U||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(G),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?S.appendChild(se):S.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",T.style.display=a?"none":T.textContent||T.childNodes.length?"":"none"})(),o.append(l,T,_),o};var ps=new Set,Dv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Fv=(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=ls(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Ov=(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=Fv(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?rm(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=Al(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Al(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Om=(e,t,n)=>{var f;let o=ps.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=Ee(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")},Ol=(e,t)=>{var U,G,ge,ue,ce,ke,ve,He,Se;let n=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(ge=(G=t==null?void 0:t.features)==null?void 0:G.toolCallDisplay)!=null?ge:{},a=s.expandable!==!1,i=a&&ps.has(e.id),{summary:d,previewText:l,isActive:f}=Ov(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((ue=n.startedAt)!=null?ue:Date.now()),v=()=>{let ie=b("span","");return ie.setAttribute("data-tool-elapsed",C),ie.textContent=Gs(n),ie},E=(ke=o.renderCollapsedSummary)==null?void 0:ke.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ce=s.collapsedMode)!=null?ce:"tool-call",isActive:f,config:t!=null?t:{},elapsed:Gs(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(m.textContent=E,g.appendChild(m)):E instanceof HTMLElement?g.appendChild(E):(m.textContent=d,g.appendChild(m));let L=(ve=s.loadingAnimation)!=null?ve:"none",I=o.activeTextTemplate,R=o.completeTextTemplate,H=f?I:R,P=E instanceof HTMLElement,w=(ie,X,re)=>{let be=re;for(let he of X){let j=b("span","persona-tool-char");j.style.setProperty("--char-index",String(be)),j.textContent=he===" "?"\xA0":he,ie.appendChild(j),be++}return be},x=(ie,X)=>{var j;m.textContent="";let re=((j=n.name)==null?void 0:j.trim())||"tool",be=ri(ie,re),he=0;for(let se of be){let Ie=se.styles.length>0?(()=>{let ne=b("span",se.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(ne),ne})():m;if(se.isDuration&&f)Ie.appendChild(v());else{let ne=se.isDuration?Gs(n):se.text;X?he=w(Ie,ne,he):Ie.appendChild(document.createTextNode(ne))}}};if(!P)if(f&&L!=="none"){let ie=(He=o.loadingAnimationDuration)!=null?He:2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),H&&x(H,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),L==="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)),H)x(H,!0);else{let X=m.textContent||d;m.textContent="",w(m,X,0)}}else H&&x(H,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let ie=o.toggleTextColor||o.headerTextColor||"currentColor",X=Ee(i?"chevron-up":"chevron-down",16,ie,2);X?k.appendChild(X):k.textContent=i?"Hide":"Show";let re=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(k),u.append(g,re)}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 ie=(Se=o.renderCollapsedPreview)==null?void 0:Se.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:f,config:t!=null?t:{}});Dv(S,ie)||(S.textContent=l),S.style.display=""}if(!i&&f&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,S),r;let T=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(T.style.display=i?"":"none",o.contentBackgroundColor&&(T.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(T.style.color=o.contentTextColor),o.contentPaddingX&&(T.style.paddingLeft=o.contentPaddingX,T.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(T.style.paddingTop=o.contentPaddingY,T.style.paddingBottom=o.contentPaddingY),n.name){let ie=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ie.style.color=o.contentTextColor:o.headerTextColor&&(ie.style.color=o.headerTextColor),ie.textContent=n.name,T.appendChild(ie)}if(n.args!==void 0){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=ls(n.args),ie.append(X,re),T.appendChild(ie)}if(n.chunks&&n.chunks.length){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=n.chunks.join(""),ie.append(X,re),T.appendChild(ie)}if(n.status==="complete"&&n.result!==void 0){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=ls(n.result),ie.append(X,re),T.appendChild(ie)}if(n.status==="complete"&&typeof n.duration=="number"){let ie=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ie.style.color=o.contentTextColor),ie.textContent=`Duration: ${n.duration}ms`,T.appendChild(ie)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let ie=o.toggleTextColor||o.headerTextColor||"currentColor",X=Ee(i?"chevron-up":"chevron-down",16,ie,2);X?k.appendChild(X):k.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(u,S,T),r};import{parse as Nv,ARR as _v,OBJ as Vv,STR as $v}from"partial-json";var Uv="ask_user_question",Nl=8,us="data-persona-ask-sheet-for",zv="Other",qv="Other\u2026",_m="Type your own answer here",Vm="Send",jv="Next",Kv="Back",Gv="Submit all",Yv="Skip",Xv=3,_l="data-ask-current-index",Vl="data-ask-question-count",$m="data-ask-answers",$l="data-ask-grouped",Um="data-ask-layout",Jv=e=>e.layout==="pills"?"pills":"rows",Qv=e=>e.getAttribute(Um)==="pills"?"pills":"rows",Nm=!1,zm=e=>e.replace(/["\\]/g,"\\$&"),Fr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Uv,Ul=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ms=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=Nv(r,$v|Vv|_v);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},da=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Nl&&!Nm&&(Nm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Nl}.`)),t.slice(0,Nl)},Zv=e=>{var t;return(t=da(e)[0])!=null?t:null},ex=(e,t)=>{var n;return(n=da(e)[t])!=null?n:null},tx=(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))},qm=(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},nx=(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=qm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ox=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},rx=(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<Xv;m++)s.appendChild(ox(o));return s}if(d.forEach((m,C)=>{s.appendChild(nx(m,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?zv:qv;if(o==="rows"){let C=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(f=t.freeTextPlaceholder)!=null?f:_m,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),v.appendChild(E),C.appendChild(v);let L=qm(o,a,d.length);L&&C.appendChild(L),s.appendChild(C)}else{let C=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(g=t.freeTextLabel)!=null?g:m,s.appendChild(C)}}return s},jm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:_m,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Vm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},sx=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:Vm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ax=(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:Kv,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:Yv,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:Gv:(g=n.nextLabel)!=null?g:jv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Or=e=>{let t=e.getAttribute($m);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Km=(e,t)=>{e.setAttribute($m,JSON.stringify(t))},go=e=>{var n;let t=Number((n=e.getAttribute(_l))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ix=(e,t)=>{e.setAttribute(_l,String(Math.max(0,Math.floor(t))))},fs=e=>{var n;let t=Number((n=e.getAttribute(Vl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},gr=e=>e.getAttribute($l)==="true",lx=(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},cx=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Wi=(e,t)=>{let{payload:n}=ms(t),o=da(n),r=Or(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},Gm=e=>{let t=Or(e),n=go(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=""},Ym=e=>{if(!gr(e))return;let t=Or(e),n=go(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}},zl=(e,t,n)=>{let o=Ul(n),r=Qv(e),{payload:s,complete:a}=ms(t),i=gr(e),d=go(e),l=fs(e),f=i?ex(s,d):Zv(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 I=typeof(f==null?void 0:f.question)=="string"?f.question:"";C.textContent=I,C.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=rx(f,o,a,r);v.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(jm(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(sx(o)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=ax(d,l,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();Gm(e),Ym(e)},dx=(e,t,n)=>{let o=Ul(t),r=Jv(o),s=e.toolCall.id,a=da(n),i=Math.max(1,a.length),d=i>1,l=lx(e,a),f=d?cx(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(us,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Vl,String(i)),u.setAttribute(_l,String(f)),u.setAttribute($l,d?"true":"false"),u.setAttribute(Um,r),Km(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`),tx(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 E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild(jm(o,r)),zl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},px=(e,t,n)=>{let{payload:o}=ms(t),r=Math.max(1,da(o).length);r>fs(e)&&(e.setAttribute(Vl,String(r)),r>1&&!gr(e)&&e.setAttribute($l,"true")),zl(e,t,n)};var Bi=(e,t,n)=>{if(!n||!Fr(e)||Ul(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${us}]`).forEach(l=>{l.getAttribute(us)!==r&&l.remove()});let a=n.querySelector(`[${us}="${zm(r)}"]`);if(a){px(a,e,t);return}let{payload:i}=ms(e),d=dx(e,t,i);n.appendChild(d)},gs=(e,t)=>{if(!e)return;let n=t?`[${us}="${zm(t)}"]`:`[${us}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},ql=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),hr=(e,t)=>{let n=Or(e),o=go(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Km(e,n),Gm(e),Ym(e)},Hi=(e,t,n,o)=>{let r=fs(e),s=Math.max(0,Math.min(r-1,o));ix(e,s),zl(e,t,n)};var Di=new Map,ux=e=>{let n=(e.startsWith(Pr)?e.slice(Pr.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)},Xm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Jm=(e,t)=>{var o,r,s;let n=(r=(o=Xm(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Di.get(e))!=null?s:n==="expanded"},Qm=(e,t,n)=>{var a,i;let o=Xm(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ee(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Zm=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Jm(e,n);Qm(o,s,n),r.style.display=s?"":"none"};var Fi=(e,t)=>{var x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se,ie;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=(k=o==null?void 0:o.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=o==null?void 0:o.titleColor)!=null?S:"currentColor",f=Ee(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=(T=o==null?void 0:o.title)!=null?T:"Approval Required",g.appendChild(m),!r){let X=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),g.appendChild(X)}u.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Pr)?Sl(n.toolName):void 0,E=(_=o==null?void 0:o.formatDescription)==null?void 0:_.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,I=E||(L?n.description:`The assistant wants to use \u201C${v!=null?v:ux(n.toolName)}\u201D.`),R=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(R.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(R.style.color=o.descriptionColor),R.textContent=I,u.appendChild(R),n.reason){let X=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?X.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(X.style.color=o.descriptionColor);let re=b("span","persona-font-medium");re.textContent=`${(U=o==null?void 0:o.reasonLabel)!=null?U:"Agent's stated reason:"} `,X.appendChild(re),X.appendChild(document.createTextNode(n.reason)),u.appendChild(X)}let H=(G=o==null?void 0:o.detailsDisplay)!=null?G:"collapsed",P=!!n.description&&!L,w=P||!!n.parameters;if(H!=="hidden"&&w){let X=Jm(e.id,t),re=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");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(re.style.color=o.descriptionColor);let be=b("span");be.setAttribute("data-approval-details-label","true");let he=b("span","persona-inline-flex persona-items-center");he.setAttribute("data-approval-details-chevron","true"),re.append(be,he),Qm(re,X,t),u.appendChild(re);let j=b("div");if(j.setAttribute("data-approval-details","true"),j.style.display=X?"":"none",P){let se=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor),se.textContent=n.description,j.appendChild(se)}if(n.parameters){let se=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&&(se.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(se.style.color=o.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=ls(n.parameters),j.appendChild(se)}u.appendChild(j)}if(r){let X=b("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let re=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");re.type="button",re.style.backgroundColor=(ge=o==null?void 0:o.approveButtonColor)!=null?ge:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(ue=o==null?void 0:o.approveButtonTextColor)!=null?ue:"#ffffff",re.setAttribute("data-approval-action","approve");let be=Ee("shield-check",14,(ce=o==null?void 0:o.approveButtonTextColor)!=null?ce:"#ffffff",2);be&&(be.style.marginRight="4px",re.appendChild(be));let he=document.createTextNode((ke=o==null?void 0:o.approveLabel)!=null?ke:"Approve");re.appendChild(he);let j=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");j.type="button",j.style.backgroundColor=(ve=o==null?void 0:o.denyButtonColor)!=null?ve:"transparent",j.style.color=(He=o==null?void 0:o.denyButtonTextColor)!=null?He:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let se=Ee("shield-x",14,(Se=o==null?void 0:o.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",j.appendChild(se));let Ie=document.createTextNode((ie=o==null?void 0:o.denyLabel)!=null?ie:"Deny");j.appendChild(Ie),X.append(re,j),u.appendChild(X)}return a.append(i,u),s.appendChild(a),s};var ef=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 pa=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 ua=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 mx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),fx=new Set(["step_start","execution_start"]),gx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),hx=new Set(["step_complete","agent_turn_complete"]),bx=new Set(["flow_complete","agent_complete"]),tf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),of=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),to=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Nr=(e,t)=>{let n=e[t];return of(n)?n:void 0};function jl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Oi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function yx(e,t){return typeof t.type=="string"?t.type:e}function vx(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 xx(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 nf(e){var o,r,s,a,i;let t=Nr(e,"result"),n=[Nr(e,"tokens"),Nr(e,"totalTokens"),t?Nr(t,"tokens"):void 0,Nr(e,"usage"),t?Nr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=to(d.output))!=null?o:to(d.outputTokens))!=null?r:to(d.completionTokens);if(l!==void 0)return l}return(i=(s=to(e.outputTokens))!=null?s:to(e.completionTokens))!=null?i:t?(a=to(t.outputTokens))!=null?a:to(t.completionTokens):void 0}function wx(e){var n,o,r,s,a;let t=Nr(e,"result");return(a=(r=(o=(n=to(e.executionTime))!=null?n:to(e.executionTimeMs))!=null?o:to(e.execution_time))!=null?r:to(e.duration))!=null?a:t?(s=to(t.executionTime))!=null?s:to(t.executionTimeMs):void 0}function Cx(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ma=class{constructor(t=Cx){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:Oi(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(!of(n)){tf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=yx(t,n),r=this.now();if(mx.has(o)){this.startRun(r);return}if(fx.has(o)){this.run||this.startRun(r);return}if(gx.has(o)){if(!xx(o,n))return;let a=vx(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+jl(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Oi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(hx.has(o)){if(!this.run)return;let a=this.run,i=nf(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+jl(a.visibleCharCount),f=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Oi(l,f),outputTokens:l,durationMs:f,source:d?"usage":"estimate"};return}if(bx.has(o)){if(!this.run)return;let a=this.run,i=nf(n),d=i!=null?i:a.exactOutputTokens+jl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",f=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Oi(d,f),outputTokens:d,durationMs:f,source:l},this.run=null;return}if(tf.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=wx(n);return s!=null?s:o-t.startedAt}};function hs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Sx={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)"}},Ax={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Tx=["flowName","stepName","reasoningText","text","name","tool","toolName"],kx=100;function Ex(e,t){let n={...Sx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Ax}function Mx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Lx(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 Ix(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 Rx(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 Px(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 Wx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Bx(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 Hx(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 Kl(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");hs(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 U,G;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"),E=Ee(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let L=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(U=o.timestampFormat)!=null?U:"relative";L.textContent=I==="relative"?Mx(e.timestamp,n):Lx(e.timestamp);let R=null;o.showSequenceNumbers!==!1&&(R=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(t+1));let H=Ex(e.type,o.badgeColors),P=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");P.style.backgroundColor=H.bg,P.style.color=H.text,P.style.borderColor=H.text+"50",P.textContent=e.type;let w=(G=o.descriptionFields)!=null?G:Tx,x=Ix(e.payload,w),k=null;x&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=x);let S=b("div","persona-flex-1 persona-min-w-0"),T=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),_=Ee("clipboard","12px","currentColor",1.5);return _&&T.appendChild(_),T.addEventListener("click",async ge=>{ge.stopPropagation(),await Rx(Px(e)),T.innerHTML="";let ue=Ee("check","12px","currentColor",1.5);ue&&T.appendChild(ue),setTimeout(()=>{T.innerHTML="";let ce=Ee("clipboard","12px","currentColor",1.5);ce&&T.appendChild(ce)},1500)}),C.appendChild(v),C.appendChild(L),R&&C.appendChild(R),C.appendChild(P),k&&C.appendChild(k),C.appendChild(S),C.appendChild(T),m.appendChild(C),d&&m.appendChild(Hx(e,a,i)),m}}function rf(e){var C,v,E,L,I;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(C=r==null?void 0:r.features)==null?void 0:C.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",f=(E=i==null?void 0:i.label)!=null?E:"",u=(I=(L=r==null?void 0:r.features)==null?void 0:L.eventStream)!=null?I:{},g=s.find(R=>R.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let R=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(R)return{element:R,update:()=>{},destroy:()=>{}}}return m();function m(){let R=u.classNames,H=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hs(H,R==null?void 0:R.panel);let P=[],w="",x="",k=null,S=[],T={},_=0,U=hi(),G=0,ge=0,ue=!1,ce=null,ke=!1,ve=0,He=new Set,Se=new Map,ie="",X="",re=null,be,he,j,se,Ie,ne=null,Z=null,oe=null;function at(){let Ce=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),le=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");hs(le,R==null?void 0:R.headerBar);let Ze=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ze.textContent="Events",be=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"),be.textContent="0",a){Z=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let wn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");wn.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",oe=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"),oe.style.display="none",oe.style.pointerEvents="none";let Cn=Z,bn=oe,Eo=()=>{if(!bn.textContent)return;let $n=Cn.getBoundingClientRect(),Un=Ce.getBoundingClientRect();bn.style.left=`${$n.left-Un.left}px`,bn.style.top=`${$n.bottom-Un.top+4}px`,bn.style.display="block"},St=()=>{bn.style.display="none"};Z.addEventListener("mouseenter",Eo),Z.addEventListener("mouseleave",St),Z.appendChild(wn),Z.appendChild(ne)}let Jt=b("div","persona-flex-1");he=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Kt=b("option","");Kt.value="",Kt.textContent="All events",he.appendChild(Kt),j=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"),j.type="button",j.title="Copy All";let yn=Ee("clipboard-copy","12px","currentColor",1.5);yn&&j.appendChild(yn);let ft=b("span","persona-text-xs");ft.textContent="Copy All",j.appendChild(ft),le.appendChild(Ze),le.appendChild(be),Z&&le.appendChild(Z),le.appendChild(Jt),le.appendChild(he),le.appendChild(j);let Mt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hs(Mt,R==null?void 0:R.searchBar);let Je=Ee("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Je&&zt.appendChild(Je),se=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),hs(se,R==null?void 0:R.searchInput),se.type="text",se.placeholder="Search event payloads...",Ie=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"),Ie.type="button",Ie.style.display="none";let an=Ee("x","12px","currentColor",2);return an&&Ie.appendChild(an),Mt.appendChild(zt),Mt.appendChild(se),Mt.appendChild(Ie),Ce.appendChild(le),Ce.appendChild(Mt),oe&&Ce.appendChild(oe),Ce}let it,Me=s.find(Ce=>Ce.renderEventStreamToolbar);if(Me!=null&&Me.renderEventStreamToolbar&&r){let Ce=Me.renderEventStreamToolbar({config:r,defaultRenderer:()=>at(),eventCount:t.getSize(),filteredCount:0,onFilterChange:le=>{w=le,sn(),D()},onSearchChange:le=>{x=le,sn(),D()}});it=Ce!=null?Ce:at()}else it=at();let de=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");de.style.display="none";function Xe(){if(!a||!ne||!Z)return;let Ce=a();ne.textContent=Wx(Ce);let le=Bx(Ce);oe&&(oe.textContent=le,le||(oe.style.display="none")),le?Z.setAttribute("aria-label",le):Z.removeAttribute("aria-label")}let We=b("div","persona-flex-1 persona-min-h-0 persona-relative"),q=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let me=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");hs(me,R==null?void 0:R.scrollIndicator),me.style.display="none",me.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let et=Ee(l,"14px","currentColor",2);et&&me.appendChild(et);let Et=b("span","");Et.textContent=f,me.appendChild(Et);let ee=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ee.style.display="none",We.appendChild(q),We.appendChild(ee),We.appendChild(me),H.setAttribute("tabindex","0"),H.appendChild(it),H.appendChild(de),H.appendChild(We);function ze(){let Ce=t.getAll(),le={};for(let ft of Ce)le[ft.type]=(le[ft.type]||0)+1;let Ze=Object.keys(le).sort(),Jt=Ze.length!==S.length||!Ze.every((ft,Mt)=>ft===S[Mt]),Kt=!Jt&&Ze.some(ft=>le[ft]!==T[ft]),Ln=Ce.length!==Object.values(T).reduce((ft,Mt)=>ft+Mt,0);if(!Jt&&!Kt&&!Ln||(S=Ze,T=le,!he))return;let yn=he.value;if(he.options[0].textContent="All events",Jt){for(;he.options.length>1;)he.remove(1);for(let ft of Ze){let Mt=b("option","");Mt.value=ft,Mt.textContent=`${ft} (${le[ft]||0})`,he.appendChild(Mt)}yn&&Ze.includes(yn)?he.value=yn:yn&&(he.value="",w="")}else for(let ft=1;ft<he.options.length;ft++){let Mt=he.options[ft];Mt.textContent=`${Mt.value} (${le[Mt.value]||0})`}}function Dn(){let Ce=t.getAll();if(w&&(Ce=Ce.filter(le=>le.type===w)),x){let le=x.toLowerCase();Ce=Ce.filter(Ze=>Ze.type.toLowerCase().includes(le)||Ze.payload.toLowerCase().includes(le))}return Ce}function Ht(){return w!==""||x!==""}function sn(){_=0,G=0,U.resume(),me.style.display="none"}function no(Ce){He.has(Ce)?He.delete(Ce):He.add(Ce),re=Ce;let le=q.scrollTop,Ze=U.isFollowing();ke=!0,U.pause(),D(),q.scrollTop=le,Ze&&U.resume(),ke=!1}function ko(){return Hr(q,50)}function D(){ge=Date.now(),ue=!1,Xe(),ze();let Ce=t.getEvictedCount();Ce>0?(de.textContent=`${Ce.toLocaleString()} older events truncated`,de.style.display=""):de.style.display="none",P=Dn();let le=P.length,Ze=t.getSize()>0;be&&(be.textContent=String(t.getSize())),le===0&&Ze&&Ht()?(ee.textContent=x?`No events matching '${x}'`:"No events matching filter",ee.style.display="",q.style.display="none"):(ee.style.display="none",q.style.display=""),j&&(j.title=Ht()?`Copy Filtered (${le})`:"Copy All"),d&&!U.isFollowing()&&le>_&&(G+=le-_,Et.textContent=f?`${f}${G>0?` (${G})`:""}`:"",me.style.display=""),_=le;let Jt=t.getAll(),Kt=Jt.length>0?Jt[0].timestamp:0,Ln=new Set(P.map(Mt=>Mt.id));for(let Mt of He)Ln.has(Mt)||He.delete(Mt);let yn=w!==ie||x!==X,ft=Se.size===0&&P.length>0;if(yn||ft||P.length===0){q.innerHTML="",Se.clear();let Mt=document.createDocumentFragment();for(let Je=0;Je<P.length;Je++){let zt=Kl(P[Je],Je,Kt,u,He,no,s,r);Se.set(P[Je].id,zt),Mt.appendChild(zt)}q.appendChild(Mt),ie=w,X=x,re=null}else{if(re!==null){let Je=Se.get(re);if(Je&&Je.parentNode===q){let zt=P.findIndex(an=>an.id===re);if(zt>=0){let an=Kl(P[zt],zt,Kt,u,He,no,s,r);q.insertBefore(an,Je),Je.remove(),Se.set(re,an)}}re=null}let Mt=new Set(P.map(Je=>Je.id));for(let[Je,zt]of Se)Mt.has(Je)||(zt.remove(),Se.delete(Je));for(let Je=0;Je<P.length;Je++){let zt=P[Je];if(!Se.has(zt.id)){let an=Kl(zt,Je,Kt,u,He,no,s,r);Se.set(zt.id,an),q.appendChild(an)}}}U.isFollowing()&&(q.scrollTop=q.scrollHeight)}function pe(){if(Date.now()-ge>=kx){ce!==null&&(cancelAnimationFrame(ce),ce=null),D();return}ue||(ue=!0,ce=requestAnimationFrame(()=>{ce=null,D()}))}let De=(Ce,le)=>{if(!j)return;j.innerHTML="";let Ze=Ee(Ce,"12px","currentColor",1.5);Ze&&j.appendChild(Ze);let Jt=b("span","persona-text-xs");Jt.textContent="Copy All",j.appendChild(Jt),setTimeout(()=>{j.innerHTML="";let Kt=Ee("clipboard-copy","12px","currentColor",1.5);Kt&&j.appendChild(Kt);let Ln=b("span","persona-text-xs");Ln.textContent="Copy All",j.appendChild(Ln),j.disabled=!1},le)},je=async()=>{if(j){j.disabled=!0;try{let Ce;Ht()?Ce=P:n?(Ce=await n(),Ce.length===0&&(Ce=t.getAll())):Ce=t.getAll();let le=Ce.map(Ze=>{try{return JSON.parse(Ze.payload)}catch{return Ze.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),De("check",1500)}catch{De("x",1500)}}},Ne=()=>{he&&(w=he.value,sn(),D())},Ve=()=>{!se||!Ie||(Ie.style.display=se.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=se.value,sn(),D()},150))},nt=()=>{!se||!Ie||(se.value="",x="",Ie.style.display="none",k&&clearTimeout(k),sn(),D())},Rt=()=>{if(ke)return;let Ce=q.scrollTop,{action:le,nextLastScrollTop:Ze}=bi({following:U.isFollowing(),currentScrollTop:Ce,lastScrollTop:ve,nearBottom:ko(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ve=Ze,le==="resume"?(U.resume(),G=0,me.style.display="none"):le==="pause"&&(U.pause(),d&&(Et.textContent=f,me.style.display=""))},jt=Ce=>{let le=yi({following:U.isFollowing(),deltaY:Ce.deltaY,nearBottom:ko(),resumeWhenNearBottom:!0});le==="pause"?(U.pause(),d&&(Et.textContent=f,me.style.display="")):le==="resume"&&(U.resume(),G=0,me.style.display="none")},Xt=()=>{d&&(q.scrollTop=q.scrollHeight,U.resume(),G=0,me.style.display="none")},K=Ce=>{let le=Ce.target;if(!le||le.closest("button"))return;let Ze=le.closest("[data-event-id]");if(!Ze)return;let Jt=Ze.getAttribute("data-event-id");Jt&&no(Jt)},vt=Ce=>{if((Ce.metaKey||Ce.ctrlKey)&&Ce.key==="f"){Ce.preventDefault(),se==null||se.focus(),se==null||se.select();return}Ce.key==="Escape"&&(se&&document.activeElement===se?(nt(),se.blur(),H.focus()):o&&o())};j&&j.addEventListener("click",je),he&&he.addEventListener("change",Ne),se&&se.addEventListener("input",Ve),Ie&&Ie.addEventListener("click",nt),q.addEventListener("scroll",Rt),q.addEventListener("wheel",jt,{passive:!0}),q.addEventListener("click",K),me.addEventListener("click",Xt),H.addEventListener("keydown",vt);function rt(){k&&clearTimeout(k),ce!==null&&(cancelAnimationFrame(ce),ce=null),ue=!1,Se.clear(),j&&j.removeEventListener("click",je),he&&he.removeEventListener("change",Ne),se&&se.removeEventListener("input",Ve),Ie&&Ie.removeEventListener("click",nt),q.removeEventListener("scroll",Rt),q.removeEventListener("wheel",jt),q.removeEventListener("click",K),me.removeEventListener("click",Xt),H.removeEventListener("keydown",vt)}return{element:H,update:pe,destroy:rt}}}function sf(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 af=(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:()=>sf(e,t)});if(f)return f}return sf(e,t)};var Gl=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)})}},_r=new Gl;_r.register("PersonaArtifactCard",af);function Dx(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 lf(e,t){var he,j,se,Ie;let n=(j=(he=e.features)==null?void 0:he.artifacts)==null?void 0:j.layout,r=((se=n==null?void 0:n.toolbarPreset)!=null?se:"default")==="document",s=(Ie=n==null?void 0:n.panePadding)==null?void 0:Ie.trim(),a=e.markdown?Qa(e.markdown):null,i=Za(e.sanitize),d=ne=>{let Z=a?a(ne):js(ne);return i?i(Z):Z},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"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var ne;f(),(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 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 ne;f(),(ne=t.onDismiss)==null||ne.call(t)});let v="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),L=r?Mn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Mn({icon:"eye",label:"Rendered view"}),I=r?Mn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Mn({icon:"code-2",label:"Source"}),R=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(P&&w&&w.length>0),k=null,S,T=null,_=null;if(r&&(H||P)&&!x){if(S=H?Wl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let ne=Ee("chevron-down",14,"currentColor",2);ne&&S.appendChild(ne)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=H?Wl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=Mn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(S,T)):r?S=Mn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Mn({icon:"copy",label:"Copy"});let U=r?Mn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Mn({icon:"refresh-cw",label:"Refresh"}),G=r?Mn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Mn({icon:"x",label:"Close"}),ge=()=>{var it,Me,de;let ne=(it=Se.find(Xe=>Xe.id===ie))!=null?it:Se[Se.length-1],Z=(Me=ne==null?void 0:ne.id)!=null?Me:null,oe=(ne==null?void 0:ne.artifactType)==="markdown"&&(de=ne.markdown)!=null?de:"",at=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:oe,jsonPayload:at,id:Z}},ue=async()=>{var it;let{markdown:ne,jsonPayload:Z}=ge(),oe=(it=Se.find(Me=>Me.id===ie))!=null?it:Se[Se.length-1],at=(oe==null?void 0:oe.artifactType)==="markdown"?ne:oe?Z:"";try{await navigator.clipboard.writeText(at)}catch{}};if(S.addEventListener("click",async()=>{let ne=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(ne&&x){let{markdown:Z,jsonPayload:oe,id:at}=ge();try{await ne({actionId:"primary",artifactId:at,markdown:Z,jsonPayload:oe})}catch{}return}await ue()}),T&&(w!=null&&w.length)){let ne=()=>{var oe;return(oe=u.closest("[data-persona-root]"))!=null?oe:document.body},Z=()=>{_=cs({items:w.map(oe=>({id:oe.id,label:oe.label})),onSelect:async oe=>{let{markdown:at,jsonPayload:it,id:Me}=ge(),de=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{de?await de({actionId:oe,artifactId:Me,markdown:at,jsonPayload:it}):oe==="markdown"||oe==="md"?await navigator.clipboard.writeText(at):oe==="json"||oe==="source"?await navigator.clipboard.writeText(it):await navigator.clipboard.writeText(at||it)}catch{}},anchor:k!=null?k:T,position:"bottom-right",portal:ne()})};u.isConnected?Z():requestAnimationFrame(Z),T.addEventListener("click",oe=>{oe.stopPropagation(),_==null||_.toggle()})}U.addEventListener("click",async()=>{var ne;try{await((ne=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:ne.call(n))}catch{}re()}),G.addEventListener("click",()=>{var ne;f(),(ne=t.onDismiss)==null||ne.call(t)});let ce=()=>{r&&(L.setAttribute("aria-pressed",v==="rendered"?"true":"false"),I.setAttribute("aria-pressed",v==="source"?"true":"false"))};L.addEventListener("click",()=>{v="rendered",ce(),re()}),I.addEventListener("click",()=>{v="source",ce(),re()});let ke=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(g.replaceChildren(),E.append(L,I),k?R.append(k,U,G):R.append(S,U,G),g.append(E,ke,R),ce()):(g.appendChild(m),g.appendChild(C)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let ve=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"),He=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ve.style.paddingLeft=s,ve.style.paddingRight=s,He.style.padding=s),u.appendChild(g),u.appendChild(ve),u.appendChild(He);let Se=[],ie=null,X=!1,re=()=>{var at,it,Me,de;let ne=r&&Se.length<=1;ve.classList.toggle("persona-hidden",ne),ve.replaceChildren();for(let Xe of Se){let We=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");We.type="button",We.textContent=Xe.title||Xe.id.slice(0,8),Xe.id===ie&&We.classList.add("persona-bg-persona-container","persona-border-persona-border"),We.addEventListener("click",()=>t.onSelect(Xe.id)),ve.appendChild(We)}He.replaceChildren();let Z=ie&&Se.find(Xe=>Xe.id===ie)||Se[Se.length-1];if(!Z)return;if(r){let Xe=Z.artifactType==="markdown"?"MD":(at=Z.component)!=null?at:"Component",q=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ke.textContent=`${q} \xB7 ${Xe}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(r&&v==="source"){let We=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");We.textContent=(it=Z.markdown)!=null?it:"",He.appendChild(We);return}let Xe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((Me=Z.markdown)!=null?Me:""),He.appendChild(Xe);return}let oe=Z.component?_r.get(Z.component):void 0;if(oe){let We={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let q=oe((de=Z.props)!=null?de:{},We);if(q){He.appendChild(q);return}}catch{}}He.appendChild(Dx(Z))},be=()=>{var Z;let ne=Se.length>0;if(u.classList.toggle("persona-hidden",!ne),l){let oe=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,it=((Z=oe==null?void 0:oe.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&it&&X?(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 Z,oe,at;Se=ne.artifacts,ie=(at=(oe=ne.selectedId)!=null?oe:(Z=ne.artifacts[ne.artifacts.length-1])==null?void 0:Z.id)!=null?at:null,Se.length>0&&(X=!0),re(),be()},setMobileOpen(ne){X=ne,!ne&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):be()}}}function ho(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function cf(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ho(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Fx(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 Ni(e,t){var d,l,f,u,g,m,C,v,E,L;if(!ho(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Fx(e),cf(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=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(L=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:L.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),cf(e,t)}var df=["panel","seamless"];function _i(e,t){var i,d,l,f,u,g;for(let m of df)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"),!ho(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=df.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 pf(e,t){var n,o,r;return!t||!ho(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function Ox(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 Nx(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 _x(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Vx(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function uf(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 mf(e,t,n,o,r,s){let a=Ox(r,200),i=Vx(t,n,o,200);i=Math.max(a,i);let d=Nx(s);return d!==null&&(i=Math.min(i,d)),_x(e,a,i)}var ff={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"}},Yl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var C,v,E;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=ff[a])!=null?v:ff.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let L=b("p","persona-text-sm persona-text-persona-muted");L.textContent=i.description,d.appendChild(L)}let f=document.createElement("form");f.className="persona-form-grid persona-space-y-3",i.fields.forEach(L=>{var w,x;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${L.name}`;let R=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=L.label,I.appendChild(R);let H=(w=L.type)!=null?w:"text",P;H==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=H),P.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",P.id=`${t.id}-${a}-${L.name}`,P.name=L.name,P.placeholder=(x=L.placeholder)!=null?x:"",L.required&&(P.required=!0),I.appendChild(P),f.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]"),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=(E=i.submitLabel)!=null?E:"Submit",u.appendChild(g),u.appendChild(m),f.appendChild(u),s.replaceChildren(d,f),f.addEventListener("submit",async L=>{var P,w;L.preventDefault();let I=(P=n.formEndpoint)!=null?P:"/form",R=new FormData(f),H={};R.forEach((x,k)=>{H[k]=x}),H.type=a,m.disabled=!0,g.textContent="Submitting\u2026";try{let x=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let k=await x.json();g.textContent=(w=k.message)!=null?w:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(x){g.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Xl=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()}},Jl=new Xl;var gf=()=>{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 $x=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Ux=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},Zl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=$x(e),n=Ux(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}},Ql=e=>typeof e=="string"?e:e==null?"":String(e),fa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ql(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Ql(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:Ql(n.text)}}},hf=e=>Array.isArray(e)?e.map(t=>String(t)):[],ec=e=>{let t=new Set(hf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(hf(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 zx=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}},qx=e=>e.map(t=>({...t,streaming:!1})),jx=e=>e.map(t=>({...t,status:"complete"})),bf=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?zx(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?qx(n.messages):void 0,artifacts:n.artifacts?jx(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as $0,STR as U0,OBJ as z0}from"partial-json";function yf(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=_r.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 vf(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 xf(e){let t=vf(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 wf(e){let t=vf(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 Kx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Cf(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=Kx}=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 E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let 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=`
23
+ `,n.addEventListener("click",t);let o=s=>{var W,H,R,w,C,k,A,S,_,V,K,fe,ue;let a=(W=s.launcher)!=null?W:{},i=Cn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ce=(H=a.title)!=null?H:"Chat Assistant";d.textContent=ce,d.setAttribute("title",ce)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ce=(R=a.subtitle)!=null?R:"Get answers fast";l.textContent=ce,l.setAttribute("title",ce)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let ce=(w=a.agentIconSize)!=null?w:"40px";if(g.style.height=ce,g.style.width=ce,g.innerHTML="",a.agentIconName){let ke=parseFloat(ce)||24,ve=Ee(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);ve?(g.appendChild(ve),g.style.display=""):(g.textContent=(C=a.agentIconText)!=null?C:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",g.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ce=(A=a.agentIconSize)!=null?A:"40px";f.style.height=ce,f.style.width=ce,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ce=(S=a.callToActionIconSize)!=null?S:"32px";m.style.height=ce,m.style.width=ce,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 ke=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ke=(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 ve=parseFloat(ce)||24,He=Math.max(ve-ke,8),Se=Ee(a.callToActionIconName,He,"currentColor",2);Se?m.appendChild(Se):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let x=a.position&&ko[a.position]?ko[a.position]:ko["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${v} ${x}`,i||(n.style.zIndex=String((K=a.zIndex)!=null?K:Ln));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(fe=a.border)!=null?fe:L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ue=a.collapsedMaxWidth)!=null?ue:"",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 ex="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Mi=(e,t={})=>{var v,E,L,I,W,H;let{showClose:n=!0,wrapperClassName:o=ex,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=r!=null?r:a.closeButtonSize)!=null?E:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(L=a.closeButtonTooltipText)!=null?L:"Close chat",g=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(W=a.closeButtonIconName)!=null?W:"x",m=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||Fn.actionIconColor;let x=Ee(f,s,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):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 R=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${R} 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),g&&u){let R=null,w=()=>{if(R)return;let k=l.ownerDocument,A=k.body;if(!A)return;R=Fo(k,"div","persona-clear-chat-tooltip"),R.textContent=u;let S=Fo(k,"div");S.className="persona-clear-chat-tooltip-arrow",R.appendChild(S);let _=l.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(hr),R.style.left=`${_.left+_.width/2}px`,R.style.top=`${_.top-8}px`,R.style.transform="translate(-50%, -100%)",A.appendChild(R)},C=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",C),l.addEventListener("focus",w),l.addEventListener("blur",C),d._cleanupTooltip=()=>{C(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",C),l.removeEventListener("focus",w),l.removeEventListener("blur",C)}}return{button:l,wrapper:d}},tx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Li=(e,t={})=>{var R,w,C,k,A,S,_,V,K,fe,ue,ce,ke;let{wrapperClassName:n=tx,buttonSize:o,iconSize:r="20px"}=t,a=(w=((R=e==null?void 0:e.launcher)!=null?R:{}).clearChat)!=null?w:{},i=(C=o!=null?o:a.size)!=null?C:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(A=a.iconColor)!=null?A:"",u=(S=a.backgroundColor)!=null?S:"",g=(_=a.borderWidth)!=null?_:"",f=(V=a.borderColor)!=null?V:"",m=(K=a.borderRadius)!=null?K:"",x=(fe=a.paddingX)!=null?fe:"",v=(ue=a.paddingY)!=null?ue:"",E=(ce=a.tooltipText)!=null?ce:"Clear chat",L=(ke=a.showTooltip)!=null?ke:!0,I=b("div",n),W=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");W.style.height=i,W.style.width=i,W.type="button",W.setAttribute("aria-label",E),W.style.color=l||Fn.actionIconColor;let H=Ee(d,r,"currentColor",1);if(H&&(H.style.display="block",W.appendChild(H)),u&&(W.style.backgroundColor=u,W.classList.remove("hover:persona-bg-gray-100")),g||f){let ve=g||"0px",He=f||"transparent";W.style.border=`${ve} solid ${He}`,W.classList.remove("persona-border-none")}if(m&&(W.style.borderRadius=m,W.classList.remove("persona-rounded-full")),x&&(W.style.paddingLeft=x,W.style.paddingRight=x),v&&(W.style.paddingTop=v,W.style.paddingBottom=v),I.appendChild(W),L&&E){let ve=null,He=()=>{if(ve)return;let ie=W.ownerDocument,X=ie.body;if(!X)return;ve=Fo(ie,"div","persona-clear-chat-tooltip"),ve.textContent=E;let re=Fo(ie,"div");re.className="persona-clear-chat-tooltip-arrow",ve.appendChild(re);let be=W.getBoundingClientRect();ve.style.position="fixed",ve.style.zIndex=String(hr),ve.style.left=`${be.left+be.width/2}px`,ve.style.top=`${be.top-8}px`,ve.style.transform="translate(-50%, -100%)",X.appendChild(ve)},Se=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};I.addEventListener("mouseenter",He),I.addEventListener("mouseleave",Se),W.addEventListener("focus",He),W.addEventListener("blur",Se),I._cleanupTooltip=()=>{Se(),I.removeEventListener("mouseenter",He),I.removeEventListener("mouseleave",Se),W.removeEventListener("focus",He),W.removeEventListener("blur",Se)}}return{button:W,wrapper:I}};var Fn={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 R,w,C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se;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=(R=t==null?void 0:t.launcher)!=null?R:{},s=(w=r.headerIconSize)!=null?w:"48px",a=(C=r.closeButtonPlacement)!=null?C:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ie=parseFloat(s)||24,X=Ee(d,ie*.6,"currentColor",1);X?l.replaceChildren(X):l.textContent=(S=(A=t==null?void 0:t.launcher)==null?void 0:A.agentIconText)!=null?S:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let ie=b("img");ie.src=t.launcher.iconUrl,ie.alt="",ie.className="persona-rounded-xl persona-object-cover",ie.style.height=s,ie.style.width=s,l.replaceChildren(ie)}else l.textContent=(K=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?K:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=b("span","persona-text-base persona-font-semibold");g.style.color=Fn.titleColor,g.textContent=(ue=(fe=t==null?void 0:t.launcher)==null?void 0:fe.title)!=null?ue:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Fn.subtitleColor,f.textContent=(ke=(ce=t==null?void 0:t.launcher)==null?void 0:ce.subtitle)!=null?ke:"Here to help you get answers fast",u.append(g,f),i?o.append(u):o.append(l,u);let m=(ve=r.clearChat)!=null?ve:{},x=(He=m.enabled)!=null?He:!0,v=(Se=m.placement)!=null?Se:"inline",E=null,L=null;if(x){let X=Li(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=X.button,L=X.wrapper,v==="top-right"&&(L.style.right="48px"),v==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:W,wrapper:H}=Mi(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(H),{header:o,iconHolder:l,headerTitle:g,headerSubtitle:f,closeButton:W,closeButtonWrapper:H,clearChatButton:E,clearChatButtonWrapper:L}},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 fs(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(hr)):(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 E=document.createElement("hr");a.appendChild(E)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let E=Ee(m.icon,16,"currentColor",1.5);E&&x.appendChild(E)}let v=document.createElement("span");v.textContent=m.label,x.appendChild(v),x.addEventListener("click",E=>{E.stopPropagation(),u(),n(m.id)}),a.appendChild(x)}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=x=>{!a.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function g(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:g,destroy:f}}function In(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ee(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,g]of Object.entries(i))d.setAttribute(u,g);return d}function ql(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let u=b("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let f=Ee(t,s!=null?s:14,"currentColor",2);f&&u.appendChild(f)}let g=b("span");if(g.textContent=n,u.appendChild(g),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function Xm(e){var m,x;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let u=b("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let g=Ee(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",l.appendChild(g)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=fs({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),r(v)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",v=>{v.stopPropagation();let E=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),f.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{u.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var nx=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 ox(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Ee(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=fs({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var rx=e=>{var I,W,H,R,w,C,k,A,S;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,u;if(d)l=Xm({label:(W=a.title)!=null?W:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Fn.titleColor,u=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Fn.titleColor,u.textContent=(R=a.title)!=null?R:"Chat Assistant",l.appendChild(u),ox(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 V=r.onTitleClick;l.addEventListener("click",K=>{K.target.closest("button")||V()}),l.addEventListener("keydown",K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),V())})}let _=r==null?void 0:r.titleRowHover;_&&(l.style.borderRadius=(C=_.borderRadius)!=null?C:"10px",l.style.padding=(k=_.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,K;l.style.backgroundColor=(V=_.background)!=null?V:"",l.style.borderColor=(K=_.border)!=null?K:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let g=(A=a.closeButtonSize)!=null?A:"32px",f=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=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Fn.actionIconColor;let x=(S=a.closeButtonIconName)!=null?S:"x",v=Ee(x,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",o&&m.addEventListener("click",o),f.appendChild(m),i.appendChild(f);let E=b("div");E.style.display="none";let L=b("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:u,headerSubtitle:L,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Qm={default:nx,minimal:rx},sx=e=>{var t;return(t=Qm[e])!=null?t:Qm.default},Ii=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=b("div");u.style.display="none";let g=b("span"),f=b("span"),m=b("button");m.style.display="none";let x=b("div");return x.style.display="none",{header:l,iconHolder:u,headerTitle:g,headerSubtitle:f,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=sx(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 Ri=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}},Pi=e=>{var R,w,C,k,A,S,_,V,K,fe,ue,ce;let t=(R=e==null?void 0:e.sendButton)!=null?R:{},n=(w=t.useIcon)!=null?w:!1,o=(C=t.iconText)!=null?C:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(A=t.tooltipText)!=null?A:"Send message",i=(S=t.stopTooltipText)!=null?S:"Stop generating",d=(V=(_=e==null?void 0:e.copy)==null?void 0:_.sendButtonLabel)!=null?V:"Send",l=(fe=(K=e==null?void 0:e.copy)==null?void 0:K.stopButtonLabel)!=null?fe:"Stop",u=(ue=t.showTooltip)!=null?ue:!1,g=(ce=t.size)!=null?ce:"40px",f=t.backgroundColor,m=t.textColor,x=b("div","persona-send-button-wrapper"),v=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let E=null,L=null;if(n){v.style.width=g,v.style.height=g,v.style.minWidth=g,v.style.minHeight=g,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 ke=parseFloat(g)||24,ve=(m==null?void 0:m.trim())||"currentColor";r?(E=Ee(r,ke,ve,2),E?v.appendChild(E):v.textContent=o):v.textContent=o,L=Ee(s,ke,ve,2),f?v.style.backgroundColor=f: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 I=null;u&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,x.appendChild(I)),v.setAttribute("aria-label",a),x.appendChild(v);let W="send";return{button:v,wrapper:x,setMode:ke=>{if(ke===W)return;W=ke;let ve=ke==="stop"?i:a;if(v.setAttribute("aria-label",ve),I&&(I.textContent=ve),n){if(E&&L){let He=ke==="stop"?L:E;v.replaceChildren(He)}}else v.textContent=ke==="stop"?l:d}}},Wi=e=>{var I,W,H,R,w,C,k,A,S,_,V,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=((W=t.provider)==null?void 0:W.type)==="runtype";if(!(o||r))return null;let a=(R=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?R:"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",u=(C=t.iconSize)!=null?C:a,g=parseFloat(u)||24,f=(A=t.backgroundColor)!=null?A:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,m=(_=t.iconColor)!=null?_:(S=e==null?void 0:e.sendButton)==null?void 0:S.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let v=Ee(l,g,m||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let E=(V=t.tooltipText)!=null?V:"Start voice recognition";if(((K=t.showTooltip)!=null?K:!1)&&E){let fe=b("div","persona-send-button-tooltip");fe.textContent=E,i.appendChild(fe)}return{button:d,wrapper:i}},Bi=e=>{var x,v,E,L,I,W,H,R;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((L=t.allowedTypes)!=null?L:Xo).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",(W=t.buttonTooltipText)!=null?W:"Attach file");let i=(H=t.buttonIconName)!=null?H:"paperclip",d=n,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let g=Ee(i,u,"currentColor",1.5);g?a.appendChild(g):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),r.click()}),s.appendChild(a);let f=(R=t.buttonTooltipText)!=null?R:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},Hi=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},Di=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Oi=e=>{var x,v,E,L,I,W;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=Di(),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}=Ri(t);a();let i=Pi(t),d=Wi(t),l=Bi(t),u=Hi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let g=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),g.append(f,m),r.append(g),r.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:g,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var Jm=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Ee("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Ee("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Zm=e=>{var x,v,E,L,I,W;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Di();o.style.display="none";let r=Hi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ri(t);s.style.maxHeight="100px",a();let i=Pi(t),d=Wi(t),l=Bi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=b("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let g=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&g.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(g,s,f),l&&n.append(l.previewsContainer),n.append(u,o,r);let m=u;return{footer:n,suggestions:o,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:r,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var eg=e=>{var u,g,f,m,x,v,E,L,I,W,H,R,w,C,k,A,S;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,n=Cn(e);if(pa(e)){let _=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},V=b("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(x=_.expandedSize)!=null?x:"anchored",V.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:Ln);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%",V.appendChild(K);let fe=b("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(L=_.expandedSize)!=null?L:"anchored",fe.style.zIndex=String((W=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?W:Ln),{wrapper:V,panel:K,pillRoot:fe}}if(n){let _=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(V),{wrapper:_,panel:V}}if(!t){let _=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),K=(R=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?R:"100%";return _.style.width=K,V.style.width="100%",_.appendChild(V),{wrapper:_,panel:V}}let r=(w=e==null?void 0:e.launcher)!=null?w:{},s=r.position&&ko[r.position]?ko[r.position]:ko["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?k:Ln);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(S=(A=e==null?void 0:e.launcher)==null?void 0:A.width)!=null?S:e==null?void 0:e.launcherWidth,l=d!=null?d:mo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},ax=(e,t)=>{var H,R,w,C,k,A,S,_,V;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Mi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(w=(R=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:R.enabled)!=null?w:!0,a=null,i=null;if(s){let K=Li(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"),l.style.setProperty("scrollbar-gutter","stable");let u=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let g=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");g.textContent=(k=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?k:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(S=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",u.append(g,f);let m=b("div","persona-flex persona-flex-col persona-gap-3"),x=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let E=b("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let L=Zm({config:e}),{root:I,textNode:W}=Jm();return n.append(d,r,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:g,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:W}},tg=(e,t=!0)=>{var E,L,I,W,H,R,w,C,k;if(pa(e))return ax(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(E=e==null?void 0:e.layout)==null?void 0:E.header,r=((L=e==null?void 0:e.layout)==null?void 0:L.showHeader)!==!1,s=o?Ii(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=Cn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(W=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?W:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(R=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",i.append(d,l);let u=b("div","persona-flex persona-flex-col persona-gap-3"),g=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((C=e==null?void 0:e.copy)==null?void 0:C.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=Oi({config:e}),x=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?ma(n,s,e):(s.header.style.display="none",ma(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",x||(m.footer.style.display="none"),n.append(m.footer),n.append(v),{container:n,body:a,messagesWrapper:u,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 ix=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}},lx=(e,t)=>{if(!e)return null;let n=ix(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},cx=(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},dx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},jl=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(":"))},Kl=320,og=320,px=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),ux=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),mx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),gx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),fx=(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 g;let l=b("img");l.alt=((g=i.alt)==null?void 0:g.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=`${Kl}px`,l.style.maxHeight=`${og}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,l.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{u=!0}),dx(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},hx=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(!jl(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=`${Kl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},bx=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(!jl(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=`${Kl}px`,r.style.maxHeight=`${og}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}},yx=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(!jl(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}},ga=()=>{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},vx=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ga};if(t){let r=t(o);if(r!==null)return r}return ga()},xx=(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},ng=(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},wx=(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},Cx=(e,t,n)=>{var m,x,v,E,L,I;let o=(m=t.showCopy)!=null?m:!0,r=(x=t.showUpvote)!=null?x:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let W=b("div");return W.style.display="none",W.id=`actions-${e.id}`,W.setAttribute("data-actions-for",e.id),W}let a=(E=t.visibility)!=null?E:"hover",i=(L=t.align)!=null?L:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(W,H,R)=>{let w=In({icon:W,label:H,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",R),w};return o&&g.appendChild(f("copy","Copy message","copy")),r&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Gl=(e,t,n,o,r,s)=>{var ie,X,re,be,he,j,se,Re,ne,Z,oe,at,it,Le,de,Xe,We;let a=n!=null?n:{},i=(ie=a.layout)!=null?ie:"bubble",d=a.avatar,l=a.timestamp,u=(X=d==null?void 0:d.show)!=null?X:!1,g=(re=l==null?void 0:l.show)!=null?re:!1,f=(be=d==null?void 0:d.position)!=null?be:"left",m=(he=l==null?void 0:l.position)!=null?he:"below",x=wx(e.role,i),v=b("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=px(e),L=(se=(j=e.content)==null?void 0:j.trim())!=null?se:"",W=E.length>0&&L===gi,H=Ti((ne=(Re=s==null?void 0:s.widgetConfig)==null?void 0:Re.features)==null?void 0:ne.streamAnimation),R=(at=(oe=(Z=s==null?void 0:s.widgetConfig)==null?void 0:Z.features)==null?void 0:oe.streamAnimation)==null?void 0:at.plugins,w=e.role==="assistant"&&H.type!=="none"?aa(H.type,R):null,C=e.role==="assistant"&&((it=w==null?void 0:w.isAnimating)==null?void 0:it.call(w,e))===!0,k=e.role==="assistant"&&w!==null&&(!!e.streaming||C);k&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let A=document.createElement("div");A.classList.add("persona-message-content"),k&&w&&(w.containerClass&&A.classList.add(w.containerClass),A.style.setProperty("--persona-stream-step",`${H.speed}ms`),A.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let S=k?ki((Le=e.content)!=null?Le:"",H.buffer,w,e,!!e.streaming):(de=e.content)!=null?de:"",_=t({text:S,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=_;k&&(w==null?void 0:w.wrap)==="char"?V=ia(_,"char",e.id,{skipTags:w.skipTags}):k&&(w==null?void 0:w.wrap)==="word"&&(V=ia(_,"word",e.id,{skipTags:w.skipTags}));let K=null;if(W?(K=document.createElement("div"),K.innerHTML=V,K.style.display="none",A.appendChild(K)):A.innerHTML=V,k&&(w!=null&&w.useCaret)&&!W&&L){let q=Ei(),me=A.querySelectorAll(".persona-stream-char, .persona-stream-word"),tt=me[me.length-1];if(tt!=null&&tt.parentNode)tt.parentNode.insertBefore(q,tt.nextSibling);else{let Tt=A.lastElementChild;Tt?Tt.appendChild(q):A.appendChild(q)}}if(g&&m==="inline"&&e.createdAt){let q=ng(e,l);q.classList.add("persona-ml-2","persona-inline"),A.appendChild(q)}if(E.length>0){let q=fx(E,!W&&!!L,()=>{W&&K&&(K.style.display="")});q?v.appendChild(q):W&&K&&(K.style.display="")}let fe=ux(e);if(fe.length>0){let q=hx(fe);q&&v.appendChild(q)}let ue=mx(e);if(ue.length>0){let q=bx(ue);q&&v.appendChild(q)}let ce=gx(e);if(ce.length>0){let q=yx(ce);q&&v.appendChild(q)}if(v.appendChild(A),g&&m==="below"&&e.createdAt){let q=ng(e,l);q.classList.add("persona-mt-1"),v.appendChild(q)}let ke=e.role==="assistant"?lx(e.stopReason,(We=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:We.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let q=!!(S&&S.trim()),me=H.placeholder==="skeleton",tt=me&&H.buffer==="line"&&q;if(q)tt&&v.appendChild(la());else if(me)v.appendChild(la());else{let Tt=vx("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Tt&&v.appendChild(Tt)}}if(ke&&e.stopReason&&!e.streaming&&(L||(A.style.display="none"),v.appendChild(cx(e.stopReason,ke))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let q=Cx(e,o,r);v.appendChild(q)}if(!u||e.role==="system")return v;let He=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Se=xx(d,e.role);return f==="right"||f==="left"&&e.role==="user"?He.append(v,Se):He.append(Se,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),He};var hs=new Set,Sx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ax=(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
+ `):""},rg=(e,t)=>{let n=hs.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ee(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Yl=(e,t)=>{var ue,ce,ke,ve,He,Se,ie,X,re,be,he;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(ce=(ue=t==null?void 0:t.features)==null?void 0:ue.reasoningDisplay)!=null?ce:{},s=r.expandable!==!1,a=s&&hs.has(e.id),i=n.status!=="complete",d=Ax(e,(ke=r.previewMaxLines)!=null?ke:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(ve=t==null?void 0:t.reasoning)!=null?ve:{},x=String((He=n.startedAt)!=null?He:Date.now()),v=()=>{let j=b("span","");return j.setAttribute("data-tool-elapsed",x),j.textContent=ci(n),j},E=(Se=m.renderCollapsedSummary)==null?void 0:Se.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ci(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(g.textContent=E,u.appendChild(g)):E instanceof HTMLElement?u.appendChild(E):(g.textContent=f,u.appendChild(g));let L=b("span","persona-text-xs persona-text-persona-primary");L.textContent=Sm(n),u.appendChild(L);let I=(ie=r.loadingAnimation)!=null?ie:"none",W=m.activeTextTemplate,H=m.completeTextTemplate,R=i?W:H,w=E instanceof HTMLElement,C=(j,se,Re)=>{let ne=Re;for(let Z of se){let oe=b("span","persona-tool-char");oe.style.setProperty("--char-index",String(ne)),oe.textContent=Z===" "?"\xA0":Z,j.appendChild(oe),ne++}return ne},k=(j,se)=>{g.textContent="";let Re=di(j,""),ne=0;for(let Z of Re){let oe=Z.styles.length>0?(()=>{let at=b("span",Z.styles.map(it=>`persona-tool-text-${it}`).join(" "));return g.appendChild(at),at})():g;if(Z.isDuration&&i)oe.appendChild(v());else{let at=Z.isDuration?ci(n):Z.text;se?ne=C(oe,at,ne):oe.appendChild(document.createTextNode(at))}}};if(!w&&R)if(L.style.display="none",g.style.display="",i&&I!=="none"){let j=(X=m.loadingAnimationDuration)!=null?X:2e3;g.setAttribute("data-preserve-animation","true"),I==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),k(R,!1)):(g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),k(R,!0))}else k(R,!1);else if(!w&&i&&I!=="none"){g.style.display="";let j=(re=m.loadingAnimationDuration)!=null?re:2e3;if(g.setAttribute("data-preserve-animation","true"),I==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let se=g.textContent||f;g.textContent="",C(g,se,0)}n.status==="complete"&&(g.style.display="none")}else w||(n.status==="complete"?g.style.display="none":g.style.display="");let A=null;if(s){A=b("div","persona-flex persona-items-center");let se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?A.appendChild(se):A.textContent=a?"Hide":"Show";let Re=b("div","persona-flex persona-items-center persona-ml-auto");Re.append(A),l.append(u,Re)}else l.append(u);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","reasoning"),S.style.display="none",S.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let j=(he=(be=t==null?void 0:t.reasoning)==null?void 0:be.renderCollapsedPreview)==null?void 0:he.call(be,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Sx(S,j)||(S.textContent=d),S.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,S),o;let _=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let V=n.chunks.join(""),K=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return K.textContent=V||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(K),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),A){A.innerHTML="";let se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?A.appendChild(se):A.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",S.style.display=a?"none":S.textContent||S.childNodes.length?"":"none"})(),o.append(l,S,_),o};var bs=new Set,Tx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),kx=(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=gs(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},Ex=(e,t)=>{var u,g,f,m,x;let n=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,r=(g=o==null?void 0:o.collapsedMode)!=null?g:"tool-call",s=kx(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Am(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=((x=n.name)==null?void 0:x.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Dl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Dl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},sg=(e,t,n)=>{var u;let o=bs.has(e),r=(u=n==null?void 0:n.toolCall)!=null?u:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let g=r.toggleTextColor||r.headerTextColor||"currentColor",f=Ee(o?"chevron-up":"chevron-down",16,g,2);f?l.appendChild(f):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Xl=(e,t)=>{var V,K,fe,ue,ce,ke,ve,He,Se;let n=e.toolCall,o=(V=t==null?void 0:t.toolCall)!=null?V:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(fe=(K=t==null?void 0:t.features)==null?void 0:K.toolCallDisplay)!=null?fe:{},a=s.expandable!==!1,i=a&&bs.has(e.id),{summary:d,previewText:l,isActive:u}=Ex(e,t),g=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");g.type="button",a&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let f=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 x=String((ue=n.startedAt)!=null?ue:Date.now()),v=()=>{let ie=b("span","");return ie.setAttribute("data-tool-elapsed",x),ie.textContent=Js(n),ie},E=(ke=o.renderCollapsedSummary)==null?void 0:ke.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ce=s.collapsedMode)!=null?ce:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Js(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(m.textContent=E,f.appendChild(m)):E instanceof HTMLElement?f.appendChild(E):(m.textContent=d,f.appendChild(m));let L=(ve=s.loadingAnimation)!=null?ve:"none",I=o.activeTextTemplate,W=o.completeTextTemplate,H=u?I:W,R=E instanceof HTMLElement,w=(ie,X,re)=>{let be=re;for(let he of X){let j=b("span","persona-tool-char");j.style.setProperty("--char-index",String(be)),j.textContent=he===" "?"\xA0":he,ie.appendChild(j),be++}return be},C=(ie,X)=>{var j;m.textContent="";let re=((j=n.name)==null?void 0:j.trim())||"tool",be=di(ie,re),he=0;for(let se of be){let Re=se.styles.length>0?(()=>{let ne=b("span",se.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(ne),ne})():m;if(se.isDuration&&u)Re.appendChild(v());else{let ne=se.isDuration?Js(n):se.text;X?he=w(Re,ne,he):Re.appendChild(document.createTextNode(ne))}}};if(!R)if(u&&L!=="none"){let ie=(He=o.loadingAnimationDuration)!=null?He:2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),H&&C(H,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),L==="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)),H)C(H,!0);else{let X=m.textContent||d;m.textContent="",w(m,X,0)}}else H&&C(H,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let ie=o.toggleTextColor||o.headerTextColor||"currentColor",X=Ee(i?"chevron-up":"chevron-down",16,ie,2);X?k.appendChild(X):k.textContent=i?"Hide":"Show";let re=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(k),g.append(f,re)}else g.append(f);let A=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(A.setAttribute("data-persona-collapsed-preview","tool"),A.style.display="none",A.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let ie=(Se=o.renderCollapsedPreview)==null?void 0:Se.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});Tx(A,ie)||(A.textContent=l),A.style.display=""}if(!i&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(g,A),r;let S=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(S.style.display=i?"":"none",o.contentBackgroundColor&&(S.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(S.style.color=o.contentTextColor),o.contentPaddingX&&(S.style.paddingLeft=o.contentPaddingX,S.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(S.style.paddingTop=o.contentPaddingY,S.style.paddingBottom=o.contentPaddingY),n.name){let ie=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ie.style.color=o.contentTextColor:o.headerTextColor&&(ie.style.color=o.headerTextColor),ie.textContent=n.name,S.appendChild(ie)}if(n.args!==void 0){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=gs(n.args),ie.append(X,re),S.appendChild(ie)}if(n.chunks&&n.chunks.length){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=n.chunks.join(""),ie.append(X,re),S.appendChild(ie)}if(n.status==="complete"&&n.result!==void 0){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=gs(n.result),ie.append(X,re),S.appendChild(ie)}if(n.status==="complete"&&typeof n.duration=="number"){let ie=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ie.style.color=o.contentTextColor),ie.textContent=`Duration: ${n.duration}ms`,S.appendChild(ie)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let ie=o.toggleTextColor||o.headerTextColor||"currentColor",X=Ee(i?"chevron-up":"chevron-down",16,ie,2);X?k.appendChild(X):k.textContent=i?"Hide":"Show"}S.style.display=i?"":"none",A.style.display=i?"none":A.textContent||A.childNodes.length?"":"none"})(),r.append(g,A,S),r};var Fi=new Map,Mx=e=>{let n=(e.startsWith(Br)?e.slice(Br.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)},ag=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,ig=(e,t)=>{var o,r,s;let n=(r=(o=ag(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Fi.get(e))!=null?s:n==="expanded"},lg=(e,t,n)=>{var a,i;let o=ag(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ee(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},cg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=ig(e,n);lg(o,s,n),r.style.display=s?"":"none"};var Ni=(e,t)=>{var C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se,ie;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(C=o==null?void 0:o.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(k=o==null?void 0:o.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=o==null?void 0:o.titleColor)!=null?A:"currentColor",u=Ee(d,20,l,2);u&&i.appendChild(u);let g=b("div","persona-flex-1 persona-min-w-0"),f=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=(S=o==null?void 0:o.title)!=null?S:"Approval Required",f.appendChild(m),!r){let X=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),f.appendChild(X)}g.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Br)?Tl(n.toolName):void 0,E=(_=o==null?void 0:o.formatDescription)==null?void 0:_.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,I=E||(L?n.description:`The assistant wants to use \u201C${v!=null?v:Mx(n.toolName)}\u201D.`),W=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(W.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(W.style.color=o.descriptionColor),W.textContent=I,g.appendChild(W),n.reason){let X=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?X.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(X.style.color=o.descriptionColor);let re=b("span","persona-font-medium");re.textContent=`${(V=o==null?void 0:o.reasonLabel)!=null?V:"Agent's stated reason:"} `,X.appendChild(re),X.appendChild(document.createTextNode(n.reason)),g.appendChild(X)}let H=(K=o==null?void 0:o.detailsDisplay)!=null?K:"collapsed",R=!!n.description&&!L,w=R||!!n.parameters;if(H!=="hidden"&&w){let X=ig(e.id,t),re=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");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(re.style.color=o.descriptionColor);let be=b("span");be.setAttribute("data-approval-details-label","true");let he=b("span","persona-inline-flex persona-items-center");he.setAttribute("data-approval-details-chevron","true"),re.append(be,he),lg(re,X,t),g.appendChild(re);let j=b("div");if(j.setAttribute("data-approval-details","true"),j.style.display=X?"":"none",R){let se=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor),se.textContent=n.description,j.appendChild(se)}if(n.parameters){let se=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&&(se.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(se.style.color=o.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=gs(n.parameters),j.appendChild(se)}g.appendChild(j)}if(r){let X=b("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let re=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");re.type="button",re.style.backgroundColor=(fe=o==null?void 0:o.approveButtonColor)!=null?fe:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(ue=o==null?void 0:o.approveButtonTextColor)!=null?ue:"#ffffff",re.setAttribute("data-approval-action","approve");let be=Ee("shield-check",14,(ce=o==null?void 0:o.approveButtonTextColor)!=null?ce:"#ffffff",2);be&&(be.style.marginRight="4px",re.appendChild(be));let he=document.createTextNode((ke=o==null?void 0:o.approveLabel)!=null?ke:"Approve");re.appendChild(he);let j=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");j.type="button",j.style.backgroundColor=(ve=o==null?void 0:o.denyButtonColor)!=null?ve:"transparent",j.style.color=(He=o==null?void 0:o.denyButtonTextColor)!=null?He:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let se=Ee("shield-x",14,(Se=o==null?void 0:o.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",j.appendChild(se));let Re=document.createTextNode((ie=o==null?void 0:o.denyLabel)!=null?ie:"Deny");j.appendChild(Re),X.append(re,j),g.appendChild(X)}return a.append(i,g),s.appendChild(a),s};var dg=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let u=(l==null?void 0:l.agentPushed)===!0;if(u||(n=null),!r||!r.length||!u&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let g=document.createDocumentFragment(),f=s?s.isStreaming():!1,m=x=>{switch(x){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'}};if(r.forEach(x=>{let v=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");v.type="button",v.textContent=x,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),s.sendMessage(x))}),g.appendChild(v),t.push(v)}),e.appendChild(g),u){let x=JSON.stringify(r);x!==n&&(n=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var fa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ha=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 Lx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ix=new Set(["step_start","execution_start"]),Rx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Px=new Set(["step_complete","agent_turn_complete"]),Wx=new Set(["flow_complete","agent_complete"]),pg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),mg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oo=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Vr=(e,t)=>{let n=e[t];return mg(n)?n:void 0};function Ql(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function _i(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Bx(e,t){return typeof t.type=="string"?t.type:e}function Hx(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 Dx(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 ug(e){var o,r,s,a,i;let t=Vr(e,"result"),n=[Vr(e,"tokens"),Vr(e,"totalTokens"),t?Vr(t,"tokens"):void 0,Vr(e,"usage"),t?Vr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=oo(d.output))!=null?o:oo(d.outputTokens))!=null?r:oo(d.completionTokens);if(l!==void 0)return l}return(i=(s=oo(e.outputTokens))!=null?s:oo(e.completionTokens))!=null?i:t?(a=oo(t.outputTokens))!=null?a:oo(t.completionTokens):void 0}function Ox(e){var n,o,r,s,a;let t=Vr(e,"result");return(a=(r=(o=(n=oo(e.executionTime))!=null?n:oo(e.executionTimeMs))!=null?o:oo(e.execution_time))!=null?r:oo(e.duration))!=null?a:t?(s=oo(t.executionTime))!=null?s:oo(t.executionTimeMs):void 0}function Fx(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ba=class{constructor(t=Fx){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:_i(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(!mg(n)){pg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Bx(t,n),r=this.now();if(Lx.has(o)){this.startRun(r);return}if(Ix.has(o)){this.run||this.startRun(r);return}if(Rx.has(o)){if(!Dx(o,n))return;let a=Hx(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+Ql(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:_i(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Px.has(o)){if(!this.run)return;let a=this.run,i=ug(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ql(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:_i(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Wx.has(o)){if(!this.run)return;let a=this.run,i=ug(n),d=i!=null?i:a.exactOutputTokens+Ql(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:_i(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(pg.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=Ox(n);return s!=null?s:o-t.startedAt}};function ys(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Nx={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)"}},_x={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Vx=["flowName","stepName","reasoningText","text","name","tool","toolName"],$x=100;function Ux(e,t){let n={...Nx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return _x}function zx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function qx(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 jx(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 Kx(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 Gx(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 Yx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Xx(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 Qx(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 Jl(e,t,n,o,r,s,a,i){var f;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");ys(l,(f=o.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>g(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(g()),l;function g(){var V,K;let m=b("div",""),x=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Ee(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let L=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(V=o.timestampFormat)!=null?V:"relative";L.textContent=I==="relative"?zx(e.timestamp,n):qx(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let H=Ux(e.type,o.badgeColors),R=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");R.style.backgroundColor=H.bg,R.style.color=H.text,R.style.borderColor=H.text+"50",R.textContent=e.type;let w=(K=o.descriptionFields)!=null?K:Vx,C=jx(e.payload,w),k=null;C&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=C);let A=b("div","persona-flex-1 persona-min-w-0"),S=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"),_=Ee("clipboard","12px","currentColor",1.5);return _&&S.appendChild(_),S.addEventListener("click",async fe=>{fe.stopPropagation(),await Kx(Gx(e)),S.innerHTML="";let ue=Ee("check","12px","currentColor",1.5);ue&&S.appendChild(ue),setTimeout(()=>{S.innerHTML="";let ce=Ee("clipboard","12px","currentColor",1.5);ce&&S.appendChild(ce)},1500)}),x.appendChild(v),x.appendChild(L),W&&x.appendChild(W),x.appendChild(R),k&&x.appendChild(k),x.appendChild(A),x.appendChild(S),m.appendChild(x),d&&m.appendChild(Qx(e,a,i)),m}}function gg(e){var x,v,E,L,I;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(x=r==null?void 0:r.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(E=i==null?void 0:i.label)!=null?E:"",g=(I=(L=r==null?void 0:r.features)==null?void 0:L.eventStream)!=null?I:{},f=s.find(W=>W.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let W=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(W)return{element:W,update:()=>{},destroy:()=>{}}}return m();function m(){let W=g.classNames,H=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ys(H,W==null?void 0:W.panel);let R=[],w="",C="",k=null,A=[],S={},_=0,V=Ci(),K=0,fe=0,ue=!1,ce=null,ke=!1,ve=0,He=new Set,Se=new Map,ie="",X="",re=null,be,he,j,se,Re,ne=null,Z=null,oe=null;function at(){let Ce=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),le=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");ys(le,W==null?void 0:W.headerBar);let Ze=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ze.textContent="Events",be=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"),be.textContent="0",a){Z=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let Sn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Sn.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",oe=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"),oe.style.display="none",oe.style.pointerEvents="none";let An=Z,bn=oe,Mo=()=>{if(!bn.textContent)return;let zn=An.getBoundingClientRect(),qn=Ce.getBoundingClientRect();bn.style.left=`${zn.left-qn.left}px`,bn.style.top=`${zn.bottom-qn.top+4}px`,bn.style.display="block"},Ct=()=>{bn.style.display="none"};Z.addEventListener("mouseenter",Mo),Z.addEventListener("mouseleave",Ct),Z.appendChild(Sn),Z.appendChild(ne)}let Zt=b("div","persona-flex-1");he=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let jt=b("option","");jt.value="",jt.textContent="All events",he.appendChild(jt),j=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"),j.type="button",j.title="Copy All";let xn=Ee("clipboard-copy","12px","currentColor",1.5);xn&&j.appendChild(xn);let ut=b("span","persona-text-xs");ut.textContent="Copy All",j.appendChild(ut),le.appendChild(Ze),le.appendChild(be),Z&&le.appendChild(Z),le.appendChild(Zt),le.appendChild(he),le.appendChild(j);let kt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ys(kt,W==null?void 0:W.searchBar);let Qe=Ee("search","14px","var(--persona-muted, #9ca3af)",1.5),Ut=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Qe&&Ut.appendChild(Qe),se=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ys(se,W==null?void 0:W.searchInput),se.type="text",se.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=Ee("x","12px","currentColor",2);return ln&&Re.appendChild(ln),kt.appendChild(Ut),kt.appendChild(se),kt.appendChild(Re),Ce.appendChild(le),Ce.appendChild(kt),oe&&Ce.appendChild(oe),Ce}let it,Le=s.find(Ce=>Ce.renderEventStreamToolbar);if(Le!=null&&Le.renderEventStreamToolbar&&r){let Ce=Le.renderEventStreamToolbar({config:r,defaultRenderer:()=>at(),eventCount:t.getSize(),filteredCount:0,onFilterChange:le=>{w=le,an(),D()},onSearchChange:le=>{C=le,an(),D()}});it=Ce!=null?Ce:at()}else it=at();let de=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");de.style.display="none";function Xe(){if(!a||!ne||!Z)return;let Ce=a();ne.textContent=Yx(Ce);let le=Xx(Ce);oe&&(oe.textContent=le,le||(oe.style.display="none")),le?Z.setAttribute("aria-label",le):Z.removeAttribute("aria-label")}let We=b("div","persona-flex-1 persona-min-h-0 persona-relative"),q=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let me=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");ys(me,W==null?void 0:W.scrollIndicator),me.style.display="none",me.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let tt=Ee(l,"14px","currentColor",2);tt&&me.appendChild(tt);let Tt=b("span","");Tt.textContent=u,me.appendChild(Tt);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",We.appendChild(q),We.appendChild(te),We.appendChild(me),H.setAttribute("tabindex","0"),H.appendChild(it),H.appendChild(de),H.appendChild(We);function ze(){let Ce=t.getAll(),le={};for(let ut of Ce)le[ut.type]=(le[ut.type]||0)+1;let Ze=Object.keys(le).sort(),Zt=Ze.length!==A.length||!Ze.every((ut,kt)=>ut===A[kt]),jt=!Zt&&Ze.some(ut=>le[ut]!==S[ut]),Rn=Ce.length!==Object.values(S).reduce((ut,kt)=>ut+kt,0);if(!Zt&&!jt&&!Rn||(A=Ze,S=le,!he))return;let xn=he.value;if(he.options[0].textContent="All events",Zt){for(;he.options.length>1;)he.remove(1);for(let ut of Ze){let kt=b("option","");kt.value=ut,kt.textContent=`${ut} (${le[ut]||0})`,he.appendChild(kt)}xn&&Ze.includes(xn)?he.value=xn:xn&&(he.value="",w="")}else for(let ut=1;ut<he.options.length;ut++){let kt=he.options[ut];kt.textContent=`${kt.value} (${le[kt.value]||0})`}}function Nn(){let Ce=t.getAll();if(w&&(Ce=Ce.filter(le=>le.type===w)),C){let le=C.toLowerCase();Ce=Ce.filter(Ze=>Ze.type.toLowerCase().includes(le)||Ze.payload.toLowerCase().includes(le))}return Ce}function Bt(){return w!==""||C!==""}function an(){_=0,K=0,V.resume(),me.style.display="none"}function ro(Ce){He.has(Ce)?He.delete(Ce):He.add(Ce),re=Ce;let le=q.scrollTop,Ze=V.isFollowing();ke=!0,V.pause(),D(),q.scrollTop=le,Ze&&V.resume(),ke=!1}function Eo(){return Nr(q,50)}function D(){fe=Date.now(),ue=!1,Xe(),ze();let Ce=t.getEvictedCount();Ce>0?(de.textContent=`${Ce.toLocaleString()} older events truncated`,de.style.display=""):de.style.display="none",R=Nn();let le=R.length,Ze=t.getSize()>0;be&&(be.textContent=String(t.getSize())),le===0&&Ze&&Bt()?(te.textContent=C?`No events matching '${C}'`:"No events matching filter",te.style.display="",q.style.display="none"):(te.style.display="none",q.style.display=""),j&&(j.title=Bt()?`Copy Filtered (${le})`:"Copy All"),d&&!V.isFollowing()&&le>_&&(K+=le-_,Tt.textContent=u?`${u}${K>0?` (${K})`:""}`:"",me.style.display=""),_=le;let Zt=t.getAll(),jt=Zt.length>0?Zt[0].timestamp:0,Rn=new Set(R.map(kt=>kt.id));for(let kt of He)Rn.has(kt)||He.delete(kt);let xn=w!==ie||C!==X,ut=Se.size===0&&R.length>0;if(xn||ut||R.length===0){q.innerHTML="",Se.clear();let kt=document.createDocumentFragment();for(let Qe=0;Qe<R.length;Qe++){let Ut=Jl(R[Qe],Qe,jt,g,He,ro,s,r);Se.set(R[Qe].id,Ut),kt.appendChild(Ut)}q.appendChild(kt),ie=w,X=C,re=null}else{if(re!==null){let Qe=Se.get(re);if(Qe&&Qe.parentNode===q){let Ut=R.findIndex(ln=>ln.id===re);if(Ut>=0){let ln=Jl(R[Ut],Ut,jt,g,He,ro,s,r);q.insertBefore(ln,Qe),Qe.remove(),Se.set(re,ln)}}re=null}let kt=new Set(R.map(Qe=>Qe.id));for(let[Qe,Ut]of Se)kt.has(Qe)||(Ut.remove(),Se.delete(Qe));for(let Qe=0;Qe<R.length;Qe++){let Ut=R[Qe];if(!Se.has(Ut.id)){let ln=Jl(Ut,Qe,jt,g,He,ro,s,r);Se.set(Ut.id,ln),q.appendChild(ln)}}}V.isFollowing()&&(q.scrollTop=q.scrollHeight)}function pe(){if(Date.now()-fe>=$x){ce!==null&&(cancelAnimationFrame(ce),ce=null),D();return}ue||(ue=!0,ce=requestAnimationFrame(()=>{ce=null,D()}))}let De=(Ce,le)=>{if(!j)return;j.innerHTML="";let Ze=Ee(Ce,"12px","currentColor",1.5);Ze&&j.appendChild(Ze);let Zt=b("span","persona-text-xs");Zt.textContent="Copy All",j.appendChild(Zt),setTimeout(()=>{j.innerHTML="";let jt=Ee("clipboard-copy","12px","currentColor",1.5);jt&&j.appendChild(jt);let Rn=b("span","persona-text-xs");Rn.textContent="Copy All",j.appendChild(Rn),j.disabled=!1},le)},Ke=async()=>{if(j){j.disabled=!0;try{let Ce;Bt()?Ce=R:n?(Ce=await n(),Ce.length===0&&(Ce=t.getAll())):Ce=t.getAll();let le=Ce.map(Ze=>{try{return JSON.parse(Ze.payload)}catch{return Ze.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),De("check",1500)}catch{De("x",1500)}}},Ne=()=>{he&&(w=he.value,an(),D())},Ve=()=>{!se||!Re||(Re.style.display=se.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{C=se.value,an(),D()},150))},ot=()=>{!se||!Re||(se.value="",C="",Re.style.display="none",k&&clearTimeout(k),an(),D())},It=()=>{if(ke)return;let Ce=q.scrollTop,{action:le,nextLastScrollTop:Ze}=Si({following:V.isFollowing(),currentScrollTop:Ce,lastScrollTop:ve,nearBottom:Eo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ve=Ze,le==="resume"?(V.resume(),K=0,me.style.display="none"):le==="pause"&&(V.pause(),d&&(Tt.textContent=u,me.style.display=""))},qt=Ce=>{let le=Ai({following:V.isFollowing(),deltaY:Ce.deltaY,nearBottom:Eo(),resumeWhenNearBottom:!0});le==="pause"?(V.pause(),d&&(Tt.textContent=u,me.style.display="")):le==="resume"&&(V.resume(),K=0,me.style.display="none")},Qt=()=>{d&&(q.scrollTop=q.scrollHeight,V.resume(),K=0,me.style.display="none")},G=Ce=>{let le=Ce.target;if(!le||le.closest("button"))return;let Ze=le.closest("[data-event-id]");if(!Ze)return;let Zt=Ze.getAttribute("data-event-id");Zt&&ro(Zt)},yt=Ce=>{if((Ce.metaKey||Ce.ctrlKey)&&Ce.key==="f"){Ce.preventDefault(),se==null||se.focus(),se==null||se.select();return}Ce.key==="Escape"&&(se&&document.activeElement===se?(ot(),se.blur(),H.focus()):o&&o())};j&&j.addEventListener("click",Ke),he&&he.addEventListener("change",Ne),se&&se.addEventListener("input",Ve),Re&&Re.addEventListener("click",ot),q.addEventListener("scroll",It),q.addEventListener("wheel",qt,{passive:!0}),q.addEventListener("click",G),me.addEventListener("click",Qt),H.addEventListener("keydown",yt);function st(){k&&clearTimeout(k),ce!==null&&(cancelAnimationFrame(ce),ce=null),ue=!1,Se.clear(),j&&j.removeEventListener("click",Ke),he&&he.removeEventListener("change",Ne),se&&se.removeEventListener("input",Ve),Re&&Re.removeEventListener("click",ot),q.removeEventListener("scroll",It),q.removeEventListener("wheel",qt),q.removeEventListener("click",G),me.removeEventListener("click",Qt),H.removeEventListener("keydown",yt)}return{element:H,update:pe,destroy:st}}}function fg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,g.appendChild(m)}else g.textContent=a;if(l.append(u,g),i.append(d,l),r==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",o),i.append(f)}return i}var hg=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>fg(e,t)});if(u)return u}return fg(e,t)};var Zl=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)})}},$r=new Zl;$r.register("PersonaArtifactCard",hg);function Jx(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 bg(e,t){var he,j,se,Re;let n=(j=(he=e.features)==null?void 0:he.artifacts)==null?void 0:j.layout,r=((se=n==null?void 0:n.toolbarPreset)!=null?se:"default")==="document",s=(Re=n==null?void 0:n.panePadding)==null?void 0:Re.trim(),a=e.markdown?ti(e.markdown):null,i=ni(e.sanitize),d=ne=>{let Z=a?a(ne):Ks(ne);return i?i(Z):Z},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let g=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");g.setAttribute("data-persona-theme-zone","artifact-pane"),r&&g.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&f.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let v="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),L=r?In({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):In({icon:"eye",label:"Rendered view"}),I=r?In({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):In({icon:"code-2",label:"Source"}),W=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,R=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,C=!!(R&&w&&w.length>0),k=null,A,S=null,_=null;if(r&&(H||R)&&!C){if(A=H?ql({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):In({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let ne=Ee("chevron-down",14,"currentColor",2);ne&&A.appendChild(ne)}}else r&&C?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),A=H?ql({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):In({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S=In({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(A,S)):r?A=In({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):A=In({icon:"copy",label:"Copy"});let V=r?In({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):In({icon:"refresh-cw",label:"Refresh"}),K=r?In({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):In({icon:"x",label:"Close"}),fe=()=>{var it,Le,de;let ne=(it=Se.find(Xe=>Xe.id===ie))!=null?it:Se[Se.length-1],Z=(Le=ne==null?void 0:ne.id)!=null?Le:null,oe=(ne==null?void 0:ne.artifactType)==="markdown"&&(de=ne.markdown)!=null?de:"",at=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:oe,jsonPayload:at,id:Z}},ue=async()=>{var it;let{markdown:ne,jsonPayload:Z}=fe(),oe=(it=Se.find(Le=>Le.id===ie))!=null?it:Se[Se.length-1],at=(oe==null?void 0:oe.artifactType)==="markdown"?ne:oe?Z:"";try{await navigator.clipboard.writeText(at)}catch{}};if(A.addEventListener("click",async()=>{let ne=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(ne&&C){let{markdown:Z,jsonPayload:oe,id:at}=fe();try{await ne({actionId:"primary",artifactId:at,markdown:Z,jsonPayload:oe})}catch{}return}await ue()}),S&&(w!=null&&w.length)){let ne=()=>{var oe;return(oe=g.closest("[data-persona-root]"))!=null?oe:document.body},Z=()=>{_=fs({items:w.map(oe=>({id:oe.id,label:oe.label})),onSelect:async oe=>{let{markdown:at,jsonPayload:it,id:Le}=fe(),de=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{de?await de({actionId:oe,artifactId:Le,markdown:at,jsonPayload:it}):oe==="markdown"||oe==="md"?await navigator.clipboard.writeText(at):oe==="json"||oe==="source"?await navigator.clipboard.writeText(it):await navigator.clipboard.writeText(at||it)}catch{}},anchor:k!=null?k:S,position:"bottom-right",portal:ne()})};g.isConnected?Z():requestAnimationFrame(Z),S.addEventListener("click",oe=>{oe.stopPropagation(),_==null||_.toggle()})}V.addEventListener("click",async()=>{var ne;try{await((ne=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:ne.call(n))}catch{}re()}),K.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let ce=()=>{r&&(L.setAttribute("aria-pressed",v==="rendered"?"true":"false"),I.setAttribute("aria-pressed",v==="source"?"true":"false"))};L.addEventListener("click",()=>{v="rendered",ce(),re()}),I.addEventListener("click",()=>{v="source",ce(),re()});let ke=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(f.replaceChildren(),E.append(L,I),k?W.append(k,V,K):W.append(A,V,K),f.append(E,ke,W),ce()):(f.appendChild(m),f.appendChild(x)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let ve=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"),He=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ve.style.paddingLeft=s,ve.style.paddingRight=s,He.style.padding=s),g.appendChild(f),g.appendChild(ve),g.appendChild(He);let Se=[],ie=null,X=!1,re=()=>{var at,it,Le,de;let ne=r&&Se.length<=1;ve.classList.toggle("persona-hidden",ne),ve.replaceChildren();for(let Xe of Se){let We=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");We.type="button",We.textContent=Xe.title||Xe.id.slice(0,8),Xe.id===ie&&We.classList.add("persona-bg-persona-container","persona-border-persona-border"),We.addEventListener("click",()=>t.onSelect(Xe.id)),ve.appendChild(We)}He.replaceChildren();let Z=ie&&Se.find(Xe=>Xe.id===ie)||Se[Se.length-1];if(!Z)return;if(r){let Xe=Z.artifactType==="markdown"?"MD":(at=Z.component)!=null?at:"Component",q=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ke.textContent=`${q} \xB7 ${Xe}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(r&&v==="source"){let We=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");We.textContent=(it=Z.markdown)!=null?it:"",He.appendChild(We);return}let Xe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((Le=Z.markdown)!=null?Le:""),He.appendChild(Xe);return}let oe=Z.component?$r.get(Z.component):void 0;if(oe){let We={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let q=oe((de=Z.props)!=null?de:{},We);if(q){He.appendChild(q);return}}catch{}}He.appendChild(Jx(Z))},be=()=>{var Z;let ne=Se.length>0;if(g.classList.toggle("persona-hidden",!ne),l){let oe=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,it=((Z=oe==null?void 0:oe.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&it&&X?(l.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:l,update(ne){var Z,oe,at;Se=ne.artifacts,ie=(at=(oe=ne.selectedId)!=null?oe:(Z=ne.artifacts[ne.artifacts.length-1])==null?void 0:Z.id)!=null?at:null,Se.length>0&&(X=!0),re(),be()},setMobileOpen(ne){X=ne,!ne&&l?(l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):be()}}}function fo(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 yg(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"),!fo(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 Zx(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 Vi(e,t){var d,l,u,g,f,m,x,v,E,L;if(!fo(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"),Zx(e),yg(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(g=n==null?void 0:n.paneWidth)!=null?g:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(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=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(L=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:L.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),yg(e,t)}var vg=["panel","seamless"];function $i(e,t){var i,d,l,u,g,f;for(let m of vg)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"),!fo(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=vg.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(g=n==null?void 0:n.paneShadow)==null?void 0:g.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=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function xg(e,t){var n,o,r;return!t||!fo(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function ew(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 tw(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 nw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ow(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function wg(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 Cg(e,t,n,o,r,s){let a=ew(r,200),i=ow(t,n,o,200);i=Math.max(a,i);let d=tw(s);return d!==null&&(i=Math.min(i,d)),nw(e,a,i)}var Sg={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"}},ec=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var x,v,E;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(v=Sg[a])!=null?v:Sg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let L=b("p","persona-text-sm persona-text-persona-muted");L.textContent=i.description,d.appendChild(L)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(L=>{var w,C;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${L.name}`;let W=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");W.textContent=L.label,I.appendChild(W);let H=(w=L.type)!=null?w:"text",R;H==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=H),R.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",R.id=`${t.id}-${a}-${L.name}`,R.name=L.name,R.placeholder=(C=L.placeholder)!=null?C:"",L.required&&(R.required=!0),I.appendChild(R),u.appendChild(I)});let g=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),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=(E=i.submitLabel)!=null?E:"Submit",g.appendChild(f),g.appendChild(m),u.appendChild(g),s.replaceChildren(d,u),u.addEventListener("submit",async L=>{var R,w;L.preventDefault();let I=(R=n.formEndpoint)!=null?R:"/form",W=new FormData(u),H={};W.forEach((C,k)=>{H[k]=C}),H.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let C=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!C.ok)throw new Error(`Form submission failed (${C.status})`);let k=await C.json();f.textContent=(w=k.message)!=null?w:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(C){f.textContent=C instanceof Error?C.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var tc=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()}},nc=new tc;var Ag=()=>{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 rw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},sw=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},rc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=rw(e),n=sw(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}},oc=e=>typeof e=="string"?e:e==null?"":String(e),ya={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:oc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=oc(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:oc(n.text)}}},Tg=e=>Array.isArray(e)?e.map(t=>String(t)):[],sc=e=>{let t=new Set(Tg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Tg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},g=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let f=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:f,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var aw=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}},iw=e=>e.map(t=>({...t,streaming:!1})),lw=e=>e.map(t=>({...t,status:"complete"})),kg=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?aw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?iw(n.messages):void 0,artifacts:n.artifacts?lw(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as mA,STR as gA,OBJ as fA}from"partial-json";function Eg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=$r.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 Mg(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 Lg(e){let t=Mg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Ig(e){let t=Mg(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 cw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rg(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=cw}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,m.appendChild(v),f.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let w=1;w<=5;w++){let C=document.createElement("button");C.type="button",C.className="persona-feedback-rating-btn persona-feedback-star-btn",C.setAttribute("role","radio"),C.setAttribute("aria-checked","false"),C.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),C.title=l[w-1],C.dataset.rating=String(w),C.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=w,L.forEach((k,S)=>{let T=S<w;k.classList.toggle("selected",T),k.setAttribute("aria-checked",S===w-1?"true":"false")})}),L.push(x),E.appendChild(x)}g.appendChild(E);let I=null;if(d){let w=document.createElement("div");w.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"),w.appendChild(I),g.appendChild(w)}let R=document.createElement("div");R.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{n==null||n(),f.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let w=(I==null?void 0:I.value.trim())||void 0;await t(u,w),f.remove()}catch(w){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),R.appendChild(H),R.appendChild(P),g.appendChild(R),f.appendChild(g),f}function Sf(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 E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,C.appendChild(E),m.appendChild(C);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=f,I.appendChild(R),I.appendChild(H);let P=document.createElement("div");P.className="persona-feedback-numbers";let w=[];for(let _=0;_<=10;_++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${_} out of 10`),U.textContent=String(_),U.dataset.rating=String(_),_<=6?U.classList.add("persona-feedback-detractor"):_<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{g=_,w.forEach((G,ge)=>{G.classList.toggle("selected",ge===_),G.setAttribute("aria-checked",ge===_?"true":"false")})}),w.push(U),P.appendChild(U)}L.appendChild(I),L.appendChild(P),m.appendChild(L);let x=null;if(d){let _=document.createElement("div");_.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"),_.appendChild(x),m.appendChild(_)}let k=document.createElement("div");k.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),u.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(g===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let _=(x==null?void 0:x.value.trim())||void 0;await t(g,_),u.remove()}catch(_){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),k.appendChild(S),k.appendChild(T),m.appendChild(k),u.appendChild(m),u}var bs="persona-chat-history",Gx=30*1e3,Yx={"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 Xx(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=Yx[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 Vi(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 Jx(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 Qx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var tc=e=>!e||typeof e!="object"?{}:{...e},Af=e=>e.map(t=>({...t,streaming:!1})),Tf=(e,t,n)=>{let o=e!=null&&e.markdown?Qa(e.markdown):null,r=Za(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=js(a),r?r(d):d}};function kf(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=Ee(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 Ef=(e,t,n)=>{var Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Jc,Qc,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=Mu(t),r=Jl.getForInstance(o.plugins);o.components&&_r.registerAll(o.components);let s=gf(),i=o.persistState===!1?null:(Rc=o.storageAdapter)!=null?Rc:bf(),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=tc(h.metadata)),(Pc=h.messages)!=null&&Pc.length&&(o={...o,initialMessages:h.messages}),(Wc=h.artifacts)!=null&&Wc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Bc=h.selectedArtifactId)!=null?Bc: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:{}});(Hc=c.messages)!=null&&Hc.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:{},Gr()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zl],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[fa.message,fa.messageAndClick],E=ec({parsers:C,handlers:v,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let L=(Fc=(Dc=o.launcher)==null?void 0:Dc.enabled)!=null?Fc:!0,I=(Nc=(Oc=o.launcher)==null?void 0:Oc.autoExpand)!=null?Nc:!1,R=(_c=o.autoFocusInput)!=null?_c:!1,H=I,P=L,w=($c=(Vc=o.layout)==null?void 0:Vc.header)==null?void 0:$c.layout,x=!1,k=()=>aa(o),S=()=>L||k(),T=k()?!1:L?I:!0,_=!1,U=null,G=()=>{_=!0,U&&clearTimeout(U),U=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},ge=Tf(o,E,G),ue=(zc=(Uc=o.features)==null?void 0:Uc.showReasoning)!=null?zc:!0,ce=(jc=(qc=o.features)==null?void 0:qc.showToolCalls)!=null?jc:!0,ke=(Gc=(Kc=o.features)==null?void 0:Kc.showEventStreamToggle)!=null?Gc:!1,ve=(Xc=(Yc=o.features)==null?void 0:Yc.scrollToBottom)!=null?Xc:{},He=(Qc=(Jc=o.features)==null?void 0:Jc.scrollBehavior)!=null?Qc:{},ie=`${(ed=typeof o.persistState=="object"?(Zc=o.persistState)==null?void 0:Zc.keyPrefix:void 0)!=null?ed:"persona-"}event-stream`,X=ke?new ua(ie):null,re=(od=(nd=(td=o.features)==null?void 0:td.eventStream)==null?void 0:nd.maxEvents)!=null?od:2e3,be=ke?new pa(re,X):null,he=ke?new ma:null,j=null,se=!1,Ie=null,ne=0;X==null||X.open().then(()=>be==null?void 0:be.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Z={onCopy:c=>{var p,h;s.emit("message:copy",c),V!=null&&V.isClientTokenMode()&&V.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onCopy)==null||h.call(p,c)},onFeedback:c=>{var p,h;s.emit("message:feedback",c),V!=null&&V.isClientTokenMode()&&V.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,c)}},oe=(rd=o.statusIndicator)!=null?rd:{},at=c=>{var p,h,y,M;return c==="idle"?(p=oe.idleText)!=null?p:kn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:kn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:kn.connected:c==="error"?(M=oe.errorText)!=null?M:kn.error:kn[c]};function it(c,p,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let M=document.createElement("a");M.href=h.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=p,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=p}let{wrapper:Me,panel:de,pillRoot:Xe}=Wm(o),We=Bm(o,S()),{container:q,body:me,messagesWrapper:et,suggestions:Et,textarea:ee,sendButton:ze,sendButtonWrapper:Dn,composerForm:Ht,statusText:sn,introTitle:no,introSubtitle:ko,closeButton:D,iconHolder:pe,headerTitle:De,headerSubtitle:je,header:Ne,footer:Ve,actionsRow:nt,leftActions:Rt,rightActions:jt}=We,Xt=We.setSendButtonMode,K=We.micButton,vt=We.micButtonWrapper,rt=We.attachmentButton,Ce=We.attachmentButtonWrapper,le=We.attachmentInput,Ze=We.attachmentPreviewsContainer;q.classList.add("persona-relative"),me.classList.add("persona-relative");let Jt=12,Kt=()=>{var c;return(c=ve.label)!=null?c:""},Ln=()=>{var c;return(c=ve.iconName)!=null?c:"arrow-down"},yn=()=>ve.enabled!==!1,ft=()=>{var c;return(c=He.mode)!=null?c:"follow"},Mt=()=>{var c;return(c=He.anchorTopOffset)!=null?c:16},Je=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");Je.type="button",Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom","true");let zt=b("span","persona-flex persona-items-center"),an=b("span",""),wn=b("span","");wn.setAttribute("data-persona-scroll-to-bottom-count",""),wn.style.display="none",Je.append(zt,an,wn),q.appendChild(Je);let Cn=b("div","persona-stream-anchor-spacer");Cn.setAttribute("aria-hidden","true"),Cn.setAttribute("data-persona-anchor-spacer",""),Cn.style.flexShrink="0",Cn.style.pointerEvents="none",Cn.style.height="0px",me.appendChild(Cn);let bn=()=>{let p=Ve.style.display==="none"?0:Ve.offsetHeight;Je.style.bottom=`${p+Jt}px`};bn();let Eo=()=>{let c=!!Kt();Je.setAttribute("aria-label",Kt()||"Jump to latest"),Je.title=Kt(),Je.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),zt.innerHTML="";let p=Ee(Ln(),"14px","currentColor",2);p?(zt.appendChild(p),zt.style.display=""):zt.style.display="none",an.textContent=Kt(),an.style.display=c?"":"none"};Eo();let St=null,$n=null,Un=r.find(c=>c.renderHeader);if(Un!=null&&Un.renderHeader){let c=Un.renderHeader({config:o,defaultRenderer:()=>{let p=Dr({config:o,showClose:S()});return la(q,p,o),p.header},onClose:()=>Ft(!1,"user")});if(c){let p=q.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(c),Ne=c)}}let No=()=>{var p,h,y,M;if(!be)return;if(se=!0,!j&&be&&(j=rf({buffer:be,getFullHistory:()=>be.getAllFromStore(),onClose:()=>bo(),config:o,plugins:r,getThroughput:()=>{var O;return(O=he==null?void 0:he.getMetric())!=null?O:{status:"idle"}}})),j&&(me.style.display="none",(p=Ve.parentNode)==null||p.insertBefore(j.element,Ve),j.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${Hn.actionIconColor}`;let O=(M=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:M.toggleButtonActive;O&&O.split(/\s+/).forEach(N=>N&&xt.classList.add(N))}let c=()=>{if(!se)return;let O=Date.now();O-ne>=200&&(j==null||j.update(),ne=O),Ie=requestAnimationFrame(c)};ne=0,Ie=requestAnimationFrame(c),Nn(),s.emit("eventStream:opened",{timestamp:Date.now()})},bo=()=>{var c,p,h;if(se){if(se=!1,j&&j.element.remove(),me.style.display="",xt){xt.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(M=>M&&xt.classList.remove(M))}Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),Nn(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(ke){let c=(ad=(sd=o.features)==null?void 0:sd.eventStream)==null?void 0:ad.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:"");xt=b("button",p),xt.style.width="28px",xt.style.height="28px",xt.style.color=Hn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let h=Ee("activity","18px","currentColor",1.5);h&&xt.appendChild(h);let y=We.clearChatButtonWrapper,M=We.closeButtonWrapper,O=y||M;O&&O.parentNode===Ne?Ne.insertBefore(xt,O):Ne.appendChild(xt),xt.addEventListener("click",()=>{se?bo():No()})}let br=c=>{var y,M,O;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 N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(h,N):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=b("input");N.type="file",N.accept=((y=p.allowedTypes)!=null?y:Yo).join(","),N.multiple=((M=p.maxFiles)!=null?M:4)>1,N.style.display="none",N.setAttribute("aria-label",(O=p.buttonTooltipText)!=null?O:"Attach files"),c.appendChild(N)}},Mo=r.find(c=>c.renderComposer);if(Mo!=null&&Mo.renderComposer){let c=o.composer,p=Mo.renderComposer({config:o,defaultRenderer:()=>Pi({config:o}).footer,onSubmit:h=>{var N;if(!V||V.isStreaming())return;let y=h.trim(),M=(N=St==null?void 0:St.hasAttachments())!=null?N:!1;if(!y&&!M)return;A();let O;M&&(O=[],O.push(...St.getContentParts()),y&&O.push(kl(y))),V.sendMessage(y,{contentParts:O}),M&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{le==null||le.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?()=>{$n==null||$n()}:void 0});p&&(Ve.replaceWith(p),Ve=p)}let yr=c=>{let p=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),O=c.querySelector("[data-persona-composer-status]");p&&(Ht=p),h&&(ee=h),y&&(ze=y),M&&(K=M,vt=M.parentElement),O&&(sn=O);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Et=N);let z=c.querySelector(".persona-attachment-button");z&&(rt=z,Ce=z.parentElement),le=c.querySelector('input[type="file"]'),Ze=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(nt=F)};br(Ve),yr(Ve);let Fn=(ud=(ld=o.layout)==null?void 0:ld.contentMaxWidth)!=null?ud:k()?(pd=(dd=(cd=o.launcher)==null?void 0:cd.composerBar)==null?void 0:dd.contentMaxWidth)!=null?pd:"720px":void 0;if(Fn&&(et.style.maxWidth=Fn,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%"),Fn&&Ht&&!k()&&(Ht.style.maxWidth=Fn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Fn&&Et&&!k()&&(Et.style.maxWidth=Fn,Et.style.marginLeft="auto",Et.style.marginRight="auto"),Fn&&Ze&&!k()&&(Ze.style.maxWidth=Fn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),(md=o.attachments)!=null&&md.enabled&&le&&Ze){St=ea.fromConfig(o.attachments),St.setPreviewsContainer(Ze),le.addEventListener("change",h=>{let y=h.target;St==null||St.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,p=kf(c);q.appendChild(p)}(()=>{var y,M;let c=(M=(y=o.layout)==null?void 0:y.slots)!=null?M:{},p=O=>{switch(O){case"body-top":return q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return et;case"footer-top":return Et;case"composer":return Ht;case"footer-bottom":return sn;default:return null}},h=(O,N)=>{var z;switch(O){case"header-left":case"header-center":case"header-right":if(O==="header-left")Ne.insertBefore(N,Ne.firstChild);else if(O==="header-right")Ne.appendChild(N);else{let F=Ne.querySelector(".persona-flex-col");F?(z=F.parentNode)==null||z.insertBefore(N,F.nextSibling):Ne.appendChild(N)}break;case"body-top":{let F=me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(N):me.insertBefore(N,me.firstChild);break}case"body-bottom":me.appendChild(N);break;case"footer-top":Et.replaceWith(N);break;case"footer-bottom":sn.replaceWith(N);break;default:break}};for(let[O,N]of Object.entries(c))if(N)try{let z=N({config:o,defaultContent:()=>p(O)});z&&h(O,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${O}":`,z)}})();let Qo=c=>{var N,z;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let O=h.getAttribute("data-bubble-type");if(O==="reasoning")ds.has(M)?ds.delete(M):ds.add(M),Fm(M,y);else if(O==="tool")ps.has(M)?ps.delete(M):ps.add(M),Om(M,y,o);else if(O==="approval"){let F=o.approval!==!1?o.approval:void 0,we=((N=F==null?void 0:F.detailsDisplay)!=null?N:"collapsed")==="expanded",fe=(z=Di.get(M))!=null?z:we;Di.set(M,!fe),Zm(M,y,o)}Uo.delete(M)};et.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qo(c))}),et.addEventListener("keydown",c=>{let p=c.target;(c.key==="Enter"||c.key===" ")&&p.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qo(c))});let _o=new Map;et.addEventListener("click",c=>{var N;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let M=y.getAttribute("data-actions-for");if(!M)return;let O=h.getAttribute("data-action");if(O==="copy"){let F=V.getMessages().find(we=>we.id===M);if(F&&Z.onCopy){let we=F.content||"";navigator.clipboard.writeText(we).then(()=>{h.classList.add("persona-message-action-success");let fe=Ee("check",14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let te=Ee("copy",14,"currentColor",2);te&&(h.innerHTML="",h.appendChild(te))},2e3)}).catch(fe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",fe)}),Z.onCopy(F)}}else if(O==="upvote"||O==="downvote"){let F=((N=_o.get(M))!=null?N:null)===O,we=O==="upvote"?"thumbs-up":"thumbs-down";if(F){_o.delete(M),h.classList.remove("persona-message-action-active");let fe=Ee(we,14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe))}else{let fe=O==="upvote"?"downvote":"upvote",te=y.querySelector(`[data-action="${fe}"]`);if(te){te.classList.remove("persona-message-action-active");let qe=Ee(fe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(te.innerHTML="",te.appendChild(qe))}_o.set(M,O),h.classList.add("persona-message-action-active");let Te=Ee(we,14,"currentColor",2);Te&&(Te.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Te)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=V.getMessages().find(tt=>tt.id===M);Ae&&Z.onFeedback&&Z.onFeedback({type:O,messageId:Ae.id,message:Ae})}}}),et.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let O=h.getAttribute("data-approval-action");if(!O)return;let N=O==="approve"?"approved":"denied",F=V.getMessages().find(fe=>fe.id===M);if(!(F!=null&&F.approval))return;let we=y.querySelector("[data-approval-buttons]");we&&we.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?V.resolveWebMcpApproval(M,N):V.resolveApproval(F.approval,N)});let At=null,zn=null,qn={artifacts:[],selectedId:null},In=!1,It={current:null};et.addEventListener("click",c=>{var te,Te,_e,Ae,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((_e=(Te=(te=o.features)==null?void 0:te.artifacts)==null?void 0:Te.onArtifactAction)==null?void 0:_e.call(Te,{type:"download",artifactId:y}))===!0)return;let O=V.getArtifactById(y),N=O==null?void 0:O.markdown,z=(O==null?void 0:O.title)||"artifact";if(!N){let qe=h.closest("[data-open-artifact]"),ct=qe==null?void 0:qe.closest("[data-message-id]"),dt=ct==null?void 0:ct.getAttribute("data-message-id");if(dt){let Le=V.getMessages().find(Ue=>Ue.id===dt);if(Le!=null&&Le.rawContent)try{let Ue=JSON.parse(Le.rawContent);N=(Ae=Ue==null?void 0:Ue.props)==null?void 0:Ae.markdown,z=((tt=Ue==null?void 0:Ue.props)==null?void 0:tt.title)||z}catch{}}}if(!N)return;let F=new Blob([N],{type:"text/markdown"}),we=URL.createObjectURL(F),fe=document.createElement("a");fe.href=we,fe.download=`${z}.md`,fe.click(),URL.revokeObjectURL(we)}),et.addEventListener("click",c=>{var O,N,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(N=(O=o.features)==null?void 0:O.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:z.call(N,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),In=!1,V.selectArtifact(y),Gn())}),et.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let p=c.target;p.hasAttribute("data-open-artifact")&&(c.preventDefault(),p.click())});let oo=We.composerOverlay,ro=(c,p,h)=>{var z,F,we,fe;let y=p.trim();if(!y||!It.current)return;let M=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",O=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:y,answers:h.structured,values:(F=h.values)!=null?F:h.source==="multi"?y.split(", "):[y],isFreeText:O,source:h.source},bubbles:!0,composed:!0})),gs(oo,M);let N=It.current.getMessages().find(te=>{var Te;return((Te=te.toolCall)==null?void 0:Te.id)===M});(we=N==null?void 0:N.agentMetadata)!=null&&we.awaitingLocalTool?It.current.resolveAskUserQuestion(N,(fe=h.structured)!=null?fe:y):It.current.sendMessage(y)},jn=c=>{var M;let p=It.current;if(!p)return;let h=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",y=p.getMessages().find(O=>{var N;return((N=O.toolCall)==null?void 0:N.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:Wi(c,y),currentIndex:go(c)})},Zo=c=>Object.entries(c).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Vo=c=>{var M,O,N;if(((O=(M=o.features)==null?void 0:M.askUserQuestion)==null?void 0:O.groupedAutoAdvance)===!1)return;let p=go(c),h=fs(c);if(p>=h-1)return;let y=(N=It.current)==null?void 0:N.getMessages().find(z=>{var F;return((F=z.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});y&&(Hi(c,y,o,p+1),jn(c))};oo.addEventListener("click",c=>{var O,N,z,F,we,fe,te,Te,_e,Ae,tt,qe,ct,dt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let M=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Pe=(O=y.getAttribute("data-tool-call-id"))!=null?O:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),gs(oo,Pe);let Le=(N=It.current)==null?void 0:N.getMessages().find(Ue=>{var Ge;return((Ge=Ue.toolCall)==null?void 0:Ge.id)===Pe});(z=Le==null?void 0:Le.agentMetadata)!=null&&z.awaitingLocalTool&&((F=It.current)==null||F.markAskUserQuestionResolved(Le),(we=It.current)==null||we.resolveAskUserQuestion(Le,"(dismissed)"));return}if(M==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Le=y.getAttribute("data-multi-select")==="true",Ue=gr(y);if(Ue&&Le){let Ge=Or(y)[go(y)],wt=new Set(Array.isArray(Ge)?Ge:[]);wt.has(Pe)?wt.delete(Pe):wt.add(Pe),hr(y,Array.from(wt)),jn(y);return}if(Ue){hr(y,Pe),jn(y),Vo(y);return}if(Le){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let wt=y.querySelector('[data-ask-user-action="submit-multi"]');wt&&(wt.disabled=ql(y).length===0);return}ro(y,Pe,{source:"pick",values:[Pe]});return}if(M==="submit-multi"){let Pe=ql(y);if(Pe.length===0)return;ro(y,Pe.join(", "),{source:"multi",values:Pe});return}if(M==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Le=Pe.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(M==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(M==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Le=(fe=Pe==null?void 0:Pe.value)!=null?fe:"";if(!Le.trim())return;if(gr(y)){hr(y,Le.trim()),jn(y),Vo(y);return}ro(y,Le,{source:"free-text"});return}if(M==="next"||M==="back"){if(!It.current)return;let Pe=(te=y.getAttribute("data-tool-call-id"))!=null?te:"",Le=It.current.getMessages().find(Be=>{var Fe;return((Fe=Be.toolCall)==null?void 0:Fe.id)===Pe});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(_e=(Te=Ue==null?void 0:Ue.value)==null?void 0:Te.trim())!=null?_e:"";if(Ge){let Be=Or(y)[go(y)];(typeof Be!="string"||Be!==Ge)&&hr(y,Ge)}let wt=M==="next"?1:-1,B=go(y)+wt;Hi(y,Le,o,B),jn(y);return}if(M==="submit-all"){if(!It.current)return;let Pe=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",Le=It.current.getMessages().find(Be=>{var Fe;return((Fe=Be.toolCall)==null?void 0:Fe.id)===Pe});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(qe=(tt=Ue==null?void 0:Ue.value)==null?void 0:tt.trim())!=null?qe:"";Ge&&hr(y,Ge);let wt=Wi(y,Le);It.current.persistAskUserQuestionProgress(Le,{answers:wt,currentIndex:go(y)});let B=Zo(wt);ro(y,B||"(submitted)",{source:"submit-all",structured:wt});return}if(M==="skip"){if(!It.current)return;let Pe=(ct=y.getAttribute("data-tool-call-id"))!=null?ct:"",Le=It.current.getMessages().find(Fe=>{var ye;return((ye=Fe.toolCall)==null?void 0:ye.id)===Pe});if(!Le)return;let Ue=gr(y),Ge=go(y),wt=fs(y),B=Ge>=wt-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),gs(oo,Pe),(dt=Le.agentMetadata)!=null&&dt.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Le),It.current.resolveAskUserQuestion(Le,"(dismissed)"));return}hr(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),B){let Fe=Wi(y,Le),ye=Zo(Fe);ro(y,ye||"(skipped)",{source:"submit-all",structured:Fe});return}Hi(y,Le,o,Ge+1),jn(y);return}}),oo.addEventListener("keydown",c=>{var O;if(c.key!=="Enter")return;let h=c.target;if(!((O=h.matches)!=null&&O.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let M=h.value;if(M.trim()){if(gr(y)){hr(y,M.trim()),jn(y),Vo(y);return}ro(y,M,{source:"free-text"})}});let er=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=oo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),O=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];O&&(c.preventDefault(),O.click())};document.addEventListener("keydown",er);let Kn=null,Dt=null,Rn=null,so=null,tr=()=>{};function $o(){so==null||so(),so=null}let nr=()=>{var N;if(!Kn||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Dt.style.removeProperty("position"),Dt.style.removeProperty("left"),Dt.style.removeProperty("top"),Dt.style.removeProperty("bottom"),Dt.style.removeProperty("width"),Dt.style.removeProperty("z-index");return}let y=Kn.firstElementChild;if(!y||y===Dt)return;let M=10;Dt.style.position="absolute",Dt.style.top="0",Dt.style.bottom="0",Dt.style.width=`${M}px`,Dt.style.zIndex="5";let O=y.offsetWidth-M/2;Dt.style.left=`${Math.max(0,O)}px`},Lo=()=>{},Gn=()=>{var h,y,M,O,N;if(!At||!ho(o))return;Ni(e,o),_i(e,o),Lo();let c=(O=(M=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:M.narrowHostMaxWidth)!=null?O:520,p=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=c),At.update(qn),In?(At.setMobileOpen(!1),At.element.classList.add("persona-hidden"),(N=At.backdrop)==null||N.classList.add("persona-hidden")):qn.artifacts.length>0&&(At.element.classList.remove("persona-hidden"),At.setMobileOpen(!0)),tr()};if(ho(o)){de.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(q),At=lf(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{In=!0,Gn()}}),At.element.classList.add("persona-hidden"),Kn=p,p.appendChild(c),p.appendChild(At.element),At.backdrop&&de.appendChild(At.backdrop),de.appendChild(p),tr=()=>{var y,M,O,N;if(!Kn||!At)return;if(!(((O=(M=(y=o.features)==null?void 0:y.artifacts)==null?void 0:M.layout)==null?void 0:O.resizable)===!0)){Rn==null||Rn(),Rn=null,$o(),Dt&&(Dt.remove(),Dt=null),At.element.style.removeProperty("width"),At.element.style.removeProperty("maxWidth");return}if(!Dt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let F=e.ownerDocument,we=(N=F.defaultView)!=null?N:window,fe=te=>{var ct,dt;if(!At||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||we.innerWidth<=640)return;te.preventDefault(),$o();let Te=te.clientX,_e=At.element.getBoundingClientRect().width,Ae=(dt=(ct=o.features)==null?void 0:ct.artifacts)==null?void 0:dt.layout,tt=Pe=>{let Le=Kn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Ge=Ue?0:uf(Kn,we),wt=Ue?0:z.getBoundingClientRect().width||6,B=_e-(Pe.clientX-Te),Be=mf(B,Le,Ge,wt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);At.element.style.width=`${Be}px`,At.element.style.maxWidth="none",nr()},qe=()=>{F.removeEventListener("pointermove",tt),F.removeEventListener("pointerup",qe),F.removeEventListener("pointercancel",qe),so=null;try{z.releasePointerCapture(te.pointerId)}catch{}};so=qe,F.addEventListener("pointermove",tt),F.addEventListener("pointerup",qe),F.addEventListener("pointercancel",qe);try{z.setPointerCapture(te.pointerId)}catch{}};z.addEventListener("pointerdown",fe),Dt=z,Kn.insertBefore(z,At.element),Rn=()=>{z.removeEventListener("pointerdown",fe)}}if(Dt){let z=qn.artifacts.length>0&&!In;Dt.classList.toggle("persona-hidden",!z),nr()}},Lo=()=>{var we,fe,te,Te,_e,Ae,tt,qe,ct,dt,Pe,Le,Ue,Ge;if(!L||!At||((fe=(we=o.launcher)==null?void 0:we.sidebarMode)!=null?fe:!1)||xn(o)&&Oo(o).reveal==="emerge")return;let y=(te=e.ownerDocument.defaultView)!=null?te:window,M=(_e=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?_e:!0,O=(tt=(Ae=o.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?tt:640;if(M&&y.innerWidth<=O||!pf(o,L))return;let N=(dt=(ct=(qe=o.launcher)==null?void 0:qe.width)!=null?ct:o.launcherWidth)!=null?dt:fo,z=(Ge=(Ue=(Le=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Le.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";qn.artifacts.length>0&&!In?(de.style.width=z,de.style.maxWidth=z):(de.style.width=N,de.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(zn=new ResizeObserver(()=>{Gn()}),zn.observe(de))}else de.appendChild(q),k()&&Xe&&(We.peekBanner&&Xe.appendChild(We.peekBanner),Xe.appendChild(Ve));e.appendChild(Me),Xe&&e.appendChild(Xe);let yo=()=>{var Be,Fe,ye,_t,Ot,Gt,Ct,qt,Qn,on,Ye,Pt,cn,uo,Zn,Sr,Ar,es,ts,Yt,Tr,pr,ur,Go,ot,vn,Pn,rn;if(k()){de.style.width="100%",de.style.maxWidth="100%";let pt=(Fe=(Be=o.launcher)==null?void 0:Be.composerBar)!=null?Fe:{},bt=Me.dataset.state==="expanded",ut=(ye=pt.expandedSize)!=null?ye:"anchored";if(!(bt&&ut!=="fullscreen")){q.style.background="",q.style.border="",q.style.borderRadius="",q.style.overflow="",q.style.boxShadow="";return}let dn=(Ot=(_t=o.theme)==null?void 0:_t.components)==null?void 0:Ot.panel,Ho=Oa(o),pn=(Er,Da)=>{var Ns;return Er==null||Er===""?Da:(Ns=ns(Ho,Er))!=null?Ns:Er},Wn="1px solid var(--persona-border)",mo="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",kr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";q.style.background="var(--persona-surface, #ffffff)",q.style.border=pn(dn==null?void 0:dn.border,Wn),q.style.borderRadius=pn(dn==null?void 0:dn.borderRadius,kr),q.style.boxShadow=pn(dn==null?void 0:dn.shadow,mo),q.style.overflow="hidden";return}let c=xn(o),p=(Ct=(Gt=o.launcher)==null?void 0:Gt.sidebarMode)!=null?Ct:!1,h=c||p||((Qn=(qt=o.launcher)==null?void 0:qt.fullHeight)!=null?Qn:!1),y=((on=o.launcher)==null?void 0:on.enabled)===!1,M=(Pt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Pt.panel,O=Oa(o),N=(pt,bt)=>{var ut;return pt==null||pt===""?bt:(ut=ns(O,pt))!=null?ut:pt},z=(cn=e.ownerDocument.defaultView)!=null?cn:window,F=(Zn=(uo=o.launcher)==null?void 0:uo.mobileFullscreen)!=null?Zn:!0,we=(Ar=(Sr=o.launcher)==null?void 0:Sr.mobileBreakpoint)!=null?Ar:640,fe=z.innerWidth<=we,te=F&&fe&&L,Te=(ts=(es=o.launcher)==null?void 0:es.position)!=null?ts:"bottom-left",_e=Te==="bottom-left"||Te==="top-left",Ae=(Tr=(Yt=o.launcher)==null?void 0:Yt.zIndex)!=null?Tr:En,tt=p||te?"none":"1px solid var(--persona-border)",qe=te?"none":p?_e?"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&&!te&&(qe="none",tt="none");let ct=p||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=N(M==null?void 0:M.border,tt),Pe=N(M==null?void 0:M.shadow,qe),Le=N(M==null?void 0:M.borderRadius,ct),Ue=me.scrollTop;e.style.cssText="",Me.style.cssText="",de.style.cssText="",q.style.cssText="",me.style.cssText="",Ve.style.cssText="";let Ge=()=>{var bt;if(Ue<=0)return;((bt=me.ownerDocument.defaultView)!=null?bt:window).requestAnimationFrame(()=>{if(me.scrollTop===Ue)return;let ut=me.scrollHeight-me.clientHeight;ut<=0||(me.scrollTop=Math.min(Ue,ut))})};if(te){Me.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"),Me.style.cssText=`
30
+ `,C.addEventListener("click",()=>{g=w,L.forEach((k,A)=>{let S=A<w;k.classList.toggle("selected",S),k.setAttribute("aria-checked",A===w-1?"true":"false")})}),L.push(C),E.appendChild(C)}f.appendChild(E);let I=null;if(d){let w=document.createElement("div");w.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"),w.appendChild(I),f.appendChild(w)}let W=document.createElement("div");W.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{n==null||n(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(g===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let w=(I==null?void 0:I.value.trim())||void 0;await t(g,w),u.remove()}catch(w){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),W.appendChild(H),W.appendChild(R),f.appendChild(W),u.appendChild(f),u}function Pg(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,x.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,x.appendChild(E),m.appendChild(x);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let W=document.createElement("span");W.className="persona-feedback-label-low",W.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=u,I.appendChild(W),I.appendChild(H);let R=document.createElement("div");R.className="persona-feedback-numbers";let w=[];for(let _=0;_<=10;_++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${_} out of 10`),V.textContent=String(_),V.dataset.rating=String(_),_<=6?V.classList.add("persona-feedback-detractor"):_<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=_,w.forEach((K,fe)=>{K.classList.toggle("selected",fe===_),K.setAttribute("aria-checked",fe===_?"true":"false")})}),w.push(V),R.appendChild(V)}L.appendChild(I),L.appendChild(R),m.appendChild(L);let C=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",C=document.createElement("textarea"),C.className="persona-feedback-comment",C.placeholder=s,C.rows=3,C.setAttribute("aria-label","Additional comments"),_.appendChild(C),m.appendChild(_)}let k=document.createElement("div");k.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{n==null||n(),g.remove()});let S=document.createElement("button");return S.type="button",S.className="persona-feedback-btn persona-feedback-btn-submit",S.textContent=a,S.addEventListener("click",async()=>{if(f===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let _=(C==null?void 0:C.value.trim())||void 0;await t(f,_),g.remove()}catch(_){S.disabled=!1,S.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),k.appendChild(A),k.appendChild(S),m.appendChild(k),g.appendChild(m),g}var vs="persona-chat-history",dw=30*1e3,pw={"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 uw(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=pw[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 Ui(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 mw(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 gw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var ac=e=>!e||typeof e!="object"?{}:{...e},Wg=e=>e.map(t=>({...t,streaming:!1})),Bg=(e,t,n)=>{let o=e!=null&&e.markdown?ti(e.markdown):null,r=ni(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,u,g;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""}):o?d=o(a):d=Ks(a),r?r(d):d}};function Hg(e){var i,d,l,u;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=Ee(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let g=b("span","persona-drop-overlay-label");g.textContent=e.label,t.appendChild(g)}return t}var Dg=(e,t,n)=>{var Dc,Oc,Fc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Wu(t),r=nc.getForInstance(o.plugins);o.components&&$r.registerAll(o.components);let s=Ag(),i=o.persistState===!1?null:(Dc=o.storageAdapter)!=null?Dc:kg(),d={},l=null,u=!1,g=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&&(u=!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 g(h)});else{let p=c!=null?c:{messages:[],metadata:{}},h=g(p);h.metadata&&(d=ac(h.metadata)),(Oc=h.messages)!=null&&Oc.length&&(o={...o,initialMessages:h.messages}),(Fc=h.artifacts)!=null&&Fc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Nc=h.selectedArtifactId)!=null?Nc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=g({messages:[],metadata:{}});(_c=c.messages)!=null&&_c.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var h;d=(h=c({...d}))!=null?h:{},Qr()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[rc],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ya.message,ya.messageAndClick],E=sc({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let L=($c=(Vc=o.launcher)==null?void 0:Vc.enabled)!=null?$c:!0,I=(zc=(Uc=o.launcher)==null?void 0:Uc.autoExpand)!=null?zc:!1,W=(qc=o.autoFocusInput)!=null?qc:!1,H=I,R=L,w=(Kc=(jc=o.layout)==null?void 0:jc.header)==null?void 0:Kc.layout,C=!1,k=()=>pa(o),A=()=>L||k(),S=k()?!1:L?I:!0,_=!1,V=null,K=()=>{_=!0,V&&clearTimeout(V),V=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},fe=Bg(o,E,K),ue=(Yc=(Gc=o.features)==null?void 0:Gc.showReasoning)!=null?Yc:!0,ce=(Qc=(Xc=o.features)==null?void 0:Xc.showToolCalls)!=null?Qc:!0,ke=(Zc=(Jc=o.features)==null?void 0:Jc.showEventStreamToggle)!=null?Zc:!1,ve=(td=(ed=o.features)==null?void 0:ed.scrollToBottom)!=null?td:{},He=(od=(nd=o.features)==null?void 0:nd.scrollBehavior)!=null?od:{},ie=`${(sd=typeof o.persistState=="object"?(rd=o.persistState)==null?void 0:rd.keyPrefix:void 0)!=null?sd:"persona-"}event-stream`,X=ke?new ha(ie):null,re=(ld=(id=(ad=o.features)==null?void 0:ad.eventStream)==null?void 0:id.maxEvents)!=null?ld:2e3,be=ke?new fa(re,X):null,he=ke?new ba:null,j=null,se=!1,Re=null,ne=0;X==null||X.open().then(()=>be==null?void 0:be.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Z={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)}},oe=(cd=o.statusIndicator)!=null?cd:{},at=c=>{var p,h,y,M;return c==="idle"?(p=oe.idleText)!=null?p:Mn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:Mn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:Mn.connected:c==="error"?(M=oe.errorText)!=null?M:Mn.error:Mn[c]};function it(c,p,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let M=document.createElement("a");M.href=h.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=p,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=p}let{wrapper:Le,panel:de,pillRoot:Xe}=eg(o),We=tg(o,A()),{container:q,body:me,messagesWrapper:tt,suggestions:Tt,textarea:te,sendButton:ze,sendButtonWrapper:Nn,composerForm:Bt,statusText:an,introTitle:ro,introSubtitle:Eo,closeButton:D,iconHolder:pe,headerTitle:De,headerSubtitle:Ke,header:Ne,footer:Ve,actionsRow:ot,leftActions:It,rightActions:qt}=We,Qt=We.setSendButtonMode,G=We.micButton,yt=We.micButtonWrapper,st=We.attachmentButton,Ce=We.attachmentButtonWrapper,le=We.attachmentInput,Ze=We.attachmentPreviewsContainer;q.classList.add("persona-relative"),me.classList.add("persona-relative");let Zt=12,jt=()=>{var c;return(c=ve.label)!=null?c:""},Rn=()=>{var c;return(c=ve.iconName)!=null?c:"arrow-down"},xn=()=>ve.enabled!==!1,ut=()=>{var c;return(c=He.mode)!=null?c:"follow"},kt=()=>{var c;return(c=He.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 Ut=b("span","persona-flex persona-items-center"),ln=b("span",""),Sn=b("span","");Sn.setAttribute("data-persona-scroll-to-bottom-count",""),Sn.style.display="none",Qe.append(Ut,ln,Sn),q.appendChild(Qe);let An=b("div","persona-stream-anchor-spacer");An.setAttribute("aria-hidden","true"),An.setAttribute("data-persona-anchor-spacer",""),An.style.flexShrink="0",An.style.pointerEvents="none",An.style.height="0px",me.appendChild(An);let bn=()=>{let p=Ve.style.display==="none"?0:Ve.offsetHeight;Qe.style.bottom=`${p+Zt}px`};bn();let Mo=()=>{let c=!!jt();Qe.setAttribute("aria-label",jt()||"Jump to latest"),Qe.title=jt(),Qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Ut.innerHTML="";let p=Ee(Rn(),"14px","currentColor",2);p?(Ut.appendChild(p),Ut.style.display=""):Ut.style.display="none",ln.textContent=jt(),ln.style.display=c?"":"none"};Mo();let Ct=null,zn=null,qn=r.find(c=>c.renderHeader);if(qn!=null&&qn.renderHeader){let c=qn.renderHeader({config:o,defaultRenderer:()=>{let p=_r({config:o,showClose:A()});return ma(q,p,o),p.header},onClose:()=>Dt(!1,"user")});if(c){let p=q.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(c),Ne=c)}}let No=()=>{var p,h,y,M;if(!be)return;if(se=!0,!j&&be&&(j=gg({buffer:be,getFullHistory:()=>be.getAllFromStore(),onClose:()=>ho(),config:o,plugins:r,getThroughput:()=>{var F;return(F=he==null?void 0:he.getMetric())!=null?F:{status:"idle"}}})),j&&(me.style.display="none",(p=Ve.parentNode)==null||p.insertBefore(j.element,Ve),j.update()),vt){vt.style.boxShadow=`inset 0 0 0 1.5px ${Fn.actionIconColor}`;let F=(M=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:M.toggleButtonActive;F&&F.split(/\s+/).forEach(N=>N&&vt.classList.add(N))}let c=()=>{if(!se)return;let F=Date.now();F-ne>=200&&(j==null||j.update(),ne=F),Re=requestAnimationFrame(c)};ne=0,Re=requestAnimationFrame(c),$n(),s.emit("eventStream:opened",{timestamp:Date.now()})},ho=()=>{var c,p,h;if(se){if(se=!1,j&&j.element.remove(),me.style.display="",vt){vt.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(M=>M&&vt.classList.remove(M))}Re!==null&&(cancelAnimationFrame(Re),Re=null),$n(),s.emit("eventStream:closed",{timestamp:Date.now()})}},vt=null;if(ke){let c=(pd=(dd=o.features)==null?void 0:dd.eventStream)==null?void 0:pd.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:"");vt=b("button",p),vt.style.width="28px",vt.style.height="28px",vt.style.color=Fn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let h=Ee("activity","18px","currentColor",1.5);h&&vt.appendChild(h);let y=We.clearChatButtonWrapper,M=We.closeButtonWrapper,F=y||M;F&&F.parentNode===Ne?Ne.insertBefore(vt,F):Ne.appendChild(vt),vt.addEventListener("click",()=>{se?ho():No()})}let yr=c=>{var y,M,F;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 N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(h,N):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=b("input");N.type="file",N.accept=((y=p.allowedTypes)!=null?y:Xo).join(","),N.multiple=((M=p.maxFiles)!=null?M:4)>1,N.style.display="none",N.setAttribute("aria-label",(F=p.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(N)}},Lo=r.find(c=>c.renderComposer);if(Lo!=null&&Lo.renderComposer){let c=o.composer,p=Lo.renderComposer({config:o,defaultRenderer:()=>Oi({config:o}).footer,onSubmit:h=>{var N;if(!$||$.isStreaming())return;let y=h.trim(),M=(N=Ct==null?void 0:Ct.hasAttachments())!=null?N:!1;if(!y&&!M)return;U();let F;M&&(F=[],F.push(...Ct.getContentParts()),y&&F.push(Fl(y))),$.sendMessage(y,{contentParts:F}),M&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{le==null||le.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:((ud=o.voiceRecognition)==null?void 0:ud.enabled)===!0?()=>{zn==null||zn()}:void 0});p&&(Ve.replaceWith(p),Ve=p)}let vr=c=>{let p=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");p&&(Bt=p),h&&(te=h),y&&(ze=y),M&&(G=M,yt=M.parentElement),F&&(an=F);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Tt=N);let z=c.querySelector(".persona-attachment-button");z&&(st=z,Ce=z.parentElement),le=c.querySelector('input[type="file"]'),Ze=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(ot=O)};yr(Ve),vr(Ve);let _n=(bd=(md=o.layout)==null?void 0:md.contentMaxWidth)!=null?bd:k()?(hd=(fd=(gd=o.launcher)==null?void 0:gd.composerBar)==null?void 0:fd.contentMaxWidth)!=null?hd:"720px":void 0;if(_n&&(tt.style.maxWidth=_n,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%"),_n&&Bt&&!k()&&(Bt.style.maxWidth=_n,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),_n&&Tt&&!k()&&(Tt.style.maxWidth=_n,Tt.style.marginLeft="auto",Tt.style.marginRight="auto"),_n&&Ze&&!k()&&(Ze.style.maxWidth=_n,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),(yd=o.attachments)!=null&&yd.enabled&&le&&Ze){Ct=ra.fromConfig(o.attachments),Ct.setPreviewsContainer(Ze),le.addEventListener("change",h=>{let y=h.target;Ct==null||Ct.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,p=Hg(c);q.appendChild(p)}(()=>{var y,M;let c=(M=(y=o.layout)==null?void 0:y.slots)!=null?M:{},p=F=>{switch(F){case"body-top":return q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return tt;case"footer-top":return Tt;case"composer":return Bt;case"footer-bottom":return an;default:return null}},h=(F,N)=>{var z;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")Ne.insertBefore(N,Ne.firstChild);else if(F==="header-right")Ne.appendChild(N);else{let O=Ne.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(N,O.nextSibling):Ne.appendChild(N)}break;case"body-top":{let O=me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(N):me.insertBefore(N,me.firstChild);break}case"body-bottom":me.appendChild(N);break;case"footer-top":Tt.replaceWith(N);break;case"footer-bottom":an.replaceWith(N);break;default:break}};for(let[F,N]of Object.entries(c))if(N)try{let z=N({config:o,defaultContent:()=>p(F)});z&&h(F,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,z)}})();let Zo=c=>{var N,z;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")hs.has(M)?hs.delete(M):hs.add(M),rg(M,y);else if(F==="tool")bs.has(M)?bs.delete(M):bs.add(M),sg(M,y,o);else if(F==="approval"){let O=o.approval!==!1?o.approval:void 0,we=((N=O==null?void 0:O.detailsDisplay)!=null?N:"collapsed")==="expanded",ge=(z=Fi.get(M))!=null?z:we;Fi.set(M,!ge),cg(M,y,o)}Uo.delete(M)};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 N;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let M=y.getAttribute("data-actions-for");if(!M)return;let F=h.getAttribute("data-action");if(F==="copy"){let O=$.getMessages().find(we=>we.id===M);if(O&&Z.onCopy){let we=O.content||"";navigator.clipboard.writeText(we).then(()=>{h.classList.add("persona-message-action-success");let ge=Ee("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=Ee("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),Z.onCopy(O)}}else if(F==="upvote"||F==="downvote"){let O=((N=_o.get(M))!=null?N:null)===F,we=F==="upvote"?"thumbs-up":"thumbs-down";if(O){_o.delete(M),h.classList.remove("persona-message-action-active");let ge=Ee(we,14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))}else{let ge=F==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ge}"]`);if(ee){ee.classList.remove("persona-message-action-active");let qe=Ee(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(ee.innerHTML="",ee.appendChild(qe))}_o.set(M,F),h.classList.add("persona-message-action-active");let Te=Ee(we,14,"currentColor",2);Te&&(Te.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Te)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=$.getMessages().find(nt=>nt.id===M);Ae&&Z.onFeedback&&Z.onFeedback({type:F,messageId:Ae.id,message:Ae})}}}),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 M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-approval-action");if(!F)return;let N=F==="approve"?"approved":"denied",O=$.getMessages().find(ge=>ge.id===M);if(!(O!=null&&O.approval))return;let we=y.querySelector("[data-approval-buttons]");we&&we.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?$.resolveWebMcpApproval(M,N):$.resolveApproval(O.approval,N)});let St=null,jn=null,Kn={artifacts:[],selectedId:null},Pn=!1,Lt={current:null};tt.addEventListener("click",c=>{var ee,Te,_e,Ae,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||((_e=(Te=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:Te.onArtifactAction)==null?void 0:_e.call(Te,{type:"download",artifactId:y}))===!0)return;let F=$.getArtifactById(y),N=F==null?void 0:F.markdown,z=(F==null?void 0:F.title)||"artifact";if(!N){let qe=h.closest("[data-open-artifact]"),ct=qe==null?void 0:qe.closest("[data-message-id]"),dt=ct==null?void 0:ct.getAttribute("data-message-id");if(dt){let Ie=$.getMessages().find(Ue=>Ue.id===dt);if(Ie!=null&&Ie.rawContent)try{let Ue=JSON.parse(Ie.rawContent);N=(Ae=Ue==null?void 0:Ue.props)==null?void 0:Ae.markdown,z=((nt=Ue==null?void 0:Ue.props)==null?void 0:nt.title)||z}catch{}}}if(!N)return;let O=new Blob([N],{type:"text/markdown"}),we=URL.createObjectURL(O),ge=document.createElement("a");ge.href=we,ge.download=`${z}.md`,ge.click(),URL.revokeObjectURL(we)}),tt.addEventListener("click",c=>{var F,N,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(N=(F=o.features)==null?void 0:F.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:z.call(N,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Pn=!1,$.selectArtifact(y),Xn())}),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 so=We.composerOverlay,ao=(c,p,h)=>{var z,O,we,ge;let y=p.trim();if(!y||!Lt.current)return;let M=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),ms(so,M);let N=Lt.current.getMessages().find(ee=>{var Te;return((Te=ee.toolCall)==null?void 0:Te.id)===M});(we=N==null?void 0:N.agentMetadata)!=null&&we.awaitingLocalTool?Lt.current.resolveAskUserQuestion(N,(ge=h.structured)!=null?ge:y):Lt.current.sendMessage(y)},Gn=c=>{var M;let p=Lt.current;if(!p)return;let h=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",y=p.getMessages().find(F=>{var N;return((N=F.toolCall)==null?void 0:N.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:si(c,y),currentIndex:go(c)})},er=c=>Object.entries(c).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Vo=c=>{var M,F,N;if(((F=(M=o.features)==null?void 0:M.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let p=go(c),h=us(c);if(p>=h-1)return;let y=(N=Lt.current)==null?void 0:N.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(ii(c,y,o,p+1),Gn(c))};so.addEventListener("click",c=>{var F,N,z,O,we,ge,ee,Te,_e,Ae,nt,qe,ct,dt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let M=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Pe=(F=y.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ms(so,Pe);let Ie=(N=Lt.current)==null?void 0:N.getMessages().find(Ue=>{var Ge;return((Ge=Ue.toolCall)==null?void 0:Ge.id)===Pe});(z=Ie==null?void 0:Ie.agentMetadata)!=null&&z.awaitingLocalTool&&((O=Lt.current)==null||O.markAskUserQuestionResolved(Ie),(we=Lt.current)==null||we.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(M==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Ie=y.getAttribute("data-multi-select")==="true",Ue=gr(y);if(Ue&&Ie){let Ge=Dr(y)[go(y)],xt=new Set(Array.isArray(Ge)?Ge:[]);xt.has(Pe)?xt.delete(Pe):xt.add(Pe),fr(y,Array.from(xt)),Gn(y);return}if(Ue){fr(y,Pe),Gn(y),Vo(y);return}if(Ie){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let xt=y.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Pl(y).length===0);return}ao(y,Pe,{source:"pick",values:[Pe]});return}if(M==="submit-multi"){let Pe=Pl(y);if(Pe.length===0)return;ao(y,Pe.join(", "),{source:"multi",values:Pe});return}if(M==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Ie=Pe.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(M==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(M==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Ie=(ge=Pe==null?void 0:Pe.value)!=null?ge:"";if(!Ie.trim())return;if(gr(y)){fr(y,Ie.trim()),Gn(y),Vo(y);return}ao(y,Ie,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Lt.current)return;let Pe=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Ie=Lt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Pe});if(!Ie)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(_e=(Te=Ue==null?void 0:Ue.value)==null?void 0:Te.trim())!=null?_e:"";if(Ge){let Be=Dr(y)[go(y)];(typeof Be!="string"||Be!==Ge)&&fr(y,Ge)}let xt=M==="next"?1:-1,B=go(y)+xt;ii(y,Ie,o,B),Gn(y);return}if(M==="submit-all"){if(!Lt.current)return;let Pe=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",Ie=Lt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Pe});if(!Ie)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(qe=(nt=Ue==null?void 0:Ue.value)==null?void 0:nt.trim())!=null?qe:"";Ge&&fr(y,Ge);let xt=si(y,Ie);Lt.current.persistAskUserQuestionProgress(Ie,{answers:xt,currentIndex:go(y)});let B=er(xt);ao(y,B||"(submitted)",{source:"submit-all",structured:xt});return}if(M==="skip"){if(!Lt.current)return;let Pe=(ct=y.getAttribute("data-tool-call-id"))!=null?ct:"",Ie=Lt.current.getMessages().find(Oe=>{var ye;return((ye=Oe.toolCall)==null?void 0:ye.id)===Pe});if(!Ie)return;let Ue=gr(y),Ge=go(y),xt=us(y),B=Ge>=xt-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ms(so,Pe),(dt=Ie.agentMetadata)!=null&&dt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Ie),Lt.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}fr(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),B){let Oe=si(y,Ie),ye=er(Oe);ao(y,ye||"(skipped)",{source:"submit-all",structured:Oe});return}ii(y,Ie,o,Ge+1),Gn(y);return}}),so.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let h=c.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let M=h.value;if(M.trim()){if(gr(y)){fr(y,M.trim()),Gn(y),Vo(y);return}ao(y,M,{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=so.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),F=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",tr);let Yn=null,Ht=null,Wn=null,io=null,nr=()=>{};function $o(){io==null||io(),io=null}let or=()=>{var N;if(!Yn||!Ht)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Ht.style.removeProperty("position"),Ht.style.removeProperty("left"),Ht.style.removeProperty("top"),Ht.style.removeProperty("bottom"),Ht.style.removeProperty("width"),Ht.style.removeProperty("z-index");return}let y=Yn.firstElementChild;if(!y||y===Ht)return;let M=10;Ht.style.position="absolute",Ht.style.top="0",Ht.style.bottom="0",Ht.style.width=`${M}px`,Ht.style.zIndex="5";let F=y.offsetWidth-M/2;Ht.style.left=`${Math.max(0,F)}px`},Io=()=>{},Xn=()=>{var h,y,M,F,N;if(!St||!fo(o))return;Vi(e,o),$i(e,o),Io();let c=(F=(M=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:M.narrowHostMaxWidth)!=null?F:520,p=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=c),St.update(Kn),Pn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(N=St.backdrop)==null||N.classList.add("persona-hidden")):Kn.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),nr()};if(fo(o)){de.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(q),St=bg(o,{onSelect:h=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Pn=!0,Xn()}}),St.element.classList.add("persona-hidden"),Yn=p,p.appendChild(c),p.appendChild(St.element),St.backdrop&&de.appendChild(St.backdrop),de.appendChild(p),nr=()=>{var y,M,F,N;if(!Yn||!St)return;if(!(((F=(M=(y=o.features)==null?void 0:y.artifacts)==null?void 0:M.layout)==null?void 0:F.resizable)===!0)){Wn==null||Wn(),Wn=null,$o(),Ht&&(Ht.remove(),Ht=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Ht){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,we=(N=O.defaultView)!=null?N:window,ge=ee=>{var ct,dt;if(!St||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||we.innerWidth<=640)return;ee.preventDefault(),$o();let Te=ee.clientX,_e=St.element.getBoundingClientRect().width,Ae=(dt=(ct=o.features)==null?void 0:ct.artifacts)==null?void 0:dt.layout,nt=Pe=>{let Ie=Yn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Ge=Ue?0:wg(Yn,we),xt=Ue?0:z.getBoundingClientRect().width||6,B=_e-(Pe.clientX-Te),Be=Cg(B,Ie,Ge,xt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);St.element.style.width=`${Be}px`,St.element.style.maxWidth="none",or()},qe=()=>{O.removeEventListener("pointermove",nt),O.removeEventListener("pointerup",qe),O.removeEventListener("pointercancel",qe),io=null;try{z.releasePointerCapture(ee.pointerId)}catch{}};io=qe,O.addEventListener("pointermove",nt),O.addEventListener("pointerup",qe),O.addEventListener("pointercancel",qe);try{z.setPointerCapture(ee.pointerId)}catch{}};z.addEventListener("pointerdown",ge),Ht=z,Yn.insertBefore(z,St.element),Wn=()=>{z.removeEventListener("pointerdown",ge)}}if(Ht){let z=Kn.artifacts.length>0&&!Pn;Ht.classList.toggle("persona-hidden",!z),or()}},Io=()=>{var we,ge,ee,Te,_e,Ae,nt,qe,ct,dt,Pe,Ie,Ue,Ge;if(!L||!St||((ge=(we=o.launcher)==null?void 0:we.sidebarMode)!=null?ge:!1)||Cn(o)&&To(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,M=(_e=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?_e:!0,F=(nt=(Ae=o.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?nt:640;if(M&&y.innerWidth<=F||!xg(o,L))return;let N=(dt=(ct=(qe=o.launcher)==null?void 0:qe.width)!=null?ct:o.launcherWidth)!=null?dt:mo,z=(Ge=(Ue=(Ie=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Ie.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";Kn.artifacts.length>0&&!Pn?(de.style.width=z,de.style.maxWidth=z):(de.style.width=N,de.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(jn=new ResizeObserver(()=>{Xn()}),jn.observe(de))}else de.appendChild(q),k()&&Xe&&(We.peekBanner&&Xe.appendChild(We.peekBanner),Xe.appendChild(Ve));e.appendChild(Le),Xe&&e.appendChild(Xe);let bo=()=>{var Be,Oe,ye,Ft,Ot,Kt,wt,zt,eo,sn,Ye,Rt,dn,uo,to,Tr,kr,os,rs,Yt,Er,ur,mr,Go,Mr,Co,et,mn;if(k()){de.style.width="100%",de.style.maxWidth="100%";let Vt=(Oe=(Be=o.launcher)==null?void 0:Be.composerBar)!=null?Oe:{},Nt=Le.dataset.state==="expanded",ht=(ye=Vt.expandedSize)!=null?ye:"anchored";if(!(Nt&&ht!=="fullscreen")){q.style.background="",q.style.border="",q.style.borderRadius="",q.style.overflow="",q.style.boxShadow="";return}let Et=(Ot=(Ft=o.theme)==null?void 0:Ft.components)==null?void 0:Ot.panel,kn=Va(o),Bn=(Dn,Lr)=>{var _s;return Dn==null||Dn===""?Lr:(_s=ss(kn,Dn))!=null?_s:Dn},Do="1px solid var(--persona-border)",vn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Hn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";q.style.background="var(--persona-surface, #ffffff)",q.style.border=Bn(Et==null?void 0:Et.border,Do),q.style.borderRadius=Bn(Et==null?void 0:Et.borderRadius,Hn),q.style.boxShadow=Bn(Et==null?void 0:Et.shadow,vn),q.style.overflow="hidden";return}let c=Cn(o),p=(wt=(Kt=o.launcher)==null?void 0:Kt.sidebarMode)!=null?wt:!1,h=c||p||((eo=(zt=o.launcher)==null?void 0:zt.fullHeight)!=null?eo:!1),y=((sn=o.launcher)==null?void 0:sn.enabled)===!1,M=(Rt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Rt.panel,F=Va(o),N=(Vt,Nt)=>{var ht;return Vt==null||Vt===""?Nt:(ht=ss(F,Vt))!=null?ht:Vt},z=(dn=e.ownerDocument.defaultView)!=null?dn:window,O=(to=(uo=o.launcher)==null?void 0:uo.mobileFullscreen)!=null?to:!0,we=(kr=(Tr=o.launcher)==null?void 0:Tr.mobileBreakpoint)!=null?kr:640,ge=z.innerWidth<=we,ee=O&&ge&&L,Te=(rs=(os=o.launcher)==null?void 0:os.position)!=null?rs:"bottom-left",_e=Te==="bottom-left"||Te==="top-left",Ae=(Er=(Yt=o.launcher)==null?void 0:Yt.zIndex)!=null?Er:Ln,nt=p||ee?"none":"1px solid var(--persona-border)",qe=ee?"none":p?_e?"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 ct=p||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=N(M==null?void 0:M.border,nt),Pe=N(M==null?void 0:M.shadow,qe),Ie=N(M==null?void 0:M.borderRadius,ct),Ue=me.scrollTop;e.style.cssText="",Le.style.cssText="",de.style.cssText="",q.style.cssText="",me.style.cssText="",Ve.style.cssText="";let Ge=()=>{var Nt;if(Ue<=0)return;((Nt=me.ownerDocument.defaultView)!=null?Nt:window).requestAnimationFrame(()=>{if(me.scrollTop===Ue)return;let ht=me.scrollHeight-me.clientHeight;ht<=0||(me.scrollTop=Math.min(Ue,ht))})};if(ee){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;
@@ -63,11 +63,11 @@ _Details: ${n.message}_`:o}var Zs=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
- `,me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.style.flexShrink="0",x=!0,Ge();return}let wt=(ur=(pr=o==null?void 0:o.launcher)==null?void 0:pr.width)!=null?ur:o==null?void 0:o.launcherWidth,B=wt!=null?wt:fo;if(!p&&!c)y&&h?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=B,de.style.maxWidth=B);else if(c)if(Oo(o).reveal==="emerge"){let bt=Oo(o).width;de.style.width=bt,de.style.maxWidth=bt}else de.style.width="100%",de.style.maxWidth="100%";if(Lo(),de.style.boxShadow=Pe,de.style.borderRadius=Le,q.style.border=dt,q.style.borderRadius=Le,c&&!te&&(M==null?void 0:M.border)===void 0&&(q.style.border="none",Oo(o).side==="right"?q.style.borderLeft="1px solid var(--persona-border)":q.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%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",y&&(Me.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",de.style.overflow="hidden",q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.overflow="hidden",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.style.flexShrink="0"),Me.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&&((Go=To[Te])!=null?Go:To["bottom-right"]).split(" ").forEach(bt=>Me.classList.add(bt)),p){let pt=(vn=(ot=o.launcher)==null?void 0:ot.sidebarWidth)!=null?vn:"420px";Me.style.cssText=`
66
+ `,me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.style.flexShrink="0",C=!0,Ge();return}let xt=(mr=(ur=o==null?void 0:o.launcher)==null?void 0:ur.width)!=null?mr:o==null?void 0:o.launcherWidth,B=xt!=null?xt:mo;if(!p&&!c)y&&h?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=B,de.style.maxWidth=B);else if(c)if(To(o).reveal==="emerge"){let Nt=To(o).width;de.style.width=Nt,de.style.maxWidth=Nt}else de.style.width="100%",de.style.maxWidth="100%";if(Io(),de.style.boxShadow=Pe,de.style.borderRadius=Ie,q.style.border=dt,q.style.borderRadius=Ie,c&&!ee&&(M==null?void 0:M.border)===void 0&&(q.style.border="none",To(o).side==="right"?q.style.borderLeft="1px solid var(--persona-border)":q.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"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",de.style.overflow="hidden",q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.overflow="hidden",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.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&&((Go=ko[Te])!=null?Go:ko["bottom-right"]).split(" ").forEach(Nt=>Le.classList.add(Nt)),p){let Vt=(Co=(Mr=o.launcher)==null?void 0:Mr.sidebarWidth)!=null?Co:"420px";Le.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${pt} !important;
70
+ width: ${Vt} !important;
71
71
  height: 100vh !important;
72
72
  max-height: 100vh !important;
73
73
  margin: 0 !important;
@@ -88,7 +88,7 @@ _Details: ${n.message}_`:o}var Zs=e=>({isError:!0,content:[{type:"text",text:e}]
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
90
  box-shadow: ${Pe} !important;
91
- border-radius: ${Le} !important;
91
+ border-radius: ${Ie} !important;
92
92
  `,de.style.setProperty("width","100%","important"),de.style.setProperty("max-width","100%","important"),q.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
@@ -98,13 +98,13 @@ _Details: ${n.message}_`:o}var Zs=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: ${Le} !important;
101
+ border-radius: ${Ie} !important;
102
102
  border: ${dt} !important;
103
103
  `,Ve.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!y&&!c){let pt="max-height: -moz-available !important; max-height: stretch !important;",bt=p?"":"padding-top: 1.25em !important;",ut=p?"":`z-index: ${(rn=(Pn=o.launcher)==null?void 0:Pn.zIndex)!=null?rn:En} !important;`;Me.style.cssText+=pt+bt+ut}Ge()};yo(),os(e,o),Ni(e,o),_i(e,o);let ht=[];ht.push(()=>{document.removeEventListener("keydown",er)});let Qt=null,Zt=null;ht.push(()=>{Qt==null||Qt(),Qt=null,Zt==null||Zt(),Zt=null}),zn&&ht.push(()=>{zn==null||zn.disconnect(),zn=null}),ht.push(()=>{Rn==null||Rn(),Rn=null,$o(),Dt&&(Dt.remove(),Dt=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),ke&&ht.push(()=>{Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),j==null||j.destroy(),j=null,be==null||be.destroy(),be=null,X=null});let Yn=null,or=()=>{Yn&&(Yn(),Yn=null),o.colorScheme==="auto"&&(Yn=Wu(()=>{os(e,o)}))};or(),ht.push(()=>{Yn&&(Yn(),Yn=null)});let xe=(fd=o.features)==null?void 0:fd.streamAnimation;if(xe!=null&&xe.type&&xe.type!=="none"){let c=na(xe.type,xe.plugins);c&&(Il(c,e),ht.push(()=>Mm(e)))}let ao=ef(Et),io=null,V,Io=!1,Uo=vm(),zo=new Map,Ro=new Map,vo=new Map,Cs=0,Xn=hi(),Jn=0,xo=null,wo=!1,vr=!1,qo=0,Sn=null,Po=null,zr=!1,xr=!1,qr=null,xa=4,jr=24,wa=80,Kr=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ss=(hd=(gd=o.voiceRecognition)==null?void 0:gd.autoResume)!=null?hd:!1,lo=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},On=()=>{m(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Ca=()=>{var y,M;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=tc(d.voiceState),p=!!c.active,h=Number((M=c.timestamp)!=null?M:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,p&&Date.now()-h<Gx&&setTimeout(()=>{var O,N;yt.active||(yt.manuallyDeactivated=!1,((N=(O=o.voiceRecognition)==null?void 0:O.provider)==null?void 0:N.type)==="runtype"?V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),lo("restore"),V.isVoiceActive()&&Ds()}):mn("restore"))},1e3)},Sa=()=>V?Af(V.getMessages()).filter(c=>!c.__skipPersist):[];function Gr(c){if(!(i!=null&&i.save))return;let h={messages:c?Af(c):V?Sa():[],metadata:d,artifacts:qn.artifacts,selectedArtifactId:qn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let jo=null,As=()=>Me.querySelector("#persona-scroll-container")||me,rr=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),wo=!1},Ts=()=>{xo!==null&&(cancelAnimationFrame(xo),xo=null),vr=!1,rr()},ks=()=>{qo>0?(wn.textContent=String(qo),wn.style.display="",Je.setAttribute("aria-label",`${Kt()||"Jump to latest"} (${qo} new)`)):(wn.textContent="",wn.style.display="none",Je.setAttribute("aria-label",Kt()||"Jump to latest"))},Es=()=>{qo!==0&&(qo=0,ks())},Ms=()=>ft()==="follow"?!Xn.isFollowing():!Hr(me,jr),Nn=()=>{if(!yn()||se){Je.parentNode&&Je.remove(),Je.style.display="none";return}Je.parentNode!==q&&q.appendChild(Je),bn();let p=Xo(me)>0&&Ms();p||Es(),Je.style.display=p?"":"none"},Yr=()=>{Xn.pause()&&(Ts(),Nn())},Wo=()=>{Xn.resume(),Es(),Nn()},Bo=(c=!1)=>{ft()==="follow"&&Xn.isFollowing()&&(!c&&!Io||(xo!==null&&(cancelAnimationFrame(xo),xo=null),vr=!0,xo=requestAnimationFrame(()=>{xo=null,vr=!1,Xn.isFollowing()&&Aa(As(),c?220:140)})))},Ls=(c,p,h,y=()=>!0)=>{let M=c.scrollTop,O=p(),N=O-M;rr();let z=performance.now();wo=!0;let F=fe=>1-Math.pow(1-fe,3),we=fe=>{if(!y()){rr();return}let te=p();te!==O&&(O=te,N=O-M);let Te=fe-z,_e=Math.min(Te/h,1),Ae=F(_e),tt=M+N*Ae;c.scrollTop=tt,Jn=c.scrollTop,_e<1?jo=requestAnimationFrame(we):(c.scrollTop=O,Jn=c.scrollTop,jo=null,wo=!1)};jo=requestAnimationFrame(we)},Aa=(c,p=500)=>{let h=Xo(c)-c.scrollTop;if(Math.abs(h)<1){Jn=c.scrollTop;return}if(Math.abs(h)>=wa){rr(),wo=!0,c.scrollTop=Xo(c),Jn=c.scrollTop,wo=!1;return}Ls(c,()=>Xo(c),p,()=>Xn.isFollowing())},Is=()=>{let c=As();wo=!0,c.scrollTop=Xo(c),Jn=c.scrollTop,wo=!1,Nn()},Rs=c=>{Cn.style.height=`${Math.max(0,Math.round(c))}px`,Sn&&(Sn.spacerHeight=Math.max(0,c))},wr=()=>{Po!==null&&(cancelAnimationFrame(Po),Po=null),rr(),Sn=null,Cn.style.height="0px"},Ta=c=>{Po!==null&&cancelAnimationFrame(Po),Po=requestAnimationFrame(()=>{var we;Po=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=me.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,M=h;for(;M&&M!==me;)y+=M.offsetTop,M=M.offsetParent;let O=(we=Sn==null?void 0:Sn.spacerHeight)!=null?we:0,N=me.scrollHeight-O,{targetScrollTop:z,spacerHeight:F}=Am({anchorOffsetTop:y,topOffset:Mt(),viewportHeight:me.clientHeight,contentHeight:N});Sn={initialSpacerHeight:F,contentHeightAtAnchor:N,spacerHeight:F},Rs(F),Ls(me,()=>z,220)})},ka=()=>{if(ft()==="follow"){if(!Xn.isFollowing()||Hr(me,1))return;Bo(!Io);return}if(Sn&&Sn.initialSpacerHeight>0){let c=me.scrollHeight-Sn.spacerHeight,p=Tm({initialSpacerHeight:Sn.initialSpacerHeight,contentHeightAtAnchor:Sn.contentHeightAtAnchor,currentContentHeight:c});p!==Sn.spacerHeight&&Rs(p)}Nn()},Ea=c=>{let p=ft();p==="follow"?(Wo(),Bo(!0)):p==="anchor-top"&&Ta(c)},Ma=c=>{let p=new Map;c.forEach(h=>{let y=Kr.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!xr&&ft()!=="anchor-top"&&Ms()&&(qo+=1,ks(),Nn())),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}))}),Kr.clear(),p.forEach((h,y)=>{Kr.set(y,h)})},Cr=(c,p,h)=>{var dt,Pe,Le,Ue,Ge,wt;let y=document.createElement("div"),O=(()=>{var Be;let B=r.find(Fe=>Fe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Be=o.loadingIndicator)!=null&&Be.render)return o.loadingIndicator.render})(),N=(B,Be)=>Be==null?!1:typeof Be=="string"?(B.textContent=Be,!0):(B.appendChild(Be),!0),z=new Set,F=new Set,we=r.some(B=>B.renderAskUserQuestion),fe=[],te=[],Te=o.enableComponentStreaming!==!1,_e=r.some(B=>B.renderApproval)&&o.approval!==!1,Ae=[];if(p.forEach(B=>{var Ye,Pt,cn,uo,Zn,Sr,Ar,es,ts,Yt,Tr,pr,ur,Go;z.add(B.id);let Be=we&&Fr(B),Fe=_e&&B.variant==="approval"&&!!B.approval,ye=!Be&&B.role==="assistant"&&!B.variant&&Te&&xf(B);if(!Fe&&vo.has(B.id)){let ot=c.querySelector(`#wrapper-${B.id}`);ot==null||ot.removeAttribute("data-preserve-runtime"),vo.delete(B.id)}if(!ye&&Ro.has(B.id)){let ot=c.querySelector(`#wrapper-${B.id}`);ot==null||ot.removeAttribute("data-preserve-runtime"),Ro.delete(B.id)}let _t=Fr(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Pt=B.agentMetadata)!=null&&Pt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=ym(B,Cs)+_t,Gt=Be||Fe||ye?null:xm(Uo,B.id,Ot);if(Gt){y.appendChild(Gt.cloneNode(!0)),Fr(B)&&((cn=B.toolCall)!=null&&cn.id)&&((uo=B.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((Zn=B.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Bi(B,o,We.composerOverlay));return}let Ct=null,qt=r.find(ot=>!!(B.variant==="reasoning"&&ot.renderReasoning||B.variant==="tool"&&ot.renderToolCall||!B.variant&&ot.renderMessage)),Qn=(Sr=o.layout)==null?void 0:Sr.messages;if(Fr(B)&&((Ar=B.agentMetadata)==null?void 0:Ar.askUserQuestionAnswered)===!0){zo.delete(B.id);let ot=c.querySelector(`#wrapper-${B.id}`);ot==null||ot.removeAttribute("data-preserve-runtime");return}if(Fr(B)&&((ts=(es=o.features)==null?void 0:es.askUserQuestion)==null?void 0:ts.enabled)!==!1){let ot=r.find(vn=>typeof vn.renderAskUserQuestion=="function");if(ot&&It.current){let vn=zo.get(B.id),Pn=vn!==Ot,rn=null;if(Pn){let{payload:ut,complete:_n}=ms(B),dn=B.id,Ho=()=>{var pn;return(pn=It.current)==null?void 0:pn.getMessages().find(Wn=>Wn.id===dn)};rn=ot.renderAskUserQuestion({message:B,payload:ut,complete:_n,resolve:pn=>{var mo;let Wn=Ho();Wn&&((mo=It.current)==null||mo.resolveAskUserQuestion(Wn,pn))},dismiss:()=>{var Wn,mo,kr;let pn=Ho();(Wn=pn==null?void 0:pn.agentMetadata)!=null&&Wn.awaitingLocalTool&&((mo=It.current)==null||mo.markAskUserQuestionResolved(pn),(kr=It.current)==null||kr.resolveAskUserQuestion(pn,"(dismissed)"))},config:o})}let pt=vn!=null;if(Pn&&rn===null&&!pt){((Yt=B.agentMetadata)==null?void 0:Yt.awaitingLocalTool)===!0&&!((Tr=B.agentMetadata)!=null&&Tr.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Bi(B,o,We.composerOverlay));return}let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${B.id}`,bt.setAttribute("data-wrapper-id",B.id),bt.setAttribute("data-ask-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),y.appendChild(bt),fe.push({messageId:B.id,fingerprint:Ot,bubble:rn});return}else{((pr=B.agentMetadata)==null?void 0:pr.awaitingLocalTool)===!0&&!((ur=B.agentMetadata)!=null&&ur.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Bi(B,o,We.composerOverlay));return}}else if(Fe){let ot=r.find(pt=>typeof pt.renderApproval=="function"),Pn=vo.get(B.id)!==Ot,rn=null;if(Pn&&(ot!=null&&ot.renderApproval)){let pt=B.id,bt=(ut,_n)=>{var Ho,pn,Wn;let dn=(Ho=It.current)==null?void 0:Ho.getMessages().find(mo=>mo.id===pt);dn!=null&&dn.approval&&(dn.approval.toolType==="webmcp"?(pn=It.current)==null||pn.resolveWebMcpApproval(dn.id,ut):(Wn=It.current)==null||Wn.resolveApproval(dn.approval,ut,_n))};rn=ot.renderApproval({message:B,defaultRenderer:()=>Fi(B,o),config:o,approve:ut=>bt("approved",ut),deny:ut=>bt("denied",ut)})}if(Pn&&rn===null){let pt=c.querySelector(`#wrapper-${B.id}`);pt==null||pt.removeAttribute("data-preserve-runtime"),vo.delete(B.id),Ct=Fi(B,o)}else{let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-${B.id}`,pt.setAttribute("data-wrapper-id",B.id),pt.setAttribute("data-approval-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),y.appendChild(pt),Ae.push({messageId:B.id,fingerprint:Ot,bubble:rn});return}}else if(qt)if(B.variant==="reasoning"&&B.reasoning&&qt.renderReasoning){if(!ue)return;Ct=qt.renderReasoning({message:B,defaultRenderer:()=>Fl(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&qt.renderToolCall){if(!ce)return;Ct=qt.renderToolCall({message:B,defaultRenderer:()=>Ol(B,o),config:o})}else qt.renderMessage&&(Ct=qt.renderMessage({message:B,defaultRenderer:()=>{let ot=Dl(B,h,Qn,o.messageActions,Z,{loadingIndicatorRenderer:O,widgetConfig:o});return B.role!=="user"&&Yl(ot,B,o,V),ot},config:o}));if(!Ct&&ye){let ot=wf(B);if(ot){let vn=Ro.get(B.id),Pn=vn!==Ot,rn=o.wrapComponentDirectiveInBubble!==!1,pt=null;if(Pn){let bt=yf(ot,{config:o,message:B,transform:h});if(bt)if(rn){let ut=document.createElement("div");if(ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let _n=document.createElement("div");_n.className="persona-mb-3 persona-text-sm persona-leading-relaxed",_n.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(_n)}ut.appendChild(bt),pt=ut}else{let ut=document.createElement("div");if(ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let _n=document.createElement("div");_n.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",_n.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(_n)}ut.appendChild(bt),pt=ut}}if(pt||vn!=null){let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${B.id}`,bt.setAttribute("data-wrapper-id",B.id),bt.setAttribute("data-component-directive-stub","true"),bt.setAttribute("data-preserve-runtime","true"),rn||bt.classList.add("persona-w-full"),y.appendChild(bt),te.push({messageId:B.id,fingerprint:Ot,bubble:pt});return}}}if(!Ct)if(B.variant==="reasoning"&&B.reasoning){if(!ue)return;Ct=Fl(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!ce)return;Ct=Ol(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;Ct=Fi(B,o)}else{let ot=(Go=o.layout)==null?void 0:Go.messages;ot!=null&&ot.renderUserMessage&&B.role==="user"?Ct=ot.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):ot!=null&&ot.renderAssistantMessage&&B.role==="assistant"?Ct=ot.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):Ct=Dl(B,h,ot,o.messageActions,Z,{loadingIndicatorRenderer:O,widgetConfig:o}),B.role!=="user"&&Ct&&Yl(Ct,B,o,V)}let on=document.createElement("div");on.className="persona-flex",on.id=`wrapper-${B.id}`,on.setAttribute("data-wrapper-id",B.id),B.role==="user"&&on.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&on.classList.add("persona-w-full"),on.appendChild(Ct),wm(Uo,B.id,Ot,on),y.appendChild(on)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Fe=Be.getAttribute("data-persona-ask-sheet-for");Fe&&!F.has(Fe)&&gs(We.composerOverlay,Fe)}),(Pe=(dt=o.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let B=[],Be=[];p.forEach(Fe=>{if(Fe.variant==="tool"&&Fe.toolCall&&ce){Be.push(Fe);return}Be.length>1&&B.push(Be),Be=[]}),Be.length>1&&B.push(Be),B.forEach((Fe,ye)=>{var Ye,Pt;let _t=Fe.map(cn=>Array.from(y.children).find(uo=>uo instanceof HTMLElement&&uo.getAttribute("data-wrapper-id")===cn.id)).filter(cn=>!!cn);if(_t.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${ye}-${Fe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${ye}-${Fe[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Fe.length} tools`,Qn=(Pt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Pt.call(Ye,{messages:Fe,toolCalls:Fe.map(cn=>cn.toolCall).filter(cn=>!!cn),defaultSummary:qt,config:o});N(Ct,Qn)||(Ct.textContent=qt);let on=document.createElement("div");on.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(Ct,on),Ot.appendChild(Gt),_t[0].before(Ot),_t.forEach((cn,uo)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),uo<_t.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(cn),on.appendChild(Zn)})})}Cm(Uo,z);let tt=p.some(B=>B.role==="assistant"&&B.streaming),qe=p[p.length-1],ct=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(Io&&p.some(B=>B.role==="user")&&!tt&&!ct){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ca},Be=r.find(ye=>ye.renderLoadingIndicator),Fe=null;if(Be!=null&&Be.renderLoadingIndicator&&(Fe=Be.renderLoadingIndicator(B)),Fe===null&&((Le=o.loadingIndicator)!=null&&Le.render)&&(Fe=o.loadingIndicator.render(B)),Fe===null&&(Fe=ca()),Fe){let ye=document.createElement("div"),_t=((Ue=o.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ye.className=_t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ye.setAttribute("data-typing-indicator","true"),ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ye.appendChild(Fe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(ye),y.appendChild(Ot)}}if(!Io&&p.length>0){let B=p[p.length-1],Be={config:o,lastMessage:B,messageCount:p.length},Fe=r.find(_t=>_t.renderIdleIndicator),ye=null;if(Fe!=null&&Fe.renderIdleIndicator&&(ye=Fe.renderIdleIndicator(Be)),ye===null&&((Ge=o.loadingIndicator)!=null&&Ge.renderIdle)&&(ye=o.loadingIndicator.renderIdle(Be)),ye){let _t=document.createElement("div"),Ot=((wt=o.loadingIndicator)==null?void 0:wt.showBubble)!==!1;_t.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_t.setAttribute("data-idle-indicator","true"),_t.appendChild(ye);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(_t),y.appendChild(Gt)}}if(fi(c,y),fe.length>0)for(let{messageId:B,fingerprint:Be,bubble:Fe}of fe){let ye=c.querySelector(`#wrapper-${B}`);ye&&Fe!==null&&(ye.replaceChildren(Fe),ye.setAttribute("data-bubble-fp",Be),zo.set(B,Be))}if(zo.size>0)for(let B of zo.keys())z.has(B)||zo.delete(B);if(te.length>0)for(let{messageId:B,fingerprint:Be,bubble:Fe}of te){let ye=c.querySelector(`#wrapper-${B}`);ye&&Fe!==null&&(ye.replaceChildren(Fe),ye.setAttribute("data-bubble-fp",Be),Ro.set(B,Be))}if(Ro.size>0)for(let B of Ro.keys())z.has(B)||Ro.delete(B);if(Ae.length>0)for(let{messageId:B,fingerprint:Be,bubble:Fe}of Ae){let ye=c.querySelector(`#wrapper-${B}`);ye&&Fe!==null&&(ye.replaceChildren(Fe),ye.setAttribute("data-bubble-fp",Be),vo.set(B,Be))}if(vo.size>0)for(let B of vo.keys())z.has(B)||vo.delete(B)},sr=null,La=()=>{var h;if(sr)return;let c=y=>{let M=y.composedPath();M.includes(Me)||Xe&&M.includes(Xe)||Ft(!1,"user")};sr=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Ps=()=>{var p;if(!sr)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("pointerdown",sr,!0),sr=null};ht.push(()=>Ps());let ar=null,Ia=()=>{var h;if(ar)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ft(!1,"user"))};ar=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Ws=()=>{var p;if(!ar)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("keydown",ar,!0),ar=null};ht.push(()=>Ws());let ir=!1,Bs=new Set,Ra=()=>{var p,h,y,M;let c=(y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((M=o.features)==null?void 0:M.streamAnimation)},Ko=()=>{var ct,dt,Pe,Le;if(!k())return;let c=We.peekBanner,p=We.peekTextNode;if(!c||!p)return;if(T){c.classList.remove("persona-pill-peek--visible");return}let h=(ct=V==null?void 0:V.getMessages())!=null?ct:[],y;for(let Ue=h.length-1;Ue>=0;Ue--){let Ge=h[Ue];if(Ge.role==="assistant"&&Ge.content){y=Ge;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let M=y.content,O=!!y.streaming,N=Ra(),z=vi(N),F=z.type!=="none"?na(z.type,N==null?void 0:N.plugins):null,we=((dt=F==null?void 0:F.isAnimating)==null?void 0:dt.call(F,y))===!0,fe=F!==null&&(O||we);fe&&F&&!Bs.has(F.name)&&(Il(F,e),Bs.add(F.name));let te=fe&&(F!=null&&F.containerClass)?F.containerClass:null,Te=(Pe=p.dataset.personaPeekStreamClass)!=null?Pe:null;Te&&Te!==te&&(p.classList.remove(Te),delete p.dataset.personaPeekStreamClass),te&&Te!==te&&(p.classList.add(te),p.dataset.personaPeekStreamClass=te),fe?(p.style.setProperty("--persona-stream-step",`${z.speed}ms`),p.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let _e=fe?xi(M,z.buffer,F,y,O):M;if(fe&&z.placeholder==="skeleton"&&O&&(!_e||!_e.trim())){let Ue=document.createElement("div"),Ge=ra();Ge.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(Ge),fi(p,Ue)}else{let Ue=Math.max(0,_e.length-100),Ge=_e.length>100?_e.slice(-100):_e,wt=js(Ge);if(!fe||!F){let B=_e.length>100?`\u2026${Ge}`:Ge;p.textContent!==B&&(p.textContent=B)}else{let B=wt;(F.wrap==="char"||F.wrap==="word")&&(B=oa(wt,F.wrap,`peek-${y.id}`,{skipTags:F.skipTags,startIndex:Ue}));let Be=document.createElement("div");if(Be.innerHTML=B,F.useCaret&&Ge.length>0){let Fe=wi(),ye=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),_t=ye[ye.length-1];_t!=null&&_t.parentNode?_t.parentNode.insertBefore(Fe,_t.nextSibling):Be.appendChild(Fe)}fi(p,Be),(Le=F.onAfterRender)==null||Le.call(F,{container:p,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let qe=Io||ir;c.classList.toggle("persona-pill-peek--visible",qe)};if(k()){let c=We.peekBanner;if(c){let y=M=>{M.preventDefault(),M.stopPropagation(),Ft(!0,"user")};c.addEventListener("pointerdown",y),ht.push(()=>{c.removeEventListener("pointerdown",y)})}let p=()=>{ir||(ir=!0,Ko())},h=()=>{ir&&(ir=!1,Ko())};de.addEventListener("pointerenter",p),de.addEventListener("pointerleave",h),ht.push(()=>{de.removeEventListener("pointerenter",p),de.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),ht.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let Pa=c=>{var Te,_e,Ae,tt,qe,ct,dt,Pe;let p=(_e=(Te=o.launcher)==null?void 0:Te.composerBar)!=null?_e:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",y=(tt=p.bottomOffset)!=null?tt:"16px",M=p.collapsedMaxWidth,O=(qe=p.expandedMaxWidth)!=null?qe:"880px",N=(ct=p.expandedTopOffset)!=null?ct:"5vh",z=(dt=p.modalMaxWidth)!=null?dt:"880px",F=(Pe=p.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",we="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",te=Me.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Xe){let Le=Xe.style;Le.bottom=y,Le.width=M!=null?M:""}if(c&&h!=="fullscreen"){if(h==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=z,te.maxWidth=we,te.maxHeight=F,te.height=F;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${y} + ${fe})`,te.top=N,te.width=O,te.maxWidth=we}},lr=()=>{var F,we,fe,te,Te,_e,Ae,tt;if(!S())return;if(k()){let ct=(fe=((we=(F=o.launcher)==null?void 0:F.composerBar)!=null?we:{}).expandedSize)!=null?fe:"anchored",dt=T?"expanded":"collapsed";Me.dataset.state=dt,Me.dataset.expandedSize=ct,Xe&&(Xe.dataset.state=dt,Xe.dataset.expandedSize=ct),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pa(T),q.style.display=T?"flex":"none",yo(),T?(La(),Ia()):(Ps(),Ws()),Ko();return}let c=xn(o),p=(te=e.ownerDocument.defaultView)!=null?te:window,h=(_e=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?_e:640,y=(tt=(Ae=o.launcher)==null?void 0:Ae.mobileFullscreen)!=null?tt:!0,M=p.innerWidth<=h,O=y&&M&&L,N=Oo(o).reveal;T?(Me.style.removeProperty("display"),Me.style.display=c?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),en?en.element.style.display="none":tn&&(tn.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!O?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),en?en.element.style.display=c?"none":"":tn&&(tn.style.display=c?"none":""))},Ft=(c,p="user")=>{var O,N;if(!S()||T===c)return;let h=T;T=c,lr();let y=(()=>{var Ae,tt,qe,ct,dt,Pe,Le,Ue,Ge,wt;let z=(tt=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?tt:!1,F=(qe=e.ownerDocument.defaultView)!=null?qe:window,we=(dt=(ct=o.launcher)==null?void 0:ct.mobileFullscreen)!=null?dt:!0,fe=(Le=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Le:640,te=F.innerWidth<=fe,Te=xn(o)&&we&&te,_e=k()&&((wt=(Ge=(Ue=o.launcher)==null?void 0:Ue.composerBar)==null?void 0:Ge.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return z||we&&te&&L||Te||_e})();if(T&&y){if(!Qt){let z=e.getRootNode(),F=z instanceof ShadowRoot?z.host:e.closest(".persona-host");F&&(Qt=Rl(F,(N=(O=o.launcher)==null?void 0:O.zIndex)!=null?N:En))}Zt||(Zt=Pl(e.ownerDocument))}else T||(Qt==null||Qt(),Qt=null,Zt==null||Zt(),Zt=null);T&&(Fs(),ft()==="follow"?Bo(!0):Is());let M={open:T,source:p,timestamp:Date.now()};T&&!h?s.emit("widget:opened",M):!T&&h&&s.emit("widget:closed",M),s.emit("widget:state",{open:T,launcherEnabled:L,voiceActive:yt.active,streaming:V.isStreaming()})},Xr=c=>{Xt(c?"stop":"send"),K&&(K.disabled=c),ao.buttons.forEach(p=>{p.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=c)})},Jr=()=>{yt.active||ee&&ee.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Jr(),200)});let Hs=()=>{var h,y,M,O,N,z,F,we,fe,te,Te;no.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",ko.textContent=(O=(M=o.copy)==null?void 0:M.welcomeSubtitle)!=null?O:"Ask anything about your account or products.",ee.placeholder=(z=(N=o.copy)==null?void 0:N.inputPlaceholder)!=null?z:"How can I help...";let c=me.querySelector("[data-persona-intro-card]");if(c){let _e=((F=o.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(me.classList.remove("persona-gap-3"),me.classList.add("persona-gap-6")):(me.classList.remove("persona-gap-6"),me.classList.add("persona-gap-3"))}!((fe=(we=o.sendButton)==null?void 0:we.useIcon)!=null&&fe)&&!(V!=null&&V.isStreaming())&&(ze.textContent=(Te=(te=o.copy)==null?void 0:te.sendButtonLabel)!=null?Te:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.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 co=null,Ke=()=>{co==null&&(co=setInterval(()=>{let c=et.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(co),co=null;return}let p=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=ni(p-y))})},100))};if(V=new ui(o,{onMessagesChanged(c){var y;Cr(et,c,ge),Ke(),V&&(c.some(O=>O.role==="user")?ao.render([],V,ee,c):ao.render(o.suggestionChips,V,ee,c,o.suggestionChipsConfig)),Bo(!Io),Ma(c);let p=[...c].reverse().find(M=>M.role==="user");c.length===0&&wr(),!zr||xr?(zr=!0,qr=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==qr&&(qr=p.id,Ea(p.id));let h=yt.lastUserMessageId;p&&p.id!==h&&(yt.lastUserMessageId=p.id,s.emit("user:message",p)),yt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Gr(c),Ko()},onStatusChanged(c){var y;let p=(y=o.statusIndicator)!=null?y:{};it(sn,(M=>{var O,N,z,F;return M==="idle"?(O=p.idleText)!=null?O:kn.idle:M==="connecting"?(N=p.connectingText)!=null?N:kn.connecting:M==="connected"?(z=p.connectedText)!=null?z:kn.connected:M==="error"?(F=p.errorText)!=null?F:kn.error:kn[M]})(c),p,c)},onStreamingChanged(c){Io=c,Xr(c),V&&Cr(et,V.getMessages(),ge),c||Bo(!0),Ko()},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":cr(),Jf();break;case"speaking":cr(),Qf();break;default:c==="idle"&&V.isBargeInActive()?(cr(),Ds(),K==null||K.setAttribute("aria-label","End voice session")):(yt.active=!1,cr(),lo("system"),On());break}},onArtifactsState(c){qn=c,Gn(),Gr()}}),It.current=V,zr=!0,((yd=(bd=o.voiceRecognition)==null?void 0:bd.provider)==null?void 0:yd.type)==="runtype")try{V.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&V.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(be||o.onSSEEvent)&&V.setSSEEventCallback((c,p)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,p),he==null||he.processEvent(c,p),be==null||be.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=tc(c.metadata),E.syncFromMetadata()),(p=c.messages)!=null&&p.length){xr=!0;try{V.hydrateMessages(c.messages)}finally{xr=!1}}(h=c.artifacts)!=null&&h.length&&V.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let A=()=>{var p,h,y;!k()||T||!((y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ft(!0,"auto")},$=c=>{var M;if(c.preventDefault(),V.isStreaming()){V.cancel(),he==null||he.reset(),j==null||j.update();return}let p=ee.value.trim(),h=(M=St==null?void 0:St.hasAttachments())!=null?M:!1;if(!p&&!h)return;A();let y;h&&(y=[],y.push(...St.getContentParts()),p&&y.push(kl(p))),ee.value="",ee.style.height="auto",Y(),V.sendMessage(p,{contentParts:y}),h&&St.clearAttachments()},W=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Q={...gi},ae=!1,Y=()=>{Q={...gi}},Re=()=>V.getMessages().filter(c=>c.role==="user").map(c=>{var p;return(p=c.content)!=null?p:""}).filter(c=>c.length>0),Oe=c=>{if(!ee)return;ae=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),ae=!1;let p=ee.value.length;ee.setSelectionRange(p,p)},st=()=>{ae||Y()},Qe=c=>{if(ee){if(W()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let p=ee.selectionStart===0&&ee.selectionEnd===0,h=bm({direction:c.key==="ArrowUp"?"up":"down",history:Re(),currentValue:ee.value,atStart:p,state:Q});if(Q=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Oe(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(V.isStreaming()){c.preventDefault();return}Y(),c.preventDefault(),ze.click()}}},Bt=c=>{c.key!=="Escape"||c.isComposing||V.isStreaming()&&c.composedPath().includes(q)&&(V.cancel(),he==null||he.reset(),j==null||j.update(),Y(),c.preventDefault(),c.stopImmediatePropagation())},Vt=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!St)return;let p=Xx(c.clipboardData);p.length!==0&&(c.preventDefault(),await St.handleFiles(p))},Nt=null,lt=!1,Tt=null,$e=null,An=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,mn=(c="user")=>{var O,N,z,F,we,fe,te;if(lt||V.isStreaming())return;let p=An();if(!p)return;Nt=new p;let y=(N=((O=o.voiceRecognition)!=null?O:{}).pauseDuration)!=null?N:2e3;Nt.continuous=!0,Nt.interimResults=!0,Nt.lang="en-US";let M=ee.value;Nt.onresult=Te=>{let _e="",Ae="";for(let qe=0;qe<Te.results.length;qe++){let ct=Te.results[qe],dt=ct[0].transcript;ct.isFinal?_e+=dt+" ":Ae=dt}let tt=M+_e+Ae;ee.value=tt,Tt&&clearTimeout(Tt),(_e||Ae)&&(Tt=window.setTimeout(()=>{let qe=ee.value.trim();qe&&Nt&&lt&&($t(),ee.value="",ee.style.height="auto",V.sendMessage(qe,{viaVoice:!0}))},y))},Nt.onerror=Te=>{Te.error!=="no-speech"&&$t()},Nt.onend=()=>{if(lt){let Te=ee.value.trim();Te&&Te!==M.trim()&&(ee.value="",ee.style.height="auto",V.sendMessage(Te,{viaVoice:!0})),$t()}};try{if(Nt.start(),lt=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),lo(c),On(),K){let Te=(z=o.voiceRecognition)!=null?z:{};$e={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(F=Te.iconName)!=null?F:"mic",iconSize:parseFloat((te=(fe=Te.iconSize)!=null?fe:(we=o.sendButton)==null?void 0:we.size)!=null?te:"40")||24};let _e=Te.recordingBackgroundColor,Ae=Te.recordingIconColor,tt=Te.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let qe=K.querySelector("svg");qe&&qe.setAttribute("stroke",Ae)}tt&&(K.style.borderColor=tt),K.setAttribute("aria-label","Stop voice recognition")}}catch{$t("system")}},$t=(c="user")=>{if(lt){if(lt=!1,Tt&&(clearTimeout(Tt),Tt=null),Nt){try{Nt.stop()}catch{}Nt=null}if(yt.active=!1,lo(c),On(),K){if(K.classList.remove("persona-voice-recording"),$e){K.style.backgroundColor=$e.backgroundColor,K.style.color=$e.color,K.style.borderColor=$e.borderColor;let p=K.querySelector("svg");p&&p.setAttribute("stroke",$e.color||"currentColor"),$e=null}K.setAttribute("aria-label","Start voice recognition")}}},Co=(c,p)=>{var ct,dt,Pe,Le,Ue,Ge,wt,B;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ct=c==null?void 0:c.provider)==null?void 0:ct.type)==="runtype";if(!(h||y))return null;let O=b("div","persona-send-button-wrapper"),N=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let z=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",F=(Pe=p==null?void 0:p.size)!=null?Pe:"40px",we=(Le=c==null?void 0:c.iconSize)!=null?Le:F,fe=parseFloat(we)||24,te=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:p==null?void 0:p.backgroundColor,Te=(Ge=c==null?void 0:c.iconColor)!=null?Ge:p==null?void 0:p.textColor;N.style.width=we,N.style.height=we,N.style.minWidth=we,N.style.minHeight=we,N.style.fontSize="18px",N.style.lineHeight="1",Te?N.style.color=Te:N.style.color="var(--persona-text, #111827)";let Ae=Ee(z,fe,Te||"currentColor",1.5);Ae?N.appendChild(Ae):N.textContent="\u{1F3A4}",te?N.style.backgroundColor=te:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),O.appendChild(N);let tt=(wt=c==null?void 0:c.tooltipText)!=null?wt:"Start voice recognition";if(((B=c==null?void 0:c.showTooltip)!=null?B:!1)&&tt){let Be=b("div","persona-send-button-tooltip");Be.textContent=tt,O.appendChild(Be)}return{micButton:N,micButtonWrapper:O}},ol=()=>{var p,h,y,M,O;if(!K||$e)return;let c=(p=o.voiceRecognition)!=null?p:{};$e={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((O=(M=c.iconSize)!=null?M:(y=o.sendButton)==null?void 0:y.size)!=null?O:"40")||24}},rl=(c,p)=>{var O,N,z,F,we;if(!K)return;let h=K.querySelector("svg");h&&h.remove();let y=(we=$e==null?void 0:$e.iconSize)!=null?we:parseFloat((F=(z=(O=o.voiceRecognition)==null?void 0:O.iconSize)!=null?z:(N=o.sendButton)==null?void 0:N.size)!=null?F:"40")||24,M=Ee(c,y,p,1.5);M&&K.appendChild(M)},Wa=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ds=()=>{var M;if(!K)return;ol();let c=(M=o.voiceRecognition)!=null?M:{},p=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(Wa(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let O=K.querySelector("svg");O&&O.setAttribute("stroke",h)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},Jf=()=>{var z,F,we,fe,te,Te,_e,Ae;if(!K)return;ol();let c=(z=o.voiceRecognition)!=null?z:{},p=V.getVoiceInterruptionMode(),h=(F=c.processingIconName)!=null?F:"loader",y=(fe=(we=c.processingIconColor)!=null?we:$e==null?void 0:$e.color)!=null?fe:"",M=(Te=(te=c.processingBackgroundColor)!=null?te:$e==null?void 0:$e.backgroundColor)!=null?Te:"",O=(Ae=(_e=c.processingBorderColor)!=null?_e:$e==null?void 0:$e.borderColor)!=null?Ae:"";Wa(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=M,K.style.borderColor=O;let N=y||"currentColor";K.style.color=N,rl(h,N),K.setAttribute("aria-label","Processing voice input"),p==="none"&&(K.style.cursor="default")},Qf=()=>{var we,fe,te,Te,_e,Ae,tt,qe,ct,dt,Pe,Le;if(!K)return;ol();let c=(we=o.voiceRecognition)!=null?we:{},p=V.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(fe=c.speakingIconName)!=null?fe:h,M=(Ae=c.speakingIconColor)!=null?Ae:p==="barge-in"?(Te=(te=c.recordingIconColor)!=null?te:$e==null?void 0:$e.color)!=null?Te:"":(_e=$e==null?void 0:$e.color)!=null?_e:"",O=(ct=c.speakingBackgroundColor)!=null?ct:p==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(qe=$e==null?void 0:$e.backgroundColor)!=null?qe:"",N=(Le=c.speakingBorderColor)!=null?Le:p==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=$e==null?void 0:$e.borderColor)!=null?Pe:"";Wa(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=O,K.style.borderColor=N;let z=M||"currentColor";K.style.color=z,rl(y,z);let F=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",F),p==="none"&&(K.style.cursor="default"),p==="barge-in"&&K.classList.add("persona-voice-recording")},cr=()=>{var c,p,h;K&&(Wa(),$e&&(K.style.backgroundColor=(c=$e.backgroundColor)!=null?c:"",K.style.color=(p=$e.color)!=null?p:"",K.style.borderColor=(h=$e.borderColor)!=null?h:"",rl($e.iconName,$e.color||"currentColor"),$e=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Ba=()=>{var c,p;if(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"){let h=V.getVoiceStatus(),y=V.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,On(),lo("user"),cr()});return}V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),yt.manuallyDeactivated=!V.isVoiceActive(),On(),lo("user"),V.isVoiceActive()?Ds():cr()});return}if(lt){let h=ee.value.trim();yt.manuallyDeactivated=!0,On(),$t("user"),h&&(ee.value="",ee.style.height="auto",V.sendMessage(h))}else yt.manuallyDeactivated=!1,On(),mn("user")};$n=Ba,K&&(K.addEventListener("click",Ba),ht.push(()=>{var c,p;((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),cr()):$t("system"),K&&K.removeEventListener("click",Ba)}));let Zf=s.on("assistant:complete",()=>{Ss&&(yt.active||yt.manuallyDeactivated||Ss==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,p;!yt.active&&!yt.manuallyDeactivated&&(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),lo("auto"),V.isVoiceActive()&&Ds()}):mn("auto"))},600))});ht.push(Zf);let eg=s.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});ht.push(eg);let Qr=()=>{Ft(!T,"user")},en=null,tn=null;if(L&&!k()){let c=r.find(p=>p.renderLauncher);if(c!=null&&c.renderLauncher){let p=c.renderLauncher({config:o,defaultRenderer:()=>ia(o,Qr).element,onToggle:Qr});p&&(tn=p)}tn||(en=ia(o,Qr))}en?e.appendChild(en.element):tn&&e.appendChild(tn),lr(),ao.render(o.suggestionChips,V,ee,void 0,o.suggestionChipsConfig),Hs(),Xr(V.isStreaming()),ft()==="follow"?Bo(!0):Is(),Ca(),R&&(!L||k()?setTimeout(()=>Jr(),0):T&&setTimeout(()=>Jr(),200));let Fs=()=>{var F,we,fe,te,Te,_e,Ae,tt,qe,ct,dt,Pe,Le,Ue,Ge,wt,B,Be,Fe,ye,_t,Ot;if(k()){bn(),lr();return}let c=xn(o),p=(we=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?we:!1,h=c||p||((te=(fe=o.launcher)==null?void 0:fe.fullHeight)!=null?te:!1),y=(Te=e.ownerDocument.defaultView)!=null?Te:window,M=(Ae=(_e=o.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ae:!0,O=(qe=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?qe:640,N=y.innerWidth<=O,z=M&&N&&L;try{if(z){yo(),os(e,o);return}if(x&&(x=!1,yo(),os(e,o)),!L&&!c){de.style.height="",de.style.width="";return}if(!p&&!c){let Gt=(dt=(ct=o==null?void 0:o.launcher)==null?void 0:ct.width)!=null?dt:o==null?void 0:o.launcherWidth,Ct=Gt!=null?Gt:fo;de.style.width=Ct,de.style.maxWidth=Ct}if(Lo(),!h){let Gt=y.innerHeight,Ct=64,qt=(Le=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Le:0,Qn=Math.max(200,Gt-Ct),on=Math.min(640,Qn),Ye=Math.max(200,on-qt);de.style.height=`${Ye}px`}}finally{if(bn(),lr(),T&&L){let Ct=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((wt=(Ge=o.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?wt:640),qt=(Be=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Be:!1,Qn=(ye=(Fe=o.launcher)==null?void 0:Fe.mobileFullscreen)!=null?ye:!0,on=xn(o)&&Qn&&Ct,Ye=qt||Qn&&Ct&&L||on;if(Ye&&!Zt){let Pt=e.getRootNode(),cn=Pt instanceof ShadowRoot?Pt.host:e.closest(".persona-host");cn&&!Qt&&(Qt=Rl(cn,(Ot=(_t=o.launcher)==null?void 0:_t.zIndex)!=null?Ot:En)),Zt=Pl(e.ownerDocument)}else Ye||(Qt==null||Qt(),Qt=null,Zt==null||Zt(),Zt=null)}}};Fs();let hc=(vd=e.ownerDocument.defaultView)!=null?vd:window;if(hc.addEventListener("resize",Fs),ht.push(()=>hc.removeEventListener("resize",Fs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bn()});c.observe(Ve),ht.push(()=>c.disconnect())}Jn=me.scrollTop;let bc=Xo(me),tg=()=>{let c=me.getRootNode(),p=typeof c.getSelection=="function"?c.getSelection():null;return p!=null?p:me.ownerDocument.getSelection()},sl=()=>Sm(tg(),me),yc=()=>{let c=me.scrollTop,p=Xo(me),h=p<bc;if(bc=p,ft()!=="follow"){Jn=c,Nn();return}let{action:y,nextLastScrollTop:M}=bi({following:Xn.isFollowing(),currentScrollTop:c,lastScrollTop:Jn,nearBottom:Hr(me,jr),userScrollThreshold:xa,isAutoScrolling:wo||vr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Jn=M,y==="resume"){sl()||Wo();return}y==="pause"&&Yr()};if(me.addEventListener("scroll",yc,{passive:!0}),ht.push(()=>me.removeEventListener("scroll",yc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{ka()});c.observe(et),c.observe(me),ht.push(()=>c.disconnect())}let vc=()=>{ft()==="follow"&&Xn.isFollowing()&&sl()&&Yr()},xc=me.ownerDocument;xc.addEventListener("selectionchange",vc),ht.push(()=>{xc.removeEventListener("selectionchange",vc)});let wc=c=>{if(ft()!=="follow")return;let p=yi({following:Xn.isFollowing(),deltaY:c.deltaY,nearBottom:Hr(me,jr),resumeWhenNearBottom:!0});p==="pause"?Yr():p==="resume"&&!sl()&&Wo()};me.addEventListener("wheel",wc,{passive:!0}),ht.push(()=>me.removeEventListener("wheel",wc)),Je.addEventListener("click",()=>{wr(),me.scrollTop=me.scrollHeight,Jn=me.scrollTop,Wo(),Bo(!0),Nn()}),ht.push(()=>Je.remove()),ht.push(()=>{Ts(),wr()});let Cc=()=>{D&&(io&&(D.removeEventListener("click",io),io=null),S()?(D.style.display="",io=()=>{Ft(!1,"user")},D.addEventListener("click",io)):D.style.display="none")};Cc(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{V.clearMessages(),Uo.clear(),Wo(),gs(We.composerOverlay);try{localStorage.removeItem(bs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==bs)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={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()})})(),Ht&&Ht.addEventListener("submit",$),ee==null||ee.addEventListener("keydown",Qe),ee==null||ee.addEventListener("input",st),ee==null||ee.addEventListener("paste",Vt);let Sc=(xd=e.ownerDocument)!=null?xd:document;Sc.addEventListener("keydown",Bt,!0);let Ac="persona-attachment-drop-active",Os=0,al=()=>{Os=0,q.classList.remove(Ac)},Zr=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&St!==null},Tc=c=>{!Vi(c.dataTransfer)||!Zr()||(Os++,Os===1&&q.classList.add(Ac))},kc=c=>{!Vi(c.dataTransfer)||!Zr()||(Os--,Os<=0&&al())},Ec=c=>{!Vi(c.dataTransfer)||!Zr()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Mc=c=>{var h;if(!Vi(c.dataTransfer)||!Zr())return;c.preventDefault(),c.stopPropagation(),al();let p=Array.from((h=c.dataTransfer.files)!=null?h:[]);p.length!==0&&St.handleFiles(p)},dr=!0;q.addEventListener("dragenter",Tc,dr),q.addEventListener("dragleave",kc,dr),e.addEventListener("dragover",Ec,dr),e.addEventListener("drop",Mc,dr);let Ha=e.ownerDocument,Lc=c=>{Zr()&&c.preventDefault()},Ic=c=>{Zr()&&c.preventDefault()};Ha.addEventListener("dragover",Lc),Ha.addEventListener("drop",Ic),ht.push(()=>{Ht&&Ht.removeEventListener("submit",$),ee==null||ee.removeEventListener("keydown",Qe),ee==null||ee.removeEventListener("input",st),ee==null||ee.removeEventListener("paste",Vt),Sc.removeEventListener("keydown",Bt,!0)}),ht.push(()=>{q.removeEventListener("dragenter",Tc,dr),q.removeEventListener("dragleave",kc,dr),e.removeEventListener("dragover",Ec,dr),e.removeEventListener("drop",Mc,dr),Ha.removeEventListener("dragover",Lc),Ha.removeEventListener("drop",Ic),al()}),ht.push(()=>{V.cancel()}),en?ht.push(()=>{en==null||en.destroy()}):tn&&ht.push(()=>{tn==null||tn.remove()});let ln={update(c){var Ho,pn,Wn,mo,kr,Er,Da,Ns,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,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;let p=o.toolCall,h=o.messageActions,y=(Ho=o.layout)==null?void 0:Ho.messages,M=o.colorScheme,O=o.loadingIndicator,N=o.iterationDisplay,z=(pn=o.features)==null?void 0:pn.showReasoning,F=(Wn=o.features)==null?void 0:Wn.showToolCalls,we=(mo=o.features)==null?void 0:mo.toolCallDisplay,fe=(kr=o.features)==null?void 0:kr.reasoningDisplay;o={...o,...c},yo(),os(e,o),Ni(e,o),_i(e,o),Gn(),o.colorScheme!==M&&or();let te=Jl.getForInstance(o.plugins);r.length=0,r.push(...te),L=(Da=(Er=o.launcher)==null?void 0:Er.enabled)!=null?Da:!0,I=(Ed=(Ns=o.launcher)==null?void 0:Ns.autoExpand)!=null?Ed:!1,ue=(Ld=(Md=o.features)==null?void 0:Md.showReasoning)!=null?Ld:!0,ce=(Rd=(Id=o.features)==null?void 0:Id.showToolCalls)!=null?Rd:!0,ve=(Wd=(Pd=o.features)==null?void 0:Pd.scrollToBottom)!=null?Wd:{};let Te=ft();He=(Hd=(Bd=o.features)==null?void 0:Bd.scrollBehavior)!=null?Hd:{},Te!==ft()&&(wr(),Wo()),Eo(),Nn();let _e=ke;if(ke=(Fd=(Dd=o.features)==null?void 0:Dd.showEventStreamToggle)!=null?Fd:!1,ke&&!_e){if(be||(X=new ua(ie),be=new pa(re,X),he=he!=null?he:new ma,X.open().then(()=>be==null?void 0:be.restore()).catch(()=>{}),V.setSSEEventCallback((J,kt)=>{var Ut;(Ut=o.onSSEEvent)==null||Ut.call(o,J,kt),he==null||he.processEvent(J,kt),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!xt&&Ne){let J=(Nd=(Od=o.features)==null?void 0:Od.eventStream)==null?void 0:Nd.classNames,kt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");xt=b("button",kt),xt.style.width="28px",xt.style.height="28px",xt.style.color=Hn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Ut=Ee("activity","18px","currentColor",1.5);Ut&&xt.appendChild(Ut);let mt=We.clearChatButtonWrapper,Wt=We.closeButtonWrapper,fn=mt||Wt;fn&&fn.parentNode===Ne?Ne.insertBefore(xt,fn):Ne.appendChild(xt),xt.addEventListener("click",()=>{se?bo():No()})}}else!ke&&_e&&(bo(),xt&&(xt.remove(),xt=null),be==null||be.clear(),X==null||X.destroy(),be=null,X=null,he==null||he.reset(),he=null);if(((_d=o.launcher)==null?void 0:_d.enabled)===!1&&en&&(en.destroy(),en=null),((Vd=o.launcher)==null?void 0:Vd.enabled)===!1&&tn&&(tn.remove(),tn=null),(($d=o.launcher)==null?void 0:$d.enabled)!==!1&&!en&&!tn){let J=r.find(kt=>kt.renderLauncher);if(J!=null&&J.renderLauncher){let kt=J.renderLauncher({config:o,defaultRenderer:()=>ia(o,Qr).element,onToggle:Qr});kt&&(tn=kt,e.appendChild(tn))}tn||(en=ia(o,Qr),e.appendChild(en.element))}en&&en.update(o),De&&((Ud=o.launcher)==null?void 0:Ud.title)!==void 0&&(De.textContent=o.launcher.title),je&&((zd=o.launcher)==null?void 0:zd.subtitle)!==void 0&&(je.textContent=o.launcher.subtitle);let Ae=(qd=o.layout)==null?void 0:qd.header;if((Ae==null?void 0:Ae.layout)!==w&&Ne){let J=Ae?Ti(o,Ae,{showClose:S(),onClose:()=>Ft(!1,"user")}):Dr({config:o,showClose:S(),onClose:()=>Ft(!1,"user")});Ne.replaceWith(J.header),Ne=J.header,pe=J.iconHolder,De=J.headerTitle,je=J.headerSubtitle,D=J.closeButton,w=Ae==null?void 0:Ae.layout}else if(Ae&&(pe&&(pe.style.display=Ae.showIcon===!1?"none":""),De&&(De.style.display=Ae.showTitle===!1?"none":""),je&&(je.style.display=Ae.showSubtitle===!1?"none":""),D&&(D.style.display=Ae.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let J=Ae.showClearChat;if(J!==void 0){We.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:kt}=We;kt&&!kt.classList.contains("persona-absolute")&&(J?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let qe=((jd=o.layout)==null?void 0:jd.showHeader)!==!1;Ne&&(Ne.style.display=qe?"":"none");let ct=((Kd=o.layout)==null?void 0:Kd.showFooter)!==!1;Ve&&(Ve.style.display=ct?"":"none"),bn(),Nn(),L!==P?L?Ft(I,"auto"):(T=!0,lr()):I!==H&&Ft(I,"auto"),H=I,P=L,Fs(),Cc();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(p),Ue=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((Gd=o.layout)==null?void 0:Gd.messages)!==JSON.stringify(y),wt=((Yd=o.loadingIndicator)==null?void 0:Yd.render)!==(O==null?void 0:O.render)||((Xd=o.loadingIndicator)==null?void 0:Xd.renderIdle)!==(O==null?void 0:O.renderIdle)||((Jd=o.loadingIndicator)==null?void 0:Jd.showBubble)!==(O==null?void 0:O.showBubble),B=o.iterationDisplay!==N,Be=((Zd=(Qd=o.features)==null?void 0:Qd.showReasoning)!=null?Zd:!0)!==(z!=null?z:!0)||((tp=(ep=o.features)==null?void 0:ep.showToolCalls)!=null?tp:!0)!==(F!=null?F:!0)||JSON.stringify((np=o.features)==null?void 0:np.toolCallDisplay)!==JSON.stringify(we)||JSON.stringify((op=o.features)==null?void 0:op.reasoningDisplay)!==JSON.stringify(fe);(Le||Ue||Ge||wt||B||Be)&&V&&(Cs++,Cr(et,V.getMessages(),ge));let ye=(rp=o.launcher)!=null?rp:{},_t=(sp=ye.headerIconHidden)!=null?sp:!1,Ot=(ip=(ap=o.layout)==null?void 0:ap.header)==null?void 0:ip.showIcon,Gt=_t||Ot===!1,Ct=ye.headerIconName,qt=(lp=ye.headerIconSize)!=null?lp:"48px";if(pe){let J=q.querySelector(".persona-border-b-persona-divider"),kt=J==null?void 0:J.querySelector(".persona-flex-col");if(Gt)pe.style.display="none",J&&kt&&!J.contains(kt)&&J.insertBefore(kt,J.firstChild);else{if(pe.style.display="",pe.style.height=qt,pe.style.width=qt,J&&kt&&(J.contains(pe)?pe.nextSibling!==kt&&(pe.remove(),J.insertBefore(pe,kt)):J.insertBefore(pe,kt)),Ct){let mt=parseFloat(qt)||24,Wt=Ee(Ct,mt*.6,"#ffffff",2);Wt?pe.replaceChildren(Wt):pe.textContent=(cp=ye.agentIconText)!=null?cp:"\u{1F4AC}"}else if(ye.iconUrl){let mt=pe.querySelector("img");if(mt)mt.src=ye.iconUrl,mt.style.height=qt,mt.style.width=qt;else{let Wt=document.createElement("img");Wt.src=ye.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=qt,Wt.style.width=qt,pe.replaceChildren(Wt)}}else{let mt=pe.querySelector("svg"),Wt=pe.querySelector("img");(mt||Wt)&&pe.replaceChildren(),pe.textContent=(dp=ye.agentIconText)!=null?dp:"\u{1F4AC}"}let Ut=pe.querySelector("img");Ut&&(Ut.style.height=qt,Ut.style.width=qt)}}let Qn=(up=(pp=o.layout)==null?void 0:pp.header)==null?void 0:up.showTitle,on=(fp=(mp=o.layout)==null?void 0:mp.header)==null?void 0:fp.showSubtitle;if(De&&(De.style.display=Qn===!1?"none":""),je&&(je.style.display=on===!1?"none":""),D){((hp=(gp=o.layout)==null?void 0:gp.header)==null?void 0:hp.showCloseButton)===!1?D.style.display="none":D.style.display="";let kt=(bp=ye.closeButtonSize)!=null?bp:"32px",Ut=(yp=ye.closeButtonPlacement)!=null?yp:"inline";D.style.height=kt,D.style.width=kt;let{closeButtonWrapper:mt}=We,Wt=Ut==="top-right",fn=mt==null?void 0:mt.classList.contains("persona-absolute");if(mt&&Wt!==fn)if(mt.remove(),Wt)mt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",q.style.position="relative",q.appendChild(mt);else{let gt=(xp=(vp=ye.clearChat)==null?void 0:vp.placement)!=null?xp:"inline",gn=(Cp=(wp=ye.clearChat)==null?void 0:wp.enabled)!=null?Cp:!0;mt.className=gn&&gt==="inline"?"":"persona-ml-auto";let Vn=q.querySelector(".persona-border-b-persona-divider");Vn&&Vn.appendChild(mt)}if(D.style.color=ye.closeButtonColor||Hn.actionIconColor,ye.closeButtonBackgroundColor?(D.style.backgroundColor=ye.closeButtonBackgroundColor,D.classList.remove("hover:persona-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let gt=ye.closeButtonBorderWidth||"0px",gn=ye.closeButtonBorderColor||"transparent";D.style.border=`${gt} solid ${gn}`,D.classList.remove("persona-border-none")}else D.style.border="",D.classList.add("persona-border-none");ye.closeButtonBorderRadius?(D.style.borderRadius=ye.closeButtonBorderRadius,D.classList.remove("persona-rounded-full")):(D.style.borderRadius="",D.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(D.style.paddingLeft=ye.closeButtonPaddingX,D.style.paddingRight=ye.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ye.closeButtonPaddingY?(D.style.paddingTop=ye.closeButtonPaddingY,D.style.paddingBottom=ye.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Tn=(Sp=ye.closeButtonIconName)!=null?Sp:"x",So=(Ap=ye.closeButtonIconText)!=null?Ap:"\xD7";D.innerHTML="";let Bn=Ee(Tn,"28px","currentColor",1);Bn?D.appendChild(Bn):D.textContent=So;let nn=(Tp=ye.closeButtonTooltipText)!=null?Tp:"Close chat",eo=(kp=ye.closeButtonShowTooltip)!=null?kp:!0;if(D.setAttribute("aria-label",nn),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),eo&&nn)){let gt=null,gn=()=>{if(gt||!D)return;let Mr=D.ownerDocument,_s=Mr.body;if(!_s)return;gt=Fo(Mr,"div","persona-clear-chat-tooltip"),gt.textContent=nn;let Vs=Fo(Mr,"div");Vs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Vs);let Lr=D.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(mr),gt.style.left=`${Lr.left+Lr.width/2}px`,gt.style.top=`${Lr.top-8}px`,gt.style.transform="translate(-50%, -100%)",_s.appendChild(gt)},Vn=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};mt.addEventListener("mouseenter",gn),mt.addEventListener("mouseleave",Vn),D.addEventListener("focus",gn),D.addEventListener("blur",Vn),mt._cleanupTooltip=()=>{Vn(),mt&&(mt.removeEventListener("mouseenter",gn),mt.removeEventListener("mouseleave",Vn)),D&&(D.removeEventListener("focus",gn),D.removeEventListener("blur",Vn))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Pt}=We;if(Ye){let J=(Ep=ye.clearChat)!=null?Ep:{},kt=(Mp=J.enabled)!=null?Mp:!0,Ut=(Ip=(Lp=o.layout)==null?void 0:Lp.header)==null?void 0:Ip.showClearChat,mt=Ut!==void 0?Ut:kt,Wt=(Rp=J.placement)!=null?Rp:"inline";if(Pt){Pt.style.display=mt?"":"none";let{closeButtonWrapper:fn}=We;!k()&&fn&&!fn.classList.contains("persona-absolute")&&(mt?fn.classList.remove("persona-ml-auto"):fn.classList.add("persona-ml-auto"));let Tn=Wt==="top-right",So=Pt.classList.contains("persona-absolute");if(!k()&&Tn!==So&&mt){if(Pt.remove(),Tn)Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px",q.style.position="relative",q.appendChild(Pt);else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let nn=q.querySelector(".persona-border-b-persona-divider"),eo=We.closeButtonWrapper;nn&&eo&&eo.parentElement===nn?nn.insertBefore(Pt,eo):nn&&nn.appendChild(Pt)}let Bn=We.closeButtonWrapper;Bn&&!Bn.classList.contains("persona-absolute")&&(Tn?Bn.classList.add("persona-ml-auto"):Bn.classList.remove("persona-ml-auto"))}}if(mt){if(!k()){let gt=(Pp=J.size)!=null?Pp:"32px";Ye.style.height=gt,Ye.style.width=gt}let fn=(Wp=J.iconName)!=null?Wp:"refresh-cw",Tn=(Bp=J.iconColor)!=null?Bp:"";Ye.style.color=Tn||Hn.actionIconColor,Ye.innerHTML="";let So=k()?"14px":"20px",Bn=Ee(fn,So,"currentColor",2);if(Bn&&Ye.appendChild(Bn),J.backgroundColor?(Ye.style.backgroundColor=J.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let gt=J.borderWidth||"0px",gn=J.borderColor||"transparent";Ye.style.border=`${gt} solid ${gn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");J.borderRadius?(Ye.style.borderRadius=J.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),J.paddingX?(Ye.style.paddingLeft=J.paddingX,Ye.style.paddingRight=J.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),J.paddingY?(Ye.style.paddingTop=J.paddingY,Ye.style.paddingBottom=J.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let nn=(Hp=J.tooltipText)!=null?Hp:"Clear chat",eo=(Dp=J.showTooltip)!=null?Dp:!0;if(Ye.setAttribute("aria-label",nn),Pt&&(Pt._cleanupTooltip&&(Pt._cleanupTooltip(),delete Pt._cleanupTooltip),eo&&nn)){let gt=null,gn=()=>{if(gt||!Ye)return;let Mr=Ye.ownerDocument,_s=Mr.body;if(!_s)return;gt=Fo(Mr,"div","persona-clear-chat-tooltip"),gt.textContent=nn;let Vs=Fo(Mr,"div");Vs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Vs);let Lr=Ye.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(mr),gt.style.left=`${Lr.left+Lr.width/2}px`,gt.style.top=`${Lr.top-8}px`,gt.style.transform="translate(-50%, -100%)",_s.appendChild(gt)},Vn=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};Pt.addEventListener("mouseenter",gn),Pt.addEventListener("mouseleave",Vn),Ye.addEventListener("focus",gn),Ye.addEventListener("blur",Vn),Pt._cleanupTooltip=()=>{Vn(),Pt&&(Pt.removeEventListener("mouseenter",gn),Pt.removeEventListener("mouseleave",Vn)),Ye&&(Ye.removeEventListener("focus",gn),Ye.removeEventListener("blur",Vn))}}}}let cn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zl],uo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[fa.message,fa.messageAndClick];E=ec({parsers:cn,handlers:uo,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ge=Tf(o,E,G),V.updateConfig(o),Cr(et,V.getMessages(),ge),ao.render(o.suggestionChips,V,ee,void 0,o.suggestionChipsConfig),Hs(),Xr(V.isStreaming());let Zn=((Fp=o.voiceRecognition)==null?void 0:Fp.enabled)===!0,Sr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ar=((Np=(Op=o.voiceRecognition)==null?void 0:Op.provider)==null?void 0:Np.type)==="runtype";if(Zn&&(Sr||Ar))if(!K||!vt){let J=Co(o.voiceRecognition,o.sendButton);J&&(K=J.micButton,vt=J.micButtonWrapper,jt.insertBefore(vt,Dn),K.addEventListener("click",Ba),K.disabled=V.isStreaming())}else{let J=(_p=o.voiceRecognition)!=null?_p:{},kt=(Vp=o.sendButton)!=null?Vp:{},Ut=($p=J.iconName)!=null?$p:"mic",mt=(Up=kt.size)!=null?Up:"40px",Wt=(zp=J.iconSize)!=null?zp:mt,fn=parseFloat(Wt)||24;K.style.width=Wt,K.style.height=Wt,K.style.minWidth=Wt,K.style.minHeight=Wt;let Tn=(jp=(qp=J.iconColor)!=null?qp:kt.textColor)!=null?jp:"currentColor";K.innerHTML="";let So=Ee(Ut,fn,Tn,2);So?K.appendChild(So):K.textContent="\u{1F3A4}";let Bn=(Kp=J.backgroundColor)!=null?Kp:kt.backgroundColor;Bn?K.style.backgroundColor=Bn:K.style.backgroundColor="",Tn?K.style.color=Tn:K.style.color="var(--persona-text, #111827)",J.borderWidth?(K.style.borderWidth=J.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),J.borderColor?K.style.borderColor=J.borderColor:K.style.borderColor="",J.paddingX?(K.style.paddingLeft=J.paddingX,K.style.paddingRight=J.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),J.paddingY?(K.style.paddingTop=J.paddingY,K.style.paddingBottom=J.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let nn=vt==null?void 0:vt.querySelector(".persona-send-button-tooltip"),eo=(Gp=J.tooltipText)!=null?Gp:"Start voice recognition";if(((Yp=J.showTooltip)!=null?Yp:!1)&&eo)if(nn)nn.textContent=eo,nn.style.display="";else{let gn=document.createElement("div");gn.className="persona-send-button-tooltip",gn.textContent=eo,vt==null||vt.insertBefore(gn,K)}else nn&&(nn.style.display="none");vt.style.display="",K.disabled=V.isStreaming()}else K&&vt&&(vt.style.display="none",((Jp=(Xp=o.voiceRecognition)==null?void 0:Xp.provider)==null?void 0:Jp.type)==="runtype"?V.isVoiceActive()&&V.toggleVoice():lt&&$t());if(((Qp=o.attachments)==null?void 0:Qp.enabled)===!0)if(!Ce||!rt){let J=(Zp=o.attachments)!=null?Zp:{},Ut=(tu=((eu=o.sendButton)!=null?eu:{}).size)!=null?tu:"40px";Ze||(Ze=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",Ht.insertBefore(Ze,ee)),le||(le=document.createElement("input"),le.type="file",le.accept=((nu=J.allowedTypes)!=null?nu:Yo).join(","),le.multiple=((ou=J.maxFiles)!=null?ou:4)>1,le.style.display="none",le.setAttribute("aria-label","Attach files"),Ht.insertBefore(le,ee)),Ce=b("div","persona-send-button-wrapper"),rt=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),rt.type="button",rt.setAttribute("aria-label",(ru=J.buttonTooltipText)!=null?ru:"Attach file");let mt=(su=J.buttonIconName)!=null?su:"paperclip",Wt=Ut,fn=parseFloat(Wt)||40,Tn=Math.round(fn*.6);rt.style.width=Wt,rt.style.height=Wt,rt.style.minWidth=Wt,rt.style.minHeight=Wt,rt.style.fontSize="18px",rt.style.lineHeight="1",rt.style.backgroundColor="transparent",rt.style.color="var(--persona-primary, #111827)",rt.style.border="none",rt.style.borderRadius="6px",rt.style.transition="background-color 0.15s ease",rt.addEventListener("mouseenter",()=>{rt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),rt.addEventListener("mouseleave",()=>{rt.style.backgroundColor="transparent"});let So=Ee(mt,Tn,"currentColor",1.5);So?rt.appendChild(So):rt.textContent="\u{1F4CE}",rt.addEventListener("click",eo=>{eo.preventDefault(),le==null||le.click()}),Ce.appendChild(rt);let Bn=(au=J.buttonTooltipText)!=null?au:"Attach file",nn=b("div","persona-send-button-tooltip");nn.textContent=Bn,Ce.appendChild(nn),Rt.append(Ce),!St&&le&&Ze&&(St=ea.fromConfig(J),St.setPreviewsContainer(Ze),le.addEventListener("change",async()=>{St&&(le!=null&&le.files)&&(await St.handleFileSelect(le.files),le.value="")})),q.querySelector(".persona-attachment-drop-overlay")||q.appendChild(kf(J.dropOverlay))}else{Ce.style.display="";let J=(iu=o.attachments)!=null?iu:{};le&&(le.accept=((lu=J.allowedTypes)!=null?lu:Yo).join(","),le.multiple=((cu=J.maxFiles)!=null?cu:4)>1),St&&St.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else Ce&&(Ce.style.display="none"),St&&St.clearAttachments(),(du=q.querySelector(".persona-attachment-drop-overlay"))==null||du.remove();let Yt=(pu=o.sendButton)!=null?pu:{},Tr=(uu=Yt.useIcon)!=null?uu:!1,pr=(mu=Yt.iconText)!=null?mu:"\u2191",ur=Yt.iconName,Go=(fu=Yt.tooltipText)!=null?fu:"Send message",ot=(gu=Yt.showTooltip)!=null?gu:!1,vn=(hu=Yt.size)!=null?hu:"40px",Pn=Yt.backgroundColor,rn=Yt.textColor;if(Tr){if(ze.style.width=vn,ze.style.height=vn,ze.style.minWidth=vn,ze.style.minHeight=vn,ze.style.fontSize="18px",ze.style.lineHeight="1",ze.innerHTML="",rn?ze.style.color=rn:ze.style.color="var(--persona-button-primary-fg, #ffffff)",ur){let J=parseFloat(vn)||24,kt=(rn==null?void 0:rn.trim())||"currentColor",Ut=Ee(ur,J,kt,2);Ut?ze.appendChild(Ut):ze.textContent=pr}else ze.textContent=pr;ze.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Pn?(ze.style.backgroundColor=Pn,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=(yu=(bu=o.copy)==null?void 0:bu.sendButtonLabel)!=null?yu:"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.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",Pn?(ze.style.backgroundColor=Pn,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),rn?ze.style.color=rn:ze.classList.add("persona-text-white");Yt.borderWidth?(ze.style.borderWidth=Yt.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),Yt.borderColor?ze.style.borderColor=Yt.borderColor:ze.style.borderColor="",Yt.paddingX?(ze.style.paddingLeft=Yt.paddingX,ze.style.paddingRight=Yt.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Yt.paddingY?(ze.style.paddingTop=Yt.paddingY,ze.style.paddingBottom=Yt.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let pt=Dn==null?void 0:Dn.querySelector(".persona-send-button-tooltip");if(ot&&Go)if(pt)pt.textContent=Go,pt.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Go,Dn==null||Dn.insertBefore(J,ze)}else pt&&(pt.style.display="none");let bt=(Su=(vu=o.layout)==null?void 0:vu.contentMaxWidth)!=null?Su:k()?(Cu=(wu=(xu=o.launcher)==null?void 0:xu.composerBar)==null?void 0:wu.contentMaxWidth)!=null?Cu:"720px":void 0;bt?(et.style.maxWidth=bt,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%",Ht&&(Ht.style.maxWidth=bt,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Et&&(Et.style.maxWidth=bt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(et.style.maxWidth="",et.style.marginLeft="",et.style.marginRight="",et.style.width="",Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let ut=(Au=o.statusIndicator)!=null?Au:{},_n=(Tu=ut.visible)!=null?Tu:!0;if(sn.style.display=_n?"":"none",V){let J=V.getStatus();it(sn,(Ut=>{var mt,Wt,fn,Tn;return Ut==="idle"?(mt=ut.idleText)!=null?mt:kn.idle:Ut==="connecting"?(Wt=ut.connectingText)!=null?Wt:kn.connecting:Ut==="connected"?(fn=ut.connectedText)!=null?fn:kn.connected:Ut==="error"?(Tn=ut.errorText)!=null?Tn:kn.error:kn[Ut]})(J),ut,J)}sn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let dn=ut.align==="left"?"persona-text-left":ut.align==="center"?"persona-text-center":"persona-text-right";sn.classList.add(dn)},open(){S()&&Ft(!0,"api")},close(){S()&&Ft(!1,"api")},toggle(){S()&&Ft(!T,"api")},clearChat(){In=!1,V.clearMessages(),Uo.clear(),Wo();try{localStorage.removeItem(bs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==bs)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={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()},setMessage(c){return!ee||V.isStreaming()?!1:(!T&&S()&&Ft(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(V.isStreaming())return!1;let p=(c==null?void 0:c.trim())||ee.value.trim();return p?(!T&&S()&&Ft(!0,"system"),ee.value="",ee.style.height="auto",V.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return V.isStreaming()?!1:((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(V.isVoiceActive()||(!T&&S()&&Ft(!0,"system"),yt.manuallyDeactivated=!1,On(),V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),lo("user"),V.isVoiceActive()&&Ds()})),!0):lt?!0:An()?(!T&&S()&&Ft(!0,"system"),yt.manuallyDeactivated=!1,On(),mn("user"),!0):!1},stopVoiceRecognition(){var c,p;return((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,On(),lo("user"),cr()}),!0):!1:lt?(yt.manuallyDeactivated=!0,On(),$t("user"),!0):!1},injectMessage(c){return!T&&S()&&Ft(!0,"system"),V.injectMessage(c)},injectAssistantMessage(c){!T&&S()&&Ft(!0,"system");let p=V.injectAssistantMessage(c);return _&&(_=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),p},injectUserMessage(c){return!T&&S()&&Ft(!0,"system"),V.injectUserMessage(c)},injectSystemMessage(c){return!T&&S()&&Ft(!0,"system"),V.injectSystemMessage(c)},injectMessageBatch(c){return!T&&S()&&Ft(!0,"system"),V.injectMessageBatch(c)},injectComponentDirective(c){return!T&&S()&&Ft(!0,"system"),V.injectComponentDirective(c)},injectTestMessage(c){!T&&S()&&Ft(!0,"system"),V.injectTestEvent(c)},async connectStream(c,p){return V.connectStream(c,p)},__pushEventStreamEvent(c){be&&(he==null||he.processEvent(c.type,c.payload),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ke||!be||No()},hideEventStream(){se&&bo()},isEventStreamVisible(){return se},showArtifacts(){ho(o)&&(In=!1,Gn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){ho(o)&&(In=!0,Gn())},upsertArtifact(c){return ho(o)?(In=!1,V.upsertArtifact(c)):null},selectArtifact(c){ho(o)&&V.selectArtifact(c)},clearArtifacts(){ho(o)&&V.clearArtifacts()},getArtifacts(){var c;return(c=V==null?void 0:V.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=V==null?void 0:V.getSelectedArtifactId())!=null?c:null},focusInput(){return L&&!T&&!k()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,p,h){let M=V.getMessages().find(O=>{var N;return O.variant==="approval"&&((N=O.approval)==null?void 0:N.id)===c});if(!(M!=null&&M.approval))throw new Error(`Approval not found: ${c}`);if(M.approval.toolType==="webmcp"){V.resolveWebMcpApproval(M.id,p);return}return V.resolveApproval(M.approval,p,h)},getMessages(){return V.getMessages()},getStatus(){return V.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()&&T},isVoiceActive(){return yt.active},getState(){return{open:S()&&T,launcherEnabled:L,voiceActive:yt.active,streaming:V.isStreaming()}},showCSATFeedback(c){!T&&S()&&Ft(!0,"system");let p=et.querySelector(".persona-feedback-container");p&&p.remove();let h=Cf({onSubmit:async(y,M)=>{var O;V.isClientTokenMode()&&await V.submitCSATFeedback(y,M),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!T&&S()&&Ft(!0,"system");let p=et.querySelector(".persona-feedback-container");p&&p.remove();let h=Sf({onSubmit:async(y,M)=>{var O;V.isClientTokenMode()&&await V.submitNPSFeedback(y,M),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,p){return V.submitCSATFeedback(c,p)},async submitNPSFeedback(c,p){return V.submitNPSFeedback(c,p)},destroy(){co!=null&&(clearInterval(co),co=null),ht.forEach(c=>c()),Me.remove(),Xe==null||Xe.remove(),en==null||en.destroy(),tn==null||tn.remove(),io&&D.removeEventListener("click",io)}};if((((wd=n==null?void 0:n.debugTools)!=null?wd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,p={controller:ln,getMessages:ln.getMessages,getStatus:ln.getStatus,getMetadata:ln.getPersistentMetadata,updateMetadata:ln.updatePersistentMetadata,clearHistory:()=>ln.clearChat(),setVoiceActive:h=>h?ln.startVoiceRecognition():ln.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ht.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=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.focusInput()};if(window.addEventListener("persona:focusInput",p),ht.push(()=>{window.removeEventListener("persona:focusInput",p)}),ke){let z=we=>{let fe=we.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===c)&&ln.showEventStream()},F=we=>{let fe=we.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===c)&&ln.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",F),ht.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",F)})}let h=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.showArtifacts()},y=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.hideArtifacts()},M=z=>{let F=z.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&ln.upsertArtifact(F.artifact)},O=z=>{let F=z.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&ln.selectArtifact(F.id)},N=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",O),window.addEventListener("persona:clearArtifacts",N),ht.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",O),window.removeEventListener("persona:clearArtifacts",N)})}let po=Jx(o.persistState);if(po&&S()){let c=Qx(po.storage),p=`${po.keyPrefix}widget-open`,h=`${po.keyPrefix}widget-voice`,y=`${po.keyPrefix}widget-voice-mode`;if(c){let M=((Cd=po.persist)==null?void 0:Cd.openState)&&c.getItem(p)==="true",O=((Sd=po.persist)==null?void 0:Sd.voiceState)&&c.getItem(h)==="true",N=((Ad=po.persist)==null?void 0:Ad.voiceState)&&c.getItem(y)==="true";if(M&&setTimeout(()=>{ln.open(),setTimeout(()=>{var z;if(O||N)ln.startVoiceRecognition();else if((z=po.persist)!=null&&z.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Td=po.persist)!=null&&Td.openState&&(s.on("widget:opened",()=>{c.setItem(p,"true")}),s.on("widget:closed",()=>{c.setItem(p,"false")})),(kd=po.persist)!=null&&kd.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),po.clearOnChatClear){let z=()=>{c.removeItem(p),c.removeItem(h),c.removeItem(y)},F=()=>z();window.addEventListener("persona:clear-chat",F),ht.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return f&&S()&&setTimeout(()=>{ln.open()},0),Ko(),ln};var Zx=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Mf=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},sc=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=""},Lf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",sc(e)},nc=e=>{e.style.transition=""},oc=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=""},rc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},$i=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ew=(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))},tw=(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)},If=(e,t,n,o,r,s,a)=>{var C,v,E,L,I,R;let i=Oo(s),d=i.reveal==="push";ew(e,t,n,o,d),tw(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=(L=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?L:640,g=l!=null?l.innerWidth<=u:!1;if(f&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),oc(t),nc(o),Lf(o),rc(n),$i(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((R=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?R:En),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"),Lf(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",oc(t),nc(o),rc(n),$i(r,o);let H=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":P;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=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",nc(o),sc(o),$i(r,o);let H=Zx(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${H}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${H}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${P+H}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=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}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="",oc(t),sc(o),rc(n),$i(r,o);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=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 ${P}`,o.style.width=P,o.style.maxWidth=P,o.style.minWidth=P,o.style.minHeight="0",o.style.position="relative",o.style.overflow=H||x?"hidden":"visible",o.style.transition=w,H&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},nw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Mf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Mf(n,o)},destroy(){n.remove()}}},ow=(e,t)=>{var I,R,H,P;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=(R=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||R?(P=(H=t==null?void 0:t.launcher)==null?void 0:H.autoExpand)!=null?P:!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(),Oo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{If(a,i,d,l,f,t,u)}),g.observe(a))},v=()=>{If(a,i,d,l,f,t,u),C()},E=a.ownerDocument.defaultView,L=()=>{v()};return E==null||E.addEventListener("resize",L),Oo(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,k;t=w,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(u=!0),v()},destroy(){E==null||E.removeEventListener("resize",L),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Rf=(e,t)=>xn(t)?ow(e,t):nw(e,t);var ys={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ac=.15,ic=1.5,Ui="persona-preview-shell-theme",Pf={load:()=>null,save:()=>{},clear:()=>{}},Wf=["How do I get started?","Pricing & plans","Talk to support"];function zi(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Bf(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 lc(e){let t=Bf(e);return`* { box-sizing: border-box; }
107
+ `}if(!y&&!c){let Vt="max-height: -moz-available !important; max-height: stretch !important;",Nt=p?"":"padding-top: 1.25em !important;",ht=p?"":`z-index: ${(mn=(et=o.launcher)==null?void 0:et.zIndex)!=null?mn:Ln} !important;`;Le.style.cssText+=Vt+Nt+ht}Ge()};bo(),as(e,o),Vi(e,o),$i(e,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",tr)});let en=null,tn=null;gt.push(()=>{en==null||en(),en=null,tn==null||tn(),tn=null}),jn&&gt.push(()=>{jn==null||jn.disconnect(),jn=null}),gt.push(()=>{Wn==null||Wn(),Wn=null,$o(),Ht&&(Ht.remove(),Ht=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),ke&&gt.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),j==null||j.destroy(),j=null,be==null||be.destroy(),be=null,X=null});let Qn=null,rr=()=>{Qn&&(Qn(),Qn=null),o.colorScheme==="auto"&&(Qn=Fu(()=>{as(e,o)}))};rr(),gt.push(()=>{Qn&&(Qn(),Qn=null)});let xe=(vd=o.features)==null?void 0:vd.streamAnimation;if(xe!=null&&xe.type&&xe.type!=="none"){let c=aa(xe.type,xe.plugins);c&&($l(c,e),gt.push(()=>Ym(e)))}let yo=dg(Tt),lo=null,$,jr=c=>{var y,M;if(!$)return;let p=c!=null?c:$.getMessages(),h=((M=(y=o.features)==null?void 0:y.suggestReplies)==null?void 0:M.enabled)!==!1?xm(p):null;h?yo.render(h,$,te,p,o.suggestionChipsConfig,{agentPushed:!0}):p.some(F=>F.role==="user")?yo.render([],$,te,p):yo.render(o.suggestionChips,$,te,p,o.suggestionChipsConfig)},Ro=!1,Uo=_m(),zo=new Map,Po=new Map,vo=new Map,As=0,Jn=Ci(),Zn=0,xo=null,wo=!1,xr=!1,qo=0,Tn=null,Wo=null,Kr=!1,wr=!1,Gr=null,Aa=4,Yr=24,Ta=80,Xr=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ts=(wd=(xd=o.voiceRecognition)==null?void 0:xd.autoResume)!=null?wd:!1,co=c=>{s.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Vn=()=>{m(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},ka=()=>{var y,M;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=ac(d.voiceState),p=!!c.active,h=Number((M=c.timestamp)!=null?M:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,p&&Date.now()-h<dw&&setTimeout(()=>{var F,N;bt.active||(bt.manuallyDeactivated=!1,((N=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),co("restore"),$.isVoiceActive()&&Os()}):Gt("restore"))},1e3)},Ea=()=>$?Wg($.getMessages()).filter(c=>!c.__skipPersist):[];function Qr(c){if(!(i!=null&&i.save))return;let h={messages:c?Wg(c):$?Ea():[],metadata:d,artifacts:Kn.artifacts,selectedArtifactId:Kn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let jo=null,ks=()=>Le.querySelector("#persona-scroll-container")||me,sr=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),wo=!1},Es=()=>{xo!==null&&(cancelAnimationFrame(xo),xo=null),xr=!1,sr()},Ms=()=>{qo>0?(Sn.textContent=String(qo),Sn.style.display="",Qe.setAttribute("aria-label",`${jt()||"Jump to latest"} (${qo} new)`)):(Sn.textContent="",Sn.style.display="none",Qe.setAttribute("aria-label",jt()||"Jump to latest"))},Ls=()=>{qo!==0&&(qo=0,Ms())},Is=()=>ut()==="follow"?!Jn.isFollowing():!Nr(me,Yr),$n=()=>{if(!xn()||se){Qe.parentNode&&Qe.remove(),Qe.style.display="none";return}Qe.parentNode!==q&&q.appendChild(Qe),bn();let p=Qo(me)>0&&Is();p||Ls(),Qe.style.display=p?"":"none"},Jr=()=>{Jn.pause()&&(Es(),$n())},Bo=()=>{Jn.resume(),Ls(),$n()},Ho=(c=!1)=>{ut()==="follow"&&Jn.isFollowing()&&(!c&&!Ro||(xo!==null&&(cancelAnimationFrame(xo),xo=null),xr=!0,xo=requestAnimationFrame(()=>{xo=null,xr=!1,Jn.isFollowing()&&Ma(ks(),c?220:140)})))},Rs=(c,p,h,y=()=>!0)=>{let M=c.scrollTop,F=p(),N=F-M;sr();let z=performance.now();wo=!0;let O=ge=>1-Math.pow(1-ge,3),we=ge=>{if(!y()){sr();return}let ee=p();ee!==F&&(F=ee,N=F-M);let Te=ge-z,_e=Math.min(Te/h,1),Ae=O(_e),nt=M+N*Ae;c.scrollTop=nt,Zn=c.scrollTop,_e<1?jo=requestAnimationFrame(we):(c.scrollTop=F,Zn=c.scrollTop,jo=null,wo=!1)};jo=requestAnimationFrame(we)},Ma=(c,p=500)=>{let h=Qo(c)-c.scrollTop;if(Math.abs(h)<1){Zn=c.scrollTop;return}if(Math.abs(h)>=Ta){sr(),wo=!0,c.scrollTop=Qo(c),Zn=c.scrollTop,wo=!1;return}Rs(c,()=>Qo(c),p,()=>Jn.isFollowing())},Ps=()=>{let c=ks();wo=!0,c.scrollTop=Qo(c),Zn=c.scrollTop,wo=!1,$n()},Ws=c=>{An.style.height=`${Math.max(0,Math.round(c))}px`,Tn&&(Tn.spacerHeight=Math.max(0,c))},Cr=()=>{Wo!==null&&(cancelAnimationFrame(Wo),Wo=null),sr(),Tn=null,An.style.height="0px"},La=c=>{Wo!==null&&cancelAnimationFrame(Wo),Wo=requestAnimationFrame(()=>{var we;Wo=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=me.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,M=h;for(;M&&M!==me;)y+=M.offsetTop,M=M.offsetParent;let F=(we=Tn==null?void 0:Tn.spacerHeight)!=null?we:0,N=me.scrollHeight-F,{targetScrollTop:z,spacerHeight:O}=qm({anchorOffsetTop:y,topOffset:kt(),viewportHeight:me.clientHeight,contentHeight:N});Tn={initialSpacerHeight:O,contentHeightAtAnchor:N,spacerHeight:O},Ws(O),Rs(me,()=>z,220)})},Ia=()=>{if(ut()==="follow"){if(!Jn.isFollowing()||Nr(me,1))return;Ho(!Ro);return}if(Tn&&Tn.initialSpacerHeight>0){let c=me.scrollHeight-Tn.spacerHeight,p=jm({initialSpacerHeight:Tn.initialSpacerHeight,contentHeightAtAnchor:Tn.contentHeightAtAnchor,currentContentHeight:c});p!==Tn.spacerHeight&&Ws(p)}$n()},Ra=c=>{let p=ut();p==="follow"?(Bo(),Ho(!0)):p==="anchor-top"&&La(c)},Pa=c=>{let p=new Map;c.forEach(h=>{let y=Xr.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!wr&&ut()!=="anchor-top"&&Is()&&(qo+=1,Ms(),$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}))}),Xr.clear(),p.forEach((h,y)=>{Xr.set(y,h)})},Sr=(c,p,h)=>{var dt,Pe,Ie,Ue,Ge,xt;let y=document.createElement("div"),F=(()=>{var Be;let B=r.find(Oe=>Oe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Be=o.loadingIndicator)!=null&&Be.render)return o.loadingIndicator.render})(),N=(B,Be)=>Be==null?!1:typeof Be=="string"?(B.textContent=Be,!0):(B.appendChild(Be),!0),z=new Set,O=new Set,we=r.some(B=>B.renderAskUserQuestion),ge=[],ee=[],Te=o.enableComponentStreaming!==!1,_e=r.some(B=>B.renderApproval)&&o.approval!==!1,Ae=[];if(p.forEach(B=>{var Ye,Rt,dn,uo,to,Tr,kr,os,rs,Yt,Er,ur,mr,Go,Mr,Co;z.add(B.id);let Be=we&&Hr(B),Oe=_e&&B.variant==="approval"&&!!B.approval,ye=!Be&&B.role==="assistant"&&!B.variant&&Te&&Lg(B);if(!Oe&&vo.has(B.id)){let et=c.querySelector(`#wrapper-${B.id}`);et==null||et.removeAttribute("data-preserve-runtime"),vo.delete(B.id)}if(!ye&&Po.has(B.id)){let et=c.querySelector(`#wrapper-${B.id}`);et==null||et.removeAttribute("data-preserve-runtime"),Po.delete(B.id)}let Ft=Hr(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Rt=B.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Nm(B,As)+Ft,Kt=Be||Oe||ye?null:Vm(Uo,B.id,Ot);if(Kt){y.appendChild(Kt.cloneNode(!0)),Hr(B)&&((dn=B.toolCall)!=null&&dn.id)&&((uo=B.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((to=B.agentMetadata)!=null&&to.askUserQuestionAnswered)&&(O.add(B.toolCall.id),ai(B,o,We.composerOverlay));return}let wt=null,zt=r.find(et=>!!(B.variant==="reasoning"&&et.renderReasoning||B.variant==="tool"&&et.renderToolCall||!B.variant&&et.renderMessage)),eo=(Tr=o.layout)==null?void 0:Tr.messages;if(Hr(B)&&((kr=B.agentMetadata)==null?void 0:kr.askUserQuestionAnswered)===!0){zo.delete(B.id);let et=c.querySelector(`#wrapper-${B.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(Bl(B)&&((rs=(os=o.features)==null?void 0:os.suggestReplies)==null?void 0:rs.enabled)!==!1)return;if(Hr(B)&&((Er=(Yt=o.features)==null?void 0:Yt.askUserQuestion)==null?void 0:Er.enabled)!==!1){let et=r.find(mn=>typeof mn.renderAskUserQuestion=="function");if(et&&Lt.current){let mn=zo.get(B.id),Vt=mn!==Ot,Nt=null;if(Vt){let{payload:Et,complete:kn}=ps(B),Bn=B.id,Do=()=>{var vn;return(vn=Lt.current)==null?void 0:vn.getMessages().find(Hn=>Hn.id===Bn)};Nt=et.renderAskUserQuestion({message:B,payload:Et,complete:kn,resolve:vn=>{var Dn;let Hn=Do();Hn&&((Dn=Lt.current)==null||Dn.resolveAskUserQuestion(Hn,vn))},dismiss:()=>{var Hn,Dn,Lr;let vn=Do();(Hn=vn==null?void 0:vn.agentMetadata)!=null&&Hn.awaitingLocalTool&&((Dn=Lt.current)==null||Dn.markAskUserQuestionResolved(vn),(Lr=Lt.current)==null||Lr.resolveAskUserQuestion(vn,"(dismissed)"))},config:o})}let ht=mn!=null;if(Vt&&Nt===null&&!ht){((ur=B.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((mr=B.agentMetadata)!=null&&mr.askUserQuestionAnswered)&&(O.add(B.toolCall.id),ai(B,o,We.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${B.id}`,Xt.setAttribute("data-wrapper-id",B.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),y.appendChild(Xt),ge.push({messageId:B.id,fingerprint:Ot,bubble:Nt});return}else{((Go=B.agentMetadata)==null?void 0:Go.awaitingLocalTool)===!0&&!((Mr=B.agentMetadata)!=null&&Mr.askUserQuestionAnswered)&&(O.add(B.toolCall.id),ai(B,o,We.composerOverlay));return}}else if(Oe){let et=r.find(ht=>typeof ht.renderApproval=="function"),Vt=vo.get(B.id)!==Ot,Nt=null;if(Vt&&(et!=null&&et.renderApproval)){let ht=B.id,Xt=(Et,kn)=>{var Do,vn,Hn;let Bn=(Do=Lt.current)==null?void 0:Do.getMessages().find(Dn=>Dn.id===ht);Bn!=null&&Bn.approval&&(Bn.approval.toolType==="webmcp"?(vn=Lt.current)==null||vn.resolveWebMcpApproval(Bn.id,Et):(Hn=Lt.current)==null||Hn.resolveApproval(Bn.approval,Et,kn))};Nt=et.renderApproval({message:B,defaultRenderer:()=>Ni(B,o),config:o,approve:Et=>Xt("approved",Et),deny:Et=>Xt("denied",Et)})}if(Vt&&Nt===null){let ht=c.querySelector(`#wrapper-${B.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),vo.delete(B.id),wt=Ni(B,o)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${B.id}`,ht.setAttribute("data-wrapper-id",B.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),y.appendChild(ht),Ae.push({messageId:B.id,fingerprint:Ot,bubble:Nt});return}}else if(zt)if(B.variant==="reasoning"&&B.reasoning&&zt.renderReasoning){if(!ue)return;wt=zt.renderReasoning({message:B,defaultRenderer:()=>Yl(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&zt.renderToolCall){if(!ce)return;wt=zt.renderToolCall({message:B,defaultRenderer:()=>Xl(B,o),config:o})}else zt.renderMessage&&(wt=zt.renderMessage({message:B,defaultRenderer:()=>{let et=Gl(B,h,eo,o.messageActions,Z,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&ec(et,B,o,$),et},config:o}));if(!wt&&ye){let et=Ig(B);if(et){let mn=Po.get(B.id),Vt=mn!==Ot,Nt=o.wrapComponentDirectiveInBubble!==!1,ht=null;if(Vt){let Xt=Eg(et,{config:o,message:B,transform:h});if(Xt)if(Nt){let Et=document.createElement("div");if(Et.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Et.id=`bubble-${B.id}`,Et.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let kn=document.createElement("div");kn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",kn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Et.appendChild(kn)}Et.appendChild(Xt),ht=Et}else{let Et=document.createElement("div");if(Et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Et.id=`bubble-${B.id}`,Et.setAttribute("data-message-id",B.id),Et.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let kn=document.createElement("div");kn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",kn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Et.appendChild(kn)}Et.appendChild(Xt),ht=Et}}if(ht||mn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${B.id}`,Xt.setAttribute("data-wrapper-id",B.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),Nt||Xt.classList.add("persona-w-full"),y.appendChild(Xt),ee.push({messageId:B.id,fingerprint:Ot,bubble:ht});return}}}if(!wt)if(B.variant==="reasoning"&&B.reasoning){if(!ue)return;wt=Yl(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!ce)return;wt=Xl(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;wt=Ni(B,o)}else{let et=(Co=o.layout)==null?void 0:Co.messages;et!=null&&et.renderUserMessage&&B.role==="user"?wt=et.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):et!=null&&et.renderAssistantMessage&&B.role==="assistant"?wt=et.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):wt=Gl(B,h,et,o.messageActions,Z,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&wt&&ec(wt,B,o,$)}let sn=document.createElement("div");sn.className="persona-flex",sn.id=`wrapper-${B.id}`,sn.setAttribute("data-wrapper-id",B.id),B.role==="user"&&sn.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&sn.classList.add("persona-w-full"),sn.appendChild(wt),$m(Uo,B.id,Ot,sn),y.appendChild(sn)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Oe=Be.getAttribute("data-persona-ask-sheet-for");Oe&&!O.has(Oe)&&ms(We.composerOverlay,Oe)}),(Pe=(dt=o.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let B=[],Be=[];p.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&ce){Be.push(Oe);return}Be.length>1&&B.push(Be),Be=[]}),Be.length>1&&B.push(Be),B.forEach((Oe,ye)=>{var Ye,Rt;let Ft=Oe.map(dn=>Array.from(y.children).find(uo=>uo instanceof HTMLElement&&uo.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if(Ft.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${ye}-${Oe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${ye}-${Oe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Oe.length} tools`,eo=(Rt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Rt.call(Ye,{messages:Oe,toolCalls:Oe.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:zt,config:o});N(wt,eo)||(wt.textContent=zt);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,sn),Ot.appendChild(Kt),Ft[0].before(Ot),Ft.forEach((dn,uo)=>{let to=document.createElement("div");to.className="persona-tool-group-item persona-relative",to.setAttribute("data-persona-tool-group-item","true"),uo<Ft.length-1&&to.setAttribute("data-persona-tool-group-connector","true"),to.appendChild(dn),sn.appendChild(to)})})}Um(Uo,z);let nt=p.some(B=>B.role==="assistant"&&B.streaming),qe=p[p.length-1],ct=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(Ro&&p.some(B=>B.role==="user")&&!nt&&!ct){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ga},Be=r.find(ye=>ye.renderLoadingIndicator),Oe=null;if(Be!=null&&Be.renderLoadingIndicator&&(Oe=Be.renderLoadingIndicator(B)),Oe===null&&((Ie=o.loadingIndicator)!=null&&Ie.render)&&(Oe=o.loadingIndicator.render(B)),Oe===null&&(Oe=ga()),Oe){let ye=document.createElement("div"),Ft=((Ue=o.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ye.className=Ft?["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(Oe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(ye),y.appendChild(Ot)}}if(!Ro&&p.length>0){let B=p[p.length-1],Be={config:o,lastMessage:B,messageCount:p.length},Oe=r.find(Ft=>Ft.renderIdleIndicator),ye=null;if(Oe!=null&&Oe.renderIdleIndicator&&(ye=Oe.renderIdleIndicator(Be)),ye===null&&((Ge=o.loadingIndicator)!=null&&Ge.renderIdle)&&(ye=o.loadingIndicator.renderIdle(Be)),ye){let Ft=document.createElement("div"),Ot=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Ft.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(ye);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ft),y.appendChild(Kt)}}if(xi(c,y),ge.length>0)for(let{messageId:B,fingerprint:Be,bubble:Oe}of ge){let ye=c.querySelector(`#wrapper-${B}`);ye&&Oe!==null&&(ye.replaceChildren(Oe),ye.setAttribute("data-bubble-fp",Be),zo.set(B,Be))}if(zo.size>0)for(let B of zo.keys())z.has(B)||zo.delete(B);if(ee.length>0)for(let{messageId:B,fingerprint:Be,bubble:Oe}of ee){let ye=c.querySelector(`#wrapper-${B}`);ye&&Oe!==null&&(ye.replaceChildren(Oe),ye.setAttribute("data-bubble-fp",Be),Po.set(B,Be))}if(Po.size>0)for(let B of Po.keys())z.has(B)||Po.delete(B);if(Ae.length>0)for(let{messageId:B,fingerprint:Be,bubble:Oe}of Ae){let ye=c.querySelector(`#wrapper-${B}`);ye&&Oe!==null&&(ye.replaceChildren(Oe),ye.setAttribute("data-bubble-fp",Be),vo.set(B,Be))}if(vo.size>0)for(let B of vo.keys())z.has(B)||vo.delete(B)},ar=null,Wa=()=>{var h;if(ar)return;let c=y=>{let M=y.composedPath();M.includes(Le)||Xe&&M.includes(Xe)||Dt(!1,"user")};ar=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Bs=()=>{var p;if(!ar)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("pointerdown",ar,!0),ar=null};gt.push(()=>Bs());let ir=null,Ba=()=>{var h;if(ir)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Dt(!1,"user"))};ir=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Hs=()=>{var p;if(!ir)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("keydown",ir,!0),ir=null};gt.push(()=>Hs());let lr=!1,Ds=new Set,Ha=()=>{var p,h,y,M;let c=(y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((M=o.features)==null?void 0:M.streamAnimation)},Ko=()=>{var ct,dt,Pe,Ie;if(!k())return;let c=We.peekBanner,p=We.peekTextNode;if(!c||!p)return;if(S){c.classList.remove("persona-pill-peek--visible");return}let h=(ct=$==null?void 0:$.getMessages())!=null?ct:[],y;for(let Ue=h.length-1;Ue>=0;Ue--){let Ge=h[Ue];if(Ge.role==="assistant"&&Ge.content){y=Ge;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let M=y.content,F=!!y.streaming,N=Ha(),z=Ti(N),O=z.type!=="none"?aa(z.type,N==null?void 0:N.plugins):null,we=((dt=O==null?void 0:O.isAnimating)==null?void 0:dt.call(O,y))===!0,ge=O!==null&&(F||we);ge&&O&&!Ds.has(O.name)&&($l(O,e),Ds.add(O.name));let ee=ge&&(O!=null&&O.containerClass)?O.containerClass:null,Te=(Pe=p.dataset.personaPeekStreamClass)!=null?Pe:null;Te&&Te!==ee&&(p.classList.remove(Te),delete p.dataset.personaPeekStreamClass),ee&&Te!==ee&&(p.classList.add(ee),p.dataset.personaPeekStreamClass=ee),ge?(p.style.setProperty("--persona-stream-step",`${z.speed}ms`),p.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let _e=ge?ki(M,z.buffer,O,y,F):M;if(ge&&z.placeholder==="skeleton"&&F&&(!_e||!_e.trim())){let Ue=document.createElement("div"),Ge=la();Ge.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(Ge),xi(p,Ue)}else{let Ue=Math.max(0,_e.length-100),Ge=_e.length>100?_e.slice(-100):_e,xt=Ks(Ge);if(!ge||!O){let B=_e.length>100?`\u2026${Ge}`:Ge;p.textContent!==B&&(p.textContent=B)}else{let B=xt;(O.wrap==="char"||O.wrap==="word")&&(B=ia(xt,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:Ue}));let Be=document.createElement("div");if(Be.innerHTML=B,O.useCaret&&Ge.length>0){let Oe=Ei(),ye=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=ye[ye.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(Oe,Ft.nextSibling):Be.appendChild(Oe)}xi(p,Be),(Ie=O.onAfterRender)==null||Ie.call(O,{container:p,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let qe=Ro||lr;c.classList.toggle("persona-pill-peek--visible",qe)};if(k()){let c=We.peekBanner;if(c){let y=M=>{M.preventDefault(),M.stopPropagation(),Dt(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let p=()=>{lr||(lr=!0,Ko())},h=()=>{lr&&(lr=!1,Ko())};de.addEventListener("pointerenter",p),de.addEventListener("pointerleave",h),gt.push(()=>{de.removeEventListener("pointerenter",p),de.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),gt.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let Da=c=>{var Te,_e,Ae,nt,qe,ct,dt,Pe;let p=(_e=(Te=o.launcher)==null?void 0:Te.composerBar)!=null?_e:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",y=(nt=p.bottomOffset)!=null?nt:"16px",M=p.collapsedMaxWidth,F=(qe=p.expandedMaxWidth)!=null?qe:"880px",N=(ct=p.expandedTopOffset)!=null?ct:"5vh",z=(dt=p.modalMaxWidth)!=null?dt:"880px",O=(Pe=p.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",we="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ee=Le.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Xe){let Ie=Xe.style;Ie.bottom=y,Ie.width=M!=null?M:""}if(c&&h!=="fullscreen"){if(h==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=z,ee.maxWidth=we,ee.maxHeight=O,ee.height=O;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ge})`,ee.top=N,ee.width=F,ee.maxWidth=we}},cr=()=>{var O,we,ge,ee,Te,_e,Ae,nt;if(!A())return;if(k()){let ct=(ge=((we=(O=o.launcher)==null?void 0:O.composerBar)!=null?we:{}).expandedSize)!=null?ge:"anchored",dt=S?"expanded":"collapsed";Le.dataset.state=dt,Le.dataset.expandedSize=ct,Xe&&(Xe.dataset.state=dt,Xe.dataset.expandedSize=ct),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Da(S),q.style.display=S?"flex":"none",bo(),S?(Wa(),Ba()):(Bs(),Hs()),Ko();return}let c=Cn(o),p=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(_e=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?_e:640,y=(nt=(Ae=o.launcher)==null?void 0:Ae.mobileFullscreen)!=null?nt:!0,M=p.innerWidth<=h,F=y&&M&&L,N=To(o).reveal;S?(Le.style.removeProperty("display"),Le.style.display=c?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),nn?nn.element.style.display="none":on&&(on.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!F?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.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"),de.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"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),nn?nn.element.style.display=c?"none":"":on&&(on.style.display=c?"none":""))},Dt=(c,p="user")=>{var F,N;if(!A()||S===c)return;let h=S;S=c,cr();let y=(()=>{var Ae,nt,qe,ct,dt,Pe,Ie,Ue,Ge,xt;let z=(nt=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?nt:!1,O=(qe=e.ownerDocument.defaultView)!=null?qe:window,we=(dt=(ct=o.launcher)==null?void 0:ct.mobileFullscreen)!=null?dt:!0,ge=(Ie=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Ie:640,ee=O.innerWidth<=ge,Te=Cn(o)&&we&&ee,_e=k()&&((xt=(Ge=(Ue=o.launcher)==null?void 0:Ue.composerBar)==null?void 0:Ge.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return z||we&&ee&&L||Te||_e})();if(S&&y){if(!en){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(en=Ul(O,(N=(F=o.launcher)==null?void 0:F.zIndex)!=null?N:Ln))}tn||(tn=zl(e.ownerDocument))}else S||(en==null||en(),en=null,tn==null||tn(),tn=null);S&&(Fs(),ut()==="follow"?Ho(!0):Ps());let M={open:S,source:p,timestamp:Date.now()};S&&!h?s.emit("widget:opened",M):!S&&h&&s.emit("widget:closed",M),s.emit("widget:state",{open:S,launcherEnabled:L,voiceActive:bt.active,streaming:$.isStreaming()})},Zr=c=>{Qt(c?"stop":"send"),G&&(G.disabled=c),yo.buttons.forEach(p=>{p.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=c)})},es=()=>{bt.active||te&&te.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>es(),200)});let Ar=()=>{var h,y,M,F,N,z,O,we,ge,ee,Te;ro.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Eo.textContent=(F=(M=o.copy)==null?void 0:M.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",te.placeholder=(z=(N=o.copy)==null?void 0:N.inputPlaceholder)!=null?z:"How can I help...";let c=me.querySelector("[data-persona-intro-card]");if(c){let _e=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(me.classList.remove("persona-gap-3"),me.classList.add("persona-gap-6")):(me.classList.remove("persona-gap-6"),me.classList.add("persona-gap-3"))}!((ge=(we=o.sendButton)==null?void 0:we.useIcon)!=null&&ge)&&!($!=null&&$.isStreaming())&&(ze.textContent=(Te=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?Te:"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 $e=null,T=()=>{$e==null&&($e=setInterval(()=>{let c=tt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval($e),$e=null;return}let p=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=li(p-y))})},100))};if($=new yi(o,{onMessagesChanged(c){var y;Sr(tt,c,fe),T(),jr(c),Ho(!Ro),Pa(c);let p=[...c].reverse().find(M=>M.role==="user");c.length===0&&Cr(),!Kr||wr?(Kr=!0,Gr=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Gr&&(Gr=p.id,Ra(p.id));let h=bt.lastUserMessageId;p&&p.id!==h&&(bt.lastUserMessageId=p.id,s.emit("user:message",p)),bt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Qr(c),Ko()},onStatusChanged(c){var y;let p=(y=o.statusIndicator)!=null?y:{};it(an,(M=>{var F,N,z,O;return M==="idle"?(F=p.idleText)!=null?F:Mn.idle:M==="connecting"?(N=p.connectingText)!=null?N:Mn.connecting:M==="connected"?(z=p.connectedText)!=null?z:Mn.connected:M==="error"?(O=p.errorText)!=null?O:Mn.error:Mn[M]})(c),p,c)},onStreamingChanged(c){Ro=c,Zr(c),$&&Sr(tt,$.getMessages(),fe),c||Ho(!0),Ko()},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(),lf();break;case"speaking":dr(),cf();break;default:c==="idle"&&$.isBargeInActive()?(dr(),Os(),G==null||G.setAttribute("aria-label","End voice session")):(bt.active=!1,dr(),co("system"),Vn());break}},onArtifactsState(c){Kn=c,Xn(),Qr()}}),Lt.current=$,Kr=!0,((Sd=(Cd=o.voiceRecognition)==null?void 0:Cd.provider)==null?void 0:Sd.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)}),(be||o.onSSEEvent)&&$.setSSEEventCallback((c,p)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,p),he==null||he.processEvent(c,p),be==null||be.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=ac(c.metadata),E.syncFromMetadata()),(p=c.messages)!=null&&p.length){wr=!0;try{$.hydrateMessages(c.messages)}finally{wr=!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 U=()=>{var p,h,y;!k()||S||!((y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Dt(!0,"auto")},P=c=>{var M;if(c.preventDefault(),$.isStreaming()){$.cancel(),he==null||he.reset(),j==null||j.update();return}let p=te.value.trim(),h=(M=Ct==null?void 0:Ct.hasAttachments())!=null?M:!1;if(!p&&!h)return;U();let y;h&&(y=[],y.push(...Ct.getContentParts()),p&&y.push(Fl(p))),te.value="",te.style.height="auto",Me(),$.sendMessage(p,{contentParts:y}),h&&Ct.clearAttachments()},J=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},ae={...wi},Y=!1,Me=()=>{ae={...wi}},Fe=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var p;return(p=c.content)!=null?p:""}).filter(c=>c.length>0),lt=c=>{if(!te)return;Y=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),Y=!1;let p=te.value.length;te.setSelectionRange(p,p)},Je=()=>{Y||Me()},Wt=c=>{if(te){if(J()&&(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=Fm({direction:c.key==="ArrowUp"?"up":"down",history:Fe(),currentValue:te.value,atStart:p,state:ae});if(ae=h.state,h.handled){c.preventDefault(),h.value!==void 0&&lt(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Me(),c.preventDefault(),ze.click()}}},_t=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(q)&&($.cancel(),he==null||he.reset(),j==null||j.update(),Me(),c.preventDefault(),c.stopImmediatePropagation())},un=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!Ct)return;let p=uw(c.clipboardData);p.length!==0&&(c.preventDefault(),await Ct.handleFiles(p))},rt=null,ft=!1,Jt=null,je=null,wn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Gt=(c="user")=>{var F,N,z,O,we,ge,ee;if(ft||$.isStreaming())return;let p=wn();if(!p)return;rt=new p;let y=(N=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?N:2e3;rt.continuous=!0,rt.interimResults=!0,rt.lang="en-US";let M=te.value;rt.onresult=Te=>{let _e="",Ae="";for(let qe=0;qe<Te.results.length;qe++){let ct=Te.results[qe],dt=ct[0].transcript;ct.isFinal?_e+=dt+" ":Ae=dt}let nt=M+_e+Ae;te.value=nt,Jt&&clearTimeout(Jt),(_e||Ae)&&(Jt=window.setTimeout(()=>{let qe=te.value.trim();qe&&rt&&ft&&(yn(),te.value="",te.style.height="auto",$.sendMessage(qe,{viaVoice:!0}))},y))},rt.onerror=Te=>{Te.error!=="no-speech"&&yn()},rt.onend=()=>{if(ft){let Te=te.value.trim();Te&&Te!==M.trim()&&(te.value="",te.style.height="auto",$.sendMessage(Te,{viaVoice:!0})),yn()}};try{if(rt.start(),ft=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),co(c),Vn(),G){let Te=(z=o.voiceRecognition)!=null?z:{};je={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(O=Te.iconName)!=null?O:"mic",iconSize:parseFloat((ee=(ge=Te.iconSize)!=null?ge:(we=o.sendButton)==null?void 0:we.size)!=null?ee:"40")||24};let _e=Te.recordingBackgroundColor,Ae=Te.recordingIconColor,nt=Te.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let qe=G.querySelector("svg");qe&&qe.setAttribute("stroke",Ae)}nt&&(G.style.borderColor=nt),G.setAttribute("aria-label","Stop voice recognition")}}catch{yn("system")}},yn=(c="user")=>{if(ft){if(ft=!1,Jt&&(clearTimeout(Jt),Jt=null),rt){try{rt.stop()}catch{}rt=null}if(bt.active=!1,co(c),Vn(),G){if(G.classList.remove("persona-voice-recording"),je){G.style.backgroundColor=je.backgroundColor,G.style.color=je.color,G.style.borderColor=je.borderColor;let p=G.querySelector("svg");p&&p.setAttribute("stroke",je.color||"currentColor"),je=null}G.setAttribute("aria-label","Start voice recognition")}}},af=(c,p)=>{var ct,dt,Pe,Ie,Ue,Ge,xt,B;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ct=c==null?void 0:c.provider)==null?void 0:ct.type)==="runtype";if(!(h||y))return null;let F=b("div","persona-send-button-wrapper"),N=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let z=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",O=(Pe=p==null?void 0:p.size)!=null?Pe:"40px",we=(Ie=c==null?void 0:c.iconSize)!=null?Ie:O,ge=parseFloat(we)||24,ee=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:p==null?void 0:p.backgroundColor,Te=(Ge=c==null?void 0:c.iconColor)!=null?Ge:p==null?void 0:p.textColor;N.style.width=we,N.style.height=we,N.style.minWidth=we,N.style.minHeight=we,N.style.fontSize="18px",N.style.lineHeight="1",Te?N.style.color=Te:N.style.color="var(--persona-text, #111827)";let Ae=Ee(z,ge,Te||"currentColor",1.5);Ae?N.appendChild(Ae):N.textContent="\u{1F3A4}",ee?N.style.backgroundColor=ee:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),F.appendChild(N);let nt=(xt=c==null?void 0:c.tooltipText)!=null?xt:"Start voice recognition";if(((B=c==null?void 0:c.showTooltip)!=null?B:!1)&&nt){let Be=b("div","persona-send-button-tooltip");Be.textContent=nt,F.appendChild(Be)}return{micButton:N,micButtonWrapper:F}},sl=()=>{var p,h,y,M,F;if(!G||je)return;let c=(p=o.voiceRecognition)!=null?p:{};je={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((F=(M=c.iconSize)!=null?M:(y=o.sendButton)==null?void 0:y.size)!=null?F:"40")||24}},al=(c,p)=>{var F,N,z,O,we;if(!G)return;let h=G.querySelector("svg");h&&h.remove();let y=(we=je==null?void 0:je.iconSize)!=null?we:parseFloat((O=(z=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?z:(N=o.sendButton)==null?void 0:N.size)!=null?O:"40")||24,M=Ee(c,y,p,1.5);M&&G.appendChild(M)},Oa=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Os=()=>{var M;if(!G)return;sl();let c=(M=o.voiceRecognition)!=null?M:{},p=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(Oa(),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 F=G.querySelector("svg");F&&F.setAttribute("stroke",h)}y&&(G.style.borderColor=y),G.setAttribute("aria-label","Stop voice recognition")},lf=()=>{var z,O,we,ge,ee,Te,_e,Ae;if(!G)return;sl();let c=(z=o.voiceRecognition)!=null?z:{},p=$.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ge=(we=c.processingIconColor)!=null?we:je==null?void 0:je.color)!=null?ge:"",M=(Te=(ee=c.processingBackgroundColor)!=null?ee:je==null?void 0:je.backgroundColor)!=null?Te:"",F=(Ae=(_e=c.processingBorderColor)!=null?_e:je==null?void 0:je.borderColor)!=null?Ae:"";Oa(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=M,G.style.borderColor=F;let N=y||"currentColor";G.style.color=N,al(h,N),G.setAttribute("aria-label","Processing voice input"),p==="none"&&(G.style.cursor="default")},cf=()=>{var we,ge,ee,Te,_e,Ae,nt,qe,ct,dt,Pe,Ie;if(!G)return;sl();let c=(we=o.voiceRecognition)!=null?we:{},p=$.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:h,M=(Ae=c.speakingIconColor)!=null?Ae:p==="barge-in"?(Te=(ee=c.recordingIconColor)!=null?ee:je==null?void 0:je.color)!=null?Te:"":(_e=je==null?void 0:je.color)!=null?_e:"",F=(ct=c.speakingBackgroundColor)!=null?ct:p==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(qe=je==null?void 0:je.backgroundColor)!=null?qe:"",N=(Ie=c.speakingBorderColor)!=null?Ie:p==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=je==null?void 0:je.borderColor)!=null?Pe:"";Oa(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=F,G.style.borderColor=N;let z=M||"currentColor";G.style.color=z,al(y,z);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&&(Oa(),je&&(G.style.backgroundColor=(c=je.backgroundColor)!=null?c:"",G.style.color=(p=je.color)!=null?p:"",G.style.borderColor=(h=je.borderColor)!=null?h:"",al(je.iconName,je.color||"currentColor"),je=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Fa=()=>{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(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Vn(),co("user"),dr()});return}$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),bt.manuallyDeactivated=!$.isVoiceActive(),Vn(),co("user"),$.isVoiceActive()?Os():dr()});return}if(ft){let h=te.value.trim();bt.manuallyDeactivated=!0,Vn(),yn("user"),h&&(te.value="",te.style.height="auto",$.sendMessage(h))}else bt.manuallyDeactivated=!1,Vn(),Gt("user")};zn=Fa,G&&(G.addEventListener("click",Fa),gt.push(()=>{var c,p;((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),dr()):yn("system"),G&&G.removeEventListener("click",Fa)}));let df=s.on("assistant:complete",()=>{Ts&&(bt.active||bt.manuallyDeactivated||Ts==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,p;!bt.active&&!bt.manuallyDeactivated&&(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),co("auto"),$.isVoiceActive()&&Os()}):Gt("auto"))},600))});gt.push(df);let pf=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});gt.push(pf);let ts=()=>{Dt(!S,"user")},nn=null,on=null;if(L&&!k()){let c=r.find(p=>p.renderLauncher);if(c!=null&&c.renderLauncher){let p=c.renderLauncher({config:o,defaultRenderer:()=>ua(o,ts).element,onToggle:ts});p&&(on=p)}on||(nn=ua(o,ts))}nn?e.appendChild(nn.element):on&&e.appendChild(on),cr(),jr(),Ar(),Zr($.isStreaming()),ut()==="follow"?Ho(!0):Ps(),ka(),W&&(!L||k()?setTimeout(()=>es(),0):S&&setTimeout(()=>es(),200));let Fs=()=>{var O,we,ge,ee,Te,_e,Ae,nt,qe,ct,dt,Pe,Ie,Ue,Ge,xt,B,Be,Oe,ye,Ft,Ot;if(k()){bn(),cr();return}let c=Cn(o),p=(we=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?we:!1,h=c||p||((ee=(ge=o.launcher)==null?void 0:ge.fullHeight)!=null?ee:!1),y=(Te=e.ownerDocument.defaultView)!=null?Te:window,M=(Ae=(_e=o.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ae:!0,F=(qe=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?qe:640,N=y.innerWidth<=F,z=M&&N&&L;try{if(z){bo(),as(e,o);return}if(C&&(C=!1,bo(),as(e,o)),!L&&!c){de.style.height="",de.style.width="";return}if(!p&&!c){let Kt=(dt=(ct=o==null?void 0:o.launcher)==null?void 0:ct.width)!=null?dt:o==null?void 0:o.launcherWidth,wt=Kt!=null?Kt:mo;de.style.width=wt,de.style.maxWidth=wt}if(Io(),!h){let Kt=y.innerHeight,wt=64,zt=(Ie=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Ie:0,eo=Math.max(200,Kt-wt),sn=Math.min(640,eo),Ye=Math.max(200,sn-zt);de.style.height=`${Ye}px`}}finally{if(bn(),cr(),S&&L){let wt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((xt=(Ge=o.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?xt:640),zt=(Be=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Be:!1,eo=(ye=(Oe=o.launcher)==null?void 0:Oe.mobileFullscreen)!=null?ye:!0,sn=Cn(o)&&eo&&wt,Ye=zt||eo&&wt&&L||sn;if(Ye&&!tn){let Rt=e.getRootNode(),dn=Rt instanceof ShadowRoot?Rt.host:e.closest(".persona-host");dn&&!en&&(en=Ul(dn,(Ot=(Ft=o.launcher)==null?void 0:Ft.zIndex)!=null?Ot:Ln)),tn=zl(e.ownerDocument)}else Ye||(en==null||en(),en=null,tn==null||tn(),tn=null)}}};Fs();let wc=(Ad=e.ownerDocument.defaultView)!=null?Ad:window;if(wc.addEventListener("resize",Fs),gt.push(()=>wc.removeEventListener("resize",Fs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bn()});c.observe(Ve),gt.push(()=>c.disconnect())}Zn=me.scrollTop;let Cc=Qo(me),uf=()=>{let c=me.getRootNode(),p=typeof c.getSelection=="function"?c.getSelection():null;return p!=null?p:me.ownerDocument.getSelection()},il=()=>zm(uf(),me),Sc=()=>{let c=me.scrollTop,p=Qo(me),h=p<Cc;if(Cc=p,ut()!=="follow"){Zn=c,$n();return}let{action:y,nextLastScrollTop:M}=Si({following:Jn.isFollowing(),currentScrollTop:c,lastScrollTop:Zn,nearBottom:Nr(me,Yr),userScrollThreshold:Aa,isAutoScrolling:wo||xr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Zn=M,y==="resume"){il()||Bo();return}y==="pause"&&Jr()};if(me.addEventListener("scroll",Sc,{passive:!0}),gt.push(()=>me.removeEventListener("scroll",Sc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ia()});c.observe(tt),c.observe(me),gt.push(()=>c.disconnect())}let Ac=()=>{ut()==="follow"&&Jn.isFollowing()&&il()&&Jr()},Tc=me.ownerDocument;Tc.addEventListener("selectionchange",Ac),gt.push(()=>{Tc.removeEventListener("selectionchange",Ac)});let kc=c=>{if(ut()!=="follow")return;let p=Ai({following:Jn.isFollowing(),deltaY:c.deltaY,nearBottom:Nr(me,Yr),resumeWhenNearBottom:!0});p==="pause"?Jr():p==="resume"&&!il()&&Bo()};me.addEventListener("wheel",kc,{passive:!0}),gt.push(()=>me.removeEventListener("wheel",kc)),Qe.addEventListener("click",()=>{Cr(),me.scrollTop=me.scrollHeight,Zn=me.scrollTop,Bo(),Ho(!0),$n()}),gt.push(()=>Qe.remove()),gt.push(()=>{Es(),Cr()});let Ec=()=>{D&&(lo&&(D.removeEventListener("click",lo),lo=null),A()?(D.style.display="",lo=()=>{Dt(!1,"user")},D.addEventListener("click",lo)):D.style.display="none")};Ec(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{$.clearMessages(),Uo.clear(),Bo(),ms(We.composerOverlay);try{localStorage.removeItem(vs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${vs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==vs)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={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()})})(),Bt&&Bt.addEventListener("submit",P),te==null||te.addEventListener("keydown",Wt),te==null||te.addEventListener("input",Je),te==null||te.addEventListener("paste",un);let Mc=(Td=e.ownerDocument)!=null?Td:document;Mc.addEventListener("keydown",_t,!0);let Lc="persona-attachment-drop-active",Ns=0,ll=()=>{Ns=0,q.classList.remove(Lc)},ns=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&Ct!==null},Ic=c=>{!Ui(c.dataTransfer)||!ns()||(Ns++,Ns===1&&q.classList.add(Lc))},Rc=c=>{!Ui(c.dataTransfer)||!ns()||(Ns--,Ns<=0&&ll())},Pc=c=>{!Ui(c.dataTransfer)||!ns()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Wc=c=>{var h;if(!Ui(c.dataTransfer)||!ns())return;c.preventDefault(),c.stopPropagation(),ll();let p=Array.from((h=c.dataTransfer.files)!=null?h:[]);p.length!==0&&Ct.handleFiles(p)},pr=!0;q.addEventListener("dragenter",Ic,pr),q.addEventListener("dragleave",Rc,pr),e.addEventListener("dragover",Pc,pr),e.addEventListener("drop",Wc,pr);let Na=e.ownerDocument,Bc=c=>{ns()&&c.preventDefault()},Hc=c=>{ns()&&c.preventDefault()};Na.addEventListener("dragover",Bc),Na.addEventListener("drop",Hc),gt.push(()=>{Bt&&Bt.removeEventListener("submit",P),te==null||te.removeEventListener("keydown",Wt),te==null||te.removeEventListener("input",Je),te==null||te.removeEventListener("paste",un),Mc.removeEventListener("keydown",_t,!0)}),gt.push(()=>{q.removeEventListener("dragenter",Ic,pr),q.removeEventListener("dragleave",Rc,pr),e.removeEventListener("dragover",Pc,pr),e.removeEventListener("drop",Wc,pr),Na.removeEventListener("dragover",Bc),Na.removeEventListener("drop",Hc),ll()}),gt.push(()=>{$.cancel()}),nn?gt.push(()=>{nn==null||nn.destroy()}):on&&gt.push(()=>{on==null||on.remove()});let cn={update(c){var kn,Bn,Do,vn,Hn,Dn,Lr,_s,Pd,Wd,Bd,Hd,Dd,Od,Fd,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Op,Fp,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Qp,Jp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,vu,xu,wu,Cu,Su,Au,Tu,ku,Eu,Mu,Lu,Iu;let p=o.toolCall,h=o.messageActions,y=(kn=o.layout)==null?void 0:kn.messages,M=o.colorScheme,F=o.loadingIndicator,N=o.iterationDisplay,z=(Bn=o.features)==null?void 0:Bn.showReasoning,O=(Do=o.features)==null?void 0:Do.showToolCalls,we=(vn=o.features)==null?void 0:vn.toolCallDisplay,ge=(Hn=o.features)==null?void 0:Hn.reasoningDisplay;o={...o,...c},bo(),as(e,o),Vi(e,o),$i(e,o),Xn(),o.colorScheme!==M&&rr();let ee=nc.getForInstance(o.plugins);r.length=0,r.push(...ee),L=(Lr=(Dn=o.launcher)==null?void 0:Dn.enabled)!=null?Lr:!0,I=(Pd=(_s=o.launcher)==null?void 0:_s.autoExpand)!=null?Pd:!1,ue=(Bd=(Wd=o.features)==null?void 0:Wd.showReasoning)!=null?Bd:!0,ce=(Dd=(Hd=o.features)==null?void 0:Hd.showToolCalls)!=null?Dd:!0,ve=(Fd=(Od=o.features)==null?void 0:Od.scrollToBottom)!=null?Fd:{};let Te=ut();He=(_d=(Nd=o.features)==null?void 0:Nd.scrollBehavior)!=null?_d:{},Te!==ut()&&(Cr(),Bo()),Mo(),$n();let _e=ke;if(ke=($d=(Vd=o.features)==null?void 0:Vd.showEventStreamToggle)!=null?$d:!1,ke&&!_e){if(be||(X=new ha(ie),be=new fa(re,X),he=he!=null?he:new ba,X.open().then(()=>be==null?void 0:be.restore()).catch(()=>{}),$.setSSEEventCallback((Q,At)=>{var $t;($t=o.onSSEEvent)==null||$t.call(o,Q,At),he==null||he.processEvent(Q,At),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(At)})})),!vt&&Ne){let Q=(zd=(Ud=o.features)==null?void 0:Ud.eventStream)==null?void 0:zd.classNames,At="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");vt=b("button",At),vt.style.width="28px",vt.style.height="28px",vt.style.color=Fn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let $t=Ee("activity","18px","currentColor",1.5);$t&&vt.appendChild($t);let pt=We.clearChatButtonWrapper,Pt=We.closeButtonWrapper,gn=pt||Pt;gn&&gn.parentNode===Ne?Ne.insertBefore(vt,gn):Ne.appendChild(vt),vt.addEventListener("click",()=>{se?ho():No()})}}else!ke&&_e&&(ho(),vt&&(vt.remove(),vt=null),be==null||be.clear(),X==null||X.destroy(),be=null,X=null,he==null||he.reset(),he=null);if(((qd=o.launcher)==null?void 0:qd.enabled)===!1&&nn&&(nn.destroy(),nn=null),((jd=o.launcher)==null?void 0:jd.enabled)===!1&&on&&(on.remove(),on=null),((Kd=o.launcher)==null?void 0:Kd.enabled)!==!1&&!nn&&!on){let Q=r.find(At=>At.renderLauncher);if(Q!=null&&Q.renderLauncher){let At=Q.renderLauncher({config:o,defaultRenderer:()=>ua(o,ts).element,onToggle:ts});At&&(on=At,e.appendChild(on))}on||(nn=ua(o,ts),e.appendChild(nn.element))}nn&&nn.update(o),De&&((Gd=o.launcher)==null?void 0:Gd.title)!==void 0&&(De.textContent=o.launcher.title),Ke&&((Yd=o.launcher)==null?void 0:Yd.subtitle)!==void 0&&(Ke.textContent=o.launcher.subtitle);let Ae=(Xd=o.layout)==null?void 0:Xd.header;if((Ae==null?void 0:Ae.layout)!==w&&Ne){let Q=Ae?Ii(o,Ae,{showClose:A(),onClose:()=>Dt(!1,"user")}):_r({config:o,showClose:A(),onClose:()=>Dt(!1,"user")});Ne.replaceWith(Q.header),Ne=Q.header,pe=Q.iconHolder,De=Q.headerTitle,Ke=Q.headerSubtitle,D=Q.closeButton,w=Ae==null?void 0:Ae.layout}else if(Ae&&(pe&&(pe.style.display=Ae.showIcon===!1?"none":""),De&&(De.style.display=Ae.showTitle===!1?"none":""),Ke&&(Ke.style.display=Ae.showSubtitle===!1?"none":""),D&&(D.style.display=Ae.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let Q=Ae.showClearChat;if(Q!==void 0){We.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:At}=We;At&&!At.classList.contains("persona-absolute")&&(Q?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let qe=((Qd=o.layout)==null?void 0:Qd.showHeader)!==!1;Ne&&(Ne.style.display=qe?"":"none");let ct=((Jd=o.layout)==null?void 0:Jd.showFooter)!==!1;Ve&&(Ve.style.display=ct?"":"none"),bn(),$n(),L!==R?L?Dt(I,"auto"):(S=!0,cr()):I!==H&&Dt(I,"auto"),H=I,R=L,Fs(),Ec();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(p),Ue=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((Zd=o.layout)==null?void 0:Zd.messages)!==JSON.stringify(y),xt=((ep=o.loadingIndicator)==null?void 0:ep.render)!==(F==null?void 0:F.render)||((tp=o.loadingIndicator)==null?void 0:tp.renderIdle)!==(F==null?void 0:F.renderIdle)||((np=o.loadingIndicator)==null?void 0:np.showBubble)!==(F==null?void 0:F.showBubble),B=o.iterationDisplay!==N,Be=((rp=(op=o.features)==null?void 0:op.showReasoning)!=null?rp:!0)!==(z!=null?z:!0)||((ap=(sp=o.features)==null?void 0:sp.showToolCalls)!=null?ap:!0)!==(O!=null?O:!0)||JSON.stringify((ip=o.features)==null?void 0:ip.toolCallDisplay)!==JSON.stringify(we)||JSON.stringify((lp=o.features)==null?void 0:lp.reasoningDisplay)!==JSON.stringify(ge);(Ie||Ue||Ge||xt||B||Be)&&$&&(As++,Sr(tt,$.getMessages(),fe));let ye=(cp=o.launcher)!=null?cp:{},Ft=(dp=ye.headerIconHidden)!=null?dp:!1,Ot=(up=(pp=o.layout)==null?void 0:pp.header)==null?void 0:up.showIcon,Kt=Ft||Ot===!1,wt=ye.headerIconName,zt=(mp=ye.headerIconSize)!=null?mp:"48px";if(pe){let Q=q.querySelector(".persona-border-b-persona-divider"),At=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Kt)pe.style.display="none",Q&&At&&!Q.contains(At)&&Q.insertBefore(At,Q.firstChild);else{if(pe.style.display="",pe.style.height=zt,pe.style.width=zt,Q&&At&&(Q.contains(pe)?pe.nextSibling!==At&&(pe.remove(),Q.insertBefore(pe,At)):Q.insertBefore(pe,At)),wt){let pt=parseFloat(zt)||24,Pt=Ee(wt,pt*.6,"#ffffff",2);Pt?pe.replaceChildren(Pt):pe.textContent=(gp=ye.agentIconText)!=null?gp:"\u{1F4AC}"}else if(ye.iconUrl){let pt=pe.querySelector("img");if(pt)pt.src=ye.iconUrl,pt.style.height=zt,pt.style.width=zt;else{let Pt=document.createElement("img");Pt.src=ye.iconUrl,Pt.alt="",Pt.className="persona-rounded-xl persona-object-cover",Pt.style.height=zt,Pt.style.width=zt,pe.replaceChildren(Pt)}}else{let pt=pe.querySelector("svg"),Pt=pe.querySelector("img");(pt||Pt)&&pe.replaceChildren(),pe.textContent=(fp=ye.agentIconText)!=null?fp:"\u{1F4AC}"}let $t=pe.querySelector("img");$t&&($t.style.height=zt,$t.style.width=zt)}}let eo=(bp=(hp=o.layout)==null?void 0:hp.header)==null?void 0:bp.showTitle,sn=(vp=(yp=o.layout)==null?void 0:yp.header)==null?void 0:vp.showSubtitle;if(De&&(De.style.display=eo===!1?"none":""),Ke&&(Ke.style.display=sn===!1?"none":""),D){((wp=(xp=o.layout)==null?void 0:xp.header)==null?void 0:wp.showCloseButton)===!1?D.style.display="none":D.style.display="";let At=(Cp=ye.closeButtonSize)!=null?Cp:"32px",$t=(Sp=ye.closeButtonPlacement)!=null?Sp:"inline";D.style.height=At,D.style.width=At;let{closeButtonWrapper:pt}=We,Pt=$t==="top-right",gn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&Pt!==gn)if(pt.remove(),Pt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",q.style.position="relative",q.appendChild(pt);else{let mt=(Tp=(Ap=ye.clearChat)==null?void 0:Ap.placement)!=null?Tp:"inline",fn=(Ep=(kp=ye.clearChat)==null?void 0:kp.enabled)!=null?Ep:!0;pt.className=fn&&mt==="inline"?"":"persona-ml-auto";let Un=q.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(pt)}if(D.style.color=ye.closeButtonColor||Fn.actionIconColor,ye.closeButtonBackgroundColor?(D.style.backgroundColor=ye.closeButtonBackgroundColor,D.classList.remove("hover:persona-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let mt=ye.closeButtonBorderWidth||"0px",fn=ye.closeButtonBorderColor||"transparent";D.style.border=`${mt} solid ${fn}`,D.classList.remove("persona-border-none")}else D.style.border="",D.classList.add("persona-border-none");ye.closeButtonBorderRadius?(D.style.borderRadius=ye.closeButtonBorderRadius,D.classList.remove("persona-rounded-full")):(D.style.borderRadius="",D.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(D.style.paddingLeft=ye.closeButtonPaddingX,D.style.paddingRight=ye.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ye.closeButtonPaddingY?(D.style.paddingTop=ye.closeButtonPaddingY,D.style.paddingBottom=ye.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let En=(Mp=ye.closeButtonIconName)!=null?Mp:"x",So=(Lp=ye.closeButtonIconText)!=null?Lp:"\xD7";D.innerHTML="";let On=Ee(En,"28px","currentColor",1);On?D.appendChild(On):D.textContent=So;let rn=(Ip=ye.closeButtonTooltipText)!=null?Ip:"Close chat",no=(Rp=ye.closeButtonShowTooltip)!=null?Rp:!0;if(D.setAttribute("aria-label",rn),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),no&&rn)){let mt=null,fn=()=>{if(mt||!D)return;let Ir=D.ownerDocument,Vs=Ir.body;if(!Vs)return;mt=Fo(Ir,"div","persona-clear-chat-tooltip"),mt.textContent=rn;let $s=Fo(Ir,"div");$s.className="persona-clear-chat-tooltip-arrow",mt.appendChild($s);let Rr=D.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(hr),mt.style.left=`${Rr.left+Rr.width/2}px`,mt.style.top=`${Rr.top-8}px`,mt.style.transform="translate(-50%, -100%)",Vs.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};pt.addEventListener("mouseenter",fn),pt.addEventListener("mouseleave",Un),D.addEventListener("focus",fn),D.addEventListener("blur",Un),pt._cleanupTooltip=()=>{Un(),pt&&(pt.removeEventListener("mouseenter",fn),pt.removeEventListener("mouseleave",Un)),D&&(D.removeEventListener("focus",fn),D.removeEventListener("blur",Un))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Rt}=We;if(Ye){let Q=(Pp=ye.clearChat)!=null?Pp:{},At=(Wp=Q.enabled)!=null?Wp:!0,$t=(Hp=(Bp=o.layout)==null?void 0:Bp.header)==null?void 0:Hp.showClearChat,pt=$t!==void 0?$t:At,Pt=(Dp=Q.placement)!=null?Dp:"inline";if(Rt){Rt.style.display=pt?"":"none";let{closeButtonWrapper:gn}=We;!k()&&gn&&!gn.classList.contains("persona-absolute")&&(pt?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let En=Pt==="top-right",So=Rt.classList.contains("persona-absolute");if(!k()&&En!==So&&pt){if(Rt.remove(),En)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",q.style.position="relative",q.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let rn=q.querySelector(".persona-border-b-persona-divider"),no=We.closeButtonWrapper;rn&&no&&no.parentElement===rn?rn.insertBefore(Rt,no):rn&&rn.appendChild(Rt)}let On=We.closeButtonWrapper;On&&!On.classList.contains("persona-absolute")&&(En?On.classList.add("persona-ml-auto"):On.classList.remove("persona-ml-auto"))}}if(pt){if(!k()){let mt=(Op=Q.size)!=null?Op:"32px";Ye.style.height=mt,Ye.style.width=mt}let gn=(Fp=Q.iconName)!=null?Fp:"refresh-cw",En=(Np=Q.iconColor)!=null?Np:"";Ye.style.color=En||Fn.actionIconColor,Ye.innerHTML="";let So=k()?"14px":"20px",On=Ee(gn,So,"currentColor",2);if(On&&Ye.appendChild(On),Q.backgroundColor?(Ye.style.backgroundColor=Q.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let mt=Q.borderWidth||"0px",fn=Q.borderColor||"transparent";Ye.style.border=`${mt} solid ${fn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");Q.borderRadius?(Ye.style.borderRadius=Q.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),Q.paddingX?(Ye.style.paddingLeft=Q.paddingX,Ye.style.paddingRight=Q.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),Q.paddingY?(Ye.style.paddingTop=Q.paddingY,Ye.style.paddingBottom=Q.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let rn=(_p=Q.tooltipText)!=null?_p:"Clear chat",no=(Vp=Q.showTooltip)!=null?Vp:!0;if(Ye.setAttribute("aria-label",rn),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),no&&rn)){let mt=null,fn=()=>{if(mt||!Ye)return;let Ir=Ye.ownerDocument,Vs=Ir.body;if(!Vs)return;mt=Fo(Ir,"div","persona-clear-chat-tooltip"),mt.textContent=rn;let $s=Fo(Ir,"div");$s.className="persona-clear-chat-tooltip-arrow",mt.appendChild($s);let Rr=Ye.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(hr),mt.style.left=`${Rr.left+Rr.width/2}px`,mt.style.top=`${Rr.top-8}px`,mt.style.transform="translate(-50%, -100%)",Vs.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};Rt.addEventListener("mouseenter",fn),Rt.addEventListener("mouseleave",Un),Ye.addEventListener("focus",fn),Ye.addEventListener("blur",Un),Rt._cleanupTooltip=()=>{Un(),Rt&&(Rt.removeEventListener("mouseenter",fn),Rt.removeEventListener("mouseleave",Un)),Ye&&(Ye.removeEventListener("focus",fn),Ye.removeEventListener("blur",Un))}}}}let dn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[rc],uo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ya.message,ya.messageAndClick];E=sc({parsers:dn,handlers:uo,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),fe=Bg(o,E,K),$.updateConfig(o),Sr(tt,$.getMessages(),fe),jr(),Ar(),Zr($.isStreaming());let to=(($p=o.voiceRecognition)==null?void 0:$p.enabled)===!0,Tr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),kr=((zp=(Up=o.voiceRecognition)==null?void 0:Up.provider)==null?void 0:zp.type)==="runtype";if(to&&(Tr||kr))if(!G||!yt){let Q=af(o.voiceRecognition,o.sendButton);Q&&(G=Q.micButton,yt=Q.micButtonWrapper,qt.insertBefore(yt,Nn),G.addEventListener("click",Fa),G.disabled=$.isStreaming())}else{let Q=(qp=o.voiceRecognition)!=null?qp:{},At=(jp=o.sendButton)!=null?jp:{},$t=(Kp=Q.iconName)!=null?Kp:"mic",pt=(Gp=At.size)!=null?Gp:"40px",Pt=(Yp=Q.iconSize)!=null?Yp:pt,gn=parseFloat(Pt)||24;G.style.width=Pt,G.style.height=Pt,G.style.minWidth=Pt,G.style.minHeight=Pt;let En=(Qp=(Xp=Q.iconColor)!=null?Xp:At.textColor)!=null?Qp:"currentColor";G.innerHTML="";let So=Ee($t,gn,En,2);So?G.appendChild(So):G.textContent="\u{1F3A4}";let On=(Jp=Q.backgroundColor)!=null?Jp:At.backgroundColor;On?G.style.backgroundColor=On:G.style.backgroundColor="",En?G.style.color=En: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 rn=yt==null?void 0:yt.querySelector(".persona-send-button-tooltip"),no=(Zp=Q.tooltipText)!=null?Zp:"Start voice recognition";if(((eu=Q.showTooltip)!=null?eu:!1)&&no)if(rn)rn.textContent=no,rn.style.display="";else{let fn=document.createElement("div");fn.className="persona-send-button-tooltip",fn.textContent=no,yt==null||yt.insertBefore(fn,G)}else rn&&(rn.style.display="none");yt.style.display="",G.disabled=$.isStreaming()}else G&&yt&&(yt.style.display="none",((nu=(tu=o.voiceRecognition)==null?void 0:tu.provider)==null?void 0:nu.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():ft&&yn());if(((ou=o.attachments)==null?void 0:ou.enabled)===!0)if(!Ce||!st){let Q=(ru=o.attachments)!=null?ru:{},$t=(au=((su=o.sendButton)!=null?su:{}).size)!=null?au:"40px";Ze||(Ze=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",Bt.insertBefore(Ze,te)),le||(le=document.createElement("input"),le.type="file",le.accept=((iu=Q.allowedTypes)!=null?iu:Xo).join(","),le.multiple=((lu=Q.maxFiles)!=null?lu:4)>1,le.style.display="none",le.setAttribute("aria-label","Attach files"),Bt.insertBefore(le,te)),Ce=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",(cu=Q.buttonTooltipText)!=null?cu:"Attach file");let pt=(du=Q.buttonIconName)!=null?du:"paperclip",Pt=$t,gn=parseFloat(Pt)||40,En=Math.round(gn*.6);st.style.width=Pt,st.style.height=Pt,st.style.minWidth=Pt,st.style.minHeight=Pt,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 So=Ee(pt,En,"currentColor",1.5);So?st.appendChild(So):st.textContent="\u{1F4CE}",st.addEventListener("click",no=>{no.preventDefault(),le==null||le.click()}),Ce.appendChild(st);let On=(pu=Q.buttonTooltipText)!=null?pu:"Attach file",rn=b("div","persona-send-button-tooltip");rn.textContent=On,Ce.appendChild(rn),It.append(Ce),!Ct&&le&&Ze&&(Ct=ra.fromConfig(Q),Ct.setPreviewsContainer(Ze),le.addEventListener("change",async()=>{Ct&&(le!=null&&le.files)&&(await Ct.handleFileSelect(le.files),le.value="")})),q.querySelector(".persona-attachment-drop-overlay")||q.appendChild(Hg(Q.dropOverlay))}else{Ce.style.display="";let Q=(uu=o.attachments)!=null?uu:{};le&&(le.accept=((mu=Q.allowedTypes)!=null?mu:Xo).join(","),le.multiple=((gu=Q.maxFiles)!=null?gu:4)>1),Ct&&Ct.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ce&&(Ce.style.display="none"),Ct&&Ct.clearAttachments(),(fu=q.querySelector(".persona-attachment-drop-overlay"))==null||fu.remove();let Yt=(hu=o.sendButton)!=null?hu:{},Er=(bu=Yt.useIcon)!=null?bu:!1,ur=(yu=Yt.iconText)!=null?yu:"\u2191",mr=Yt.iconName,Go=(vu=Yt.tooltipText)!=null?vu:"Send message",Mr=(xu=Yt.showTooltip)!=null?xu:!1,Co=(wu=Yt.size)!=null?wu:"40px",et=Yt.backgroundColor,mn=Yt.textColor;if(Er){if(ze.style.width=Co,ze.style.height=Co,ze.style.minWidth=Co,ze.style.minHeight=Co,ze.style.fontSize="18px",ze.style.lineHeight="1",ze.innerHTML="",mn?ze.style.color=mn:ze.style.color="var(--persona-button-primary-fg, #ffffff)",mr){let Q=parseFloat(Co)||24,At=(mn==null?void 0:mn.trim())||"currentColor",$t=Ee(mr,Q,At,2);$t?ze.appendChild($t):ze.textContent=ur}else ze.textContent=ur;ze.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",et?(ze.style.backgroundColor=et,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=(Su=(Cu=o.copy)==null?void 0:Cu.sendButtonLabel)!=null?Su:"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.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",et?(ze.style.backgroundColor=et,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),mn?ze.style.color=mn:ze.classList.add("persona-text-white");Yt.borderWidth?(ze.style.borderWidth=Yt.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),Yt.borderColor?ze.style.borderColor=Yt.borderColor:ze.style.borderColor="",Yt.paddingX?(ze.style.paddingLeft=Yt.paddingX,ze.style.paddingRight=Yt.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Yt.paddingY?(ze.style.paddingTop=Yt.paddingY,ze.style.paddingBottom=Yt.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let Vt=Nn==null?void 0:Nn.querySelector(".persona-send-button-tooltip");if(Mr&&Go)if(Vt)Vt.textContent=Go,Vt.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Go,Nn==null||Nn.insertBefore(Q,ze)}else Vt&&(Vt.style.display="none");let Nt=(Mu=(Au=o.layout)==null?void 0:Au.contentMaxWidth)!=null?Mu:k()?(Eu=(ku=(Tu=o.launcher)==null?void 0:Tu.composerBar)==null?void 0:ku.contentMaxWidth)!=null?Eu:"720px":void 0;Nt?(tt.style.maxWidth=Nt,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%",Bt&&(Bt.style.maxWidth=Nt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Tt&&(Tt.style.maxWidth=Nt,Tt.style.marginLeft="auto",Tt.style.marginRight="auto")):(tt.style.maxWidth="",tt.style.marginLeft="",tt.style.marginRight="",tt.style.width="",Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""),Tt&&(Tt.style.maxWidth="",Tt.style.marginLeft="",Tt.style.marginRight=""));let ht=(Lu=o.statusIndicator)!=null?Lu:{},Xt=(Iu=ht.visible)!=null?Iu:!0;if(an.style.display=Xt?"":"none",$){let Q=$.getStatus();it(an,($t=>{var pt,Pt,gn,En;return $t==="idle"?(pt=ht.idleText)!=null?pt:Mn.idle:$t==="connecting"?(Pt=ht.connectingText)!=null?Pt:Mn.connecting:$t==="connected"?(gn=ht.connectedText)!=null?gn:Mn.connected:$t==="error"?(En=ht.errorText)!=null?En:Mn.error:Mn[$t]})(Q),ht,Q)}an.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";an.classList.add(Et)},open(){A()&&Dt(!0,"api")},close(){A()&&Dt(!1,"api")},toggle(){A()&&Dt(!S,"api")},clearChat(){Pn=!1,$.clearMessages(),Uo.clear(),Bo();try{localStorage.removeItem(vs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${vs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==vs)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={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()},setMessage(c){return!te||$.isStreaming()?!1:(!S&&A()&&Dt(!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?(!S&&A()&&Dt(!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()||(!S&&A()&&Dt(!0,"system"),bt.manuallyDeactivated=!1,Vn(),$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),co("user"),$.isVoiceActive()&&Os()})),!0):ft?!0:wn()?(!S&&A()&&Dt(!0,"system"),bt.manuallyDeactivated=!1,Vn(),Gt("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(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Vn(),co("user"),dr()}),!0):!1:ft?(bt.manuallyDeactivated=!0,Vn(),yn("user"),!0):!1},injectMessage(c){return!S&&A()&&Dt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!S&&A()&&Dt(!0,"system");let p=$.injectAssistantMessage(c);return _&&(_=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),p},injectUserMessage(c){return!S&&A()&&Dt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!S&&A()&&Dt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!S&&A()&&Dt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!S&&A()&&Dt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!S&&A()&&Dt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,p){return $.connectStream(c,p)},__pushEventStreamEvent(c){be&&(he==null||he.processEvent(c.type,c.payload),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ke||!be||No()},hideEventStream(){se&&ho()},isEventStreamVisible(){return se},showArtifacts(){fo(o)&&(Pn=!1,Xn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){fo(o)&&(Pn=!0,Xn())},upsertArtifact(c){return fo(o)?(Pn=!1,$.upsertArtifact(c)):null},selectArtifact(c){fo(o)&&$.selectArtifact(c)},clearArtifacts(){fo(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 L&&!S&&!k()||!te?!1:(te.focus(),!0)},async resolveApproval(c,p,h){let M=$.getMessages().find(F=>{var N;return F.variant==="approval"&&((N=F.approval)==null?void 0:N.id)===c});if(!(M!=null&&M.approval))throw new Error(`Approval not found: ${c}`);if(M.approval.toolType==="webmcp"){$.resolveWebMcpApproval(M.id,p);return}return $.resolveApproval(M.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 A()&&S},isVoiceActive(){return bt.active},getState(){return{open:A()&&S,launcherEnabled:L,voiceActive:bt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!S&&A()&&Dt(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Rg({onSubmit:async(y,M)=>{var F;$.isClientTokenMode()&&await $.submitCSATFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!S&&A()&&Dt(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Pg({onSubmit:async(y,M)=>{var F;$.isClientTokenMode()&&await $.submitNPSFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},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(){$e!=null&&(clearInterval($e),$e=null),gt.forEach(c=>c()),Le.remove(),Xe==null||Xe.remove(),nn==null||nn.destroy(),on==null||on.remove(),lo&&D.removeEventListener("click",lo)}};if((((kd=n==null?void 0:n.debugTools)!=null?kd:!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,gt.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=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",p),gt.push(()=>{window.removeEventListener("persona:focusInput",p)}),ke){let z=we=>{let ge=we.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.showEventStream()},O=we=>{let ge=we.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),gt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.hideArtifacts()},M=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&cn.upsertArtifact(O.artifact)},F=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&cn.selectArtifact(O.id)},N=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",N),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",N)})}let po=mw(o.persistState);if(po&&A()){let c=gw(po.storage),p=`${po.keyPrefix}widget-open`,h=`${po.keyPrefix}widget-voice`,y=`${po.keyPrefix}widget-voice-mode`;if(c){let M=((Ed=po.persist)==null?void 0:Ed.openState)&&c.getItem(p)==="true",F=((Md=po.persist)==null?void 0:Md.voiceState)&&c.getItem(h)==="true",N=((Ld=po.persist)==null?void 0:Ld.voiceState)&&c.getItem(y)==="true";if(M&&setTimeout(()=>{cn.open(),setTimeout(()=>{var z;if(F||N)cn.startVoiceRecognition();else if((z=po.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Id=po.persist)!=null&&Id.openState&&(s.on("widget:opened",()=>{c.setItem(p,"true")}),s.on("widget:closed",()=>{c.setItem(p,"false")})),(Rd=po.persist)!=null&&Rd.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),po.clearOnChatClear){let z=()=>{c.removeItem(p),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),gt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return u&&A()&&setTimeout(()=>{cn.open()},0),Ko(),cn};var fw=(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},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},bw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},yw=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},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"},dc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Fg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",dc(e)},ic=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=""},cc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},zi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},vw=(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))},xw=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Ng=(e,t,n,o,r,s,a)=>{var x,v,E,L,I,W;let i=To(s),d=i.reveal==="push";vw(e,t,n,o,d),xw(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(v=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,g=(L=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?L:640,f=l!=null?l.innerWidth<=g:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),lc(t),ic(o),Fg(o),cc(n),zi(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((W=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?W:Ln),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Fg(o),hw(o,i.maxHeight),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),ic(o),cc(n),zi(r,o);let H=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":R;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=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",ic(o),dc(o),zi(r,o);let H=fw(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",C=i.side==="right"?a?`translateX(-${H}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${H}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${R+H}px`,t.style.transition=w,t.style.transform=C,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}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.top="",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),dc(o),cc(n),zi(r,o);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",C=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${R}`,o.style.width=R,o.style.maxWidth=R,o.style.minWidth=R,o.style.minHeight="0",bw(o,i.maxHeight),o.style.overflow=H||C?"hidden":"visible",o.style.transition=w,H&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},ww=(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()}}},Cw=(e,t)=>{var W,H,R,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"),u=n.createElement("div"),g=(H=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)==null||H?(w=(R=t==null?void 0:t.launcher)==null?void 0:R.autoExpand)!=null?w:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},x=()=>{m(),To(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Ng(a,i,d,l,u,t,g)}),f.observe(a))},v=!1,E=()=>{Ng(a,i,d,l,u,t,g),x(),g&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,yw(a,To(t)))},L=a.ownerDocument.defaultView,I=()=>{E()};return L==null||L.addEventListener("resize",I),To(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),E(),{mode:"docked",host:u,shell:a,syncWidgetState(C){let k=C.launcherEnabled?C.open:!0;g!==k&&(g=k,E())},updateConfig(C){var k,A;t=C,((A=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)!=null?A:!0)===!1&&(g=!0),E()},destroy(){L==null||L.removeEventListener("resize",I),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},_g=(e,t)=>Cn(t)?Cw(e,t):ww(e,t);var xs={desktop:{w:1280,h:800},mobile:{w:390,h:844}},pc=.15,uc=1.5,qi="persona-preview-shell-theme",Vg={load:()=>null,save:()=>{},clear:()=>{}},$g=["How do I get started?","Pricing & plans","Talk to support"];function ji(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ug(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 mc(e){let t=Ug(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 Zs=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 cc(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Ui);o||(o=n.createElement("style"),o.id=Ui,n.head.appendChild(o)),o.textContent=lc(t)}var Hf=`
131
+ .preview-workspace-card.short { height: 96px; }`}function gc(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(qi);o||(o=n.createElement("style"),o.id=qi,n.head.appendChild(o)),o.textContent=mc(t)}var zg=`
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 Zs=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>`,Df=`
150
+ </div>`,qg=`
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 Zs=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 dc(e,t,n,o){let r=`
164
- ${Hf}
163
+ </div>`;function fc(e,t,n,o){let r=`
164
+ ${zg}
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 Zs=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
- ${Df}
176
+ ${qg}
177
177
  </div>
178
178
  </div>
179
179
  </div>`;return`<!DOCTYPE html>
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var Zs=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="${zi(o)}">
185
- <style id="${Ui}">${lc(t)}</style>
184
+ <link rel="stylesheet" href="${ji(o)}">
185
+ <style id="${qi}">${mc(t)}</style>
186
186
  </head>
187
187
  <body>
188
188
  ${n?s:r}
189
189
  </body>
190
- </html>`}var rw={"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 sw(e){return rw[e]}function pc(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 Sw={"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 Aw(e){return Sw[e]}function hc(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"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 aw(e,t){return[...e,pc(t,e.length)]}function Ff(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function iw(e,t,n){var d,l;let o=pc(e,t);if(!Ff(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 lw=()=>[{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()}],cw=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 Of(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"&&cw(t)?[...lw(),...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 uc(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:Wf:e.suggestionChips,initialMessages:Of(t,e,n),storageAdapter:Pf};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Vr(e,t){var s,a,i,d;let n=e.theme?un(e.theme,{validate:!1}):un(),o=(s=e.scene)!=null?s:"conversation",r={...Lt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return uc(r,o,(d=e.appendedMessages)!=null?d:[])}function dw(e,t,n){var a,i,d;let o=e.theme?un(e.theme,{validate:!1}):un(),r=(a=e.scene)!=null?a:"conversation",s={...Lt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return uc(s,r,t)}function Nf(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:Vr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Vr(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:Vr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Vr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Vr(e,n),shellMode:n}]}function pw(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function f(){var I;return(I=n.device)!=null?I:"desktop"}function u(){var I;return(I=n.zoom)!=null?I:i}function g(){var T,_;let I=getComputedStyle(e),R=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),H=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),P=40,w=((T=n.compareMode)!=null?T:"off")!=="off",x=(e.clientWidth-R-P)/(w?2:1),k=e.clientHeight-H-P;if(x<=0||k<=0)return 1;let S=(_=ys[f()])!=null?_:ys.desktop;return Math.min(x/S.w,k/S.h,1)}function m(){var H,P,w;i=g();let I=Math.max(ac,Math.min(ic,u()));d=I;let R=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of R){let k=(H=x.dataset.device)!=null?H:"desktop",S=(P=ys[k])!=null?P:ys.desktop;x.style.width=`${S.w*I}px`,x.style.height=`${S.h*I}px`,k==="mobile"&&(x.style.borderRadius=`${32*I}px`);let T=x.querySelector("iframe");T&&(T.style.width=`${S.w}px`,T.style.height=`${S.h}px`,T.style.transformOrigin="top left",T.style.transition="none",T.style.transform=`scale(${I})`)}(w=n.onScaleChange)==null||w.call(n,I)}function C(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let R of o)R.destroy();for(let R of r)R();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function E(){var ce,ke,ve,He;if(a)return;C();let I=++l,R=Nf(n),H=f(),P=((ce=n.compareMode)!=null?ce:"off")!=="off",w=((ke=n.scene)!=null?ke:"conversation")==="minimized",x=(ve=n.widgetCssPath)!=null?ve:"/widget-dist/widget.css",k=(He=n.buildSrcdoc)!=null?He:dc,S=H==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",T=Se=>`<div class="${S}" data-mount-id="${Se.mountId}" data-device="${H}" data-shell-mode="${Se.shellMode}">
194
- ${P?`<div class="preview-frame-meta"><span class="preview-frame-label">${zi(Se.label)}</span></div>`:""}
193
+ `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"approval-request":{let r=`preview-approval-${o}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${o}`,toolName:"add_to_cart",description:"Add the selected item to the shopping cart. Approve to let the assistant continue.",parameters:{items:[{productEntityId:129,quantity:1}]}}}}case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function Tw(e,t){return[...e,hc(t,e.length)]}function jg(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function kw(e,t,n){var d,l;let o=hc(e,t);if(!jg(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let u=r;u<a.length;u+=r)i.push({message:{...o,content:a.slice(0,u),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var Ew=()=>[{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()}],Mw=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 Kg(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"&&Mw(t)?[...Ew(),...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 bc(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:$g:e.suggestionChips,initialMessages:Kg(t,e,n),storageAdapter:Vg};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Ur(e,t){var s,a,i,d;let n=e.theme?pn(e.theme,{validate:!1}):pn(),o=(s=e.scene)!=null?s:"conversation",r={...Mt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return bc(r,o,(d=e.appendedMessages)!=null?d:[])}function Lw(e,t,n){var a,i,d;let o=e.theme?pn(e.theme,{validate:!1}):pn(),r=(a=e.scene)!=null?a:"conversation",s={...Mt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return bc(s,r,t)}function Gg(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:Ur(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ur(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:Ur(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Ur(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Ur(e,n),shellMode:n}]}function Iw(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function u(){var I;return(I=n.device)!=null?I:"desktop"}function g(){var I;return(I=n.zoom)!=null?I:i}function f(){var S,_;let I=getComputedStyle(e),W=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),H=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),R=40,w=((S=n.compareMode)!=null?S:"off")!=="off",C=(e.clientWidth-W-R)/(w?2:1),k=e.clientHeight-H-R;if(C<=0||k<=0)return 1;let A=(_=xs[u()])!=null?_:xs.desktop;return Math.min(C/A.w,k/A.h,1)}function m(){var H,R,w;i=f();let I=Math.max(pc,Math.min(uc,g()));d=I;let W=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let C of W){let k=(H=C.dataset.device)!=null?H:"desktop",A=(R=xs[k])!=null?R:xs.desktop;C.style.width=`${A.w*I}px`,C.style.height=`${A.h*I}px`,k==="mobile"&&(C.style.borderRadius=`${32*I}px`);let S=C.querySelector("iframe");S&&(S.style.width=`${A.w}px`,S.style.height=`${A.h}px`,S.style.transformOrigin="top left",S.style.transition="none",S.style.transform=`scale(${I})`)}(w=n.onScaleChange)==null||w.call(n,I)}function x(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let W of o)W.destroy();for(let W of r)W();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function E(){var ce,ke,ve,He;if(a)return;x();let I=++l,W=Gg(n),H=u(),R=((ce=n.compareMode)!=null?ce:"off")!=="off",w=((ke=n.scene)!=null?ke:"conversation")==="minimized",C=(ve=n.widgetCssPath)!=null?ve:"/widget-dist/widget.css",k=(He=n.buildSrcdoc)!=null?He:fc,A=H==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",S=Se=>`<div class="${A}" data-mount-id="${Se.mountId}" data-device="${H}" data-shell-mode="${Se.shellMode}">
194
+ ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${ji(Se.label)}</span></div>`:""}
195
195
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Se.mountId}"></iframe>
196
- </div>`,_=P?`<div class="preview-compare-grid">${R.map(Se=>`<div class="preview-compare-cell">${T(Se)}</div>`).join("")}</div>`:`<div class="preview-single">${T(R[0])}</div>`;n.morphContainer?n.morphContainer(e,_):e.innerHTML=_,m();let U=v(),G=0,ge=U.length,ue=()=>{var ie,X,re,be,he;if(a||I!==l)return;for(let j of U){let se=j.dataset.mountId;if(!se||!j.contentDocument)continue;let Ie=R.find(it=>it.mountId===se);if(!Ie)continue;let ne=()=>{},Z=xn(Ie.config),oe=Z?(()=>{var q;let it=(q=j.contentDocument)==null?void 0:q.getElementById(`preview-content-${se}`);if(!it)return null;let Me=Rf(it,Ie.config),de=j.contentDocument.createElement("div");de.id=se,de.style.height="100%",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1",de.style.minHeight="0",Me.host.appendChild(de);let Xe=()=>Me.syncWidgetState(at.getState()),We=ne;return ne=()=>{Me.destroy(),We()},de.__syncDock=Xe,de.__hostLayout=Me,de})():j.contentDocument.getElementById(se);if(!oe)continue;let at=Ef(oe,Ie.config);if(o.push(at),Z&&oe.__syncDock){let it=oe.__syncDock,Me=at.on("widget:opened",it),de=at.on("widget:closed",it),Xe=ne;ne=()=>{Me(),de(),Xe()},it()}r.push(ne),w&&at.close()}if(((ie=n.scene)!=null?ie:"conversation")==="artifact"||(be=(re=(X=n.config)==null?void 0:X.features)==null?void 0:re.artifacts)!=null&&be.enabled)for(let j of o)j.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
196
+ </div>`,_=R?`<div class="preview-compare-grid">${W.map(Se=>`<div class="preview-compare-cell">${S(Se)}</div>`).join("")}</div>`:`<div class="preview-single">${S(W[0])}</div>`;n.morphContainer?n.morphContainer(e,_):e.innerHTML=_,m();let V=v(),K=0,fe=V.length,ue=()=>{var ie,X,re,be,he;if(a||I!==l)return;for(let j of V){let se=j.dataset.mountId;if(!se||!j.contentDocument)continue;let Re=W.find(it=>it.mountId===se);if(!Re)continue;let ne=()=>{},Z=Cn(Re.config),oe=Z?(()=>{var q;let it=(q=j.contentDocument)==null?void 0:q.getElementById(`preview-content-${se}`);if(!it)return null;let Le=_g(it,Re.config),de=j.contentDocument.createElement("div");de.id=se,de.style.height="100%",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1",de.style.minHeight="0",Le.host.appendChild(de);let Xe=()=>Le.syncWidgetState(at.getState()),We=ne;return ne=()=>{Le.destroy(),We()},de.__syncDock=Xe,de.__hostLayout=Le,de})():j.contentDocument.getElementById(se);if(!oe)continue;let at=Dg(oe,Re.config);if(o.push(at),Z&&oe.__syncDock){let it=oe.__syncDock,Le=at.on("widget:opened",it),de=at.on("widget:closed",it),Xe=ne;ne=()=>{Le(),de(),Xe()},it()}r.push(ne),w&&at.close()}if(((ie=n.scene)!=null?ie:"conversation")==="artifact"||(be=(re=(X=n.config)==null?void 0:X.features)==null?void 0:re.artifacts)!=null&&be.enabled)for(let j of o)j.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
197
197
 
198
198
  This is a preview of the artifact sidebar.
199
199
 
@@ -201,4 +201,4 @@ This is a preview of the artifact sidebar.
201
201
 
202
202
  - Markdown rendering
203
203
  - Document toolbar
204
- - Resizable panes`});(he=n.onAfterMount)==null||he.call(n,{iframes:U,controllers:[...o]})};for(let Se of U){let ie=Se.dataset.mountId;if(!ie)continue;let X=R.find(re=>re.mountId===ie);X&&(Se.addEventListener("load",()=>{G++,G>=ge&&ue()},{once:!0}),Se.srcdoc=k(ie,X.shellMode,xn(X.config),x))}ge===0&&ue()}function L(){var H;if(a)return;let I=Nf(n);if(o.length!==I.length){E();return}if(I.some(P=>{let w=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!w||w.dataset.shellMode!==P.shellMode})){E();return}o.forEach((P,w)=>{var x;P.update(I[w].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&P.close()});for(let P of I){let w=e.querySelector(`iframe[data-mount-id="${P.mountId}"]`);w&&cc(w,P.shellMode)}(H=n.onAfterUpdate)==null||H.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),E(),{update(I){if(a)return;let R=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},R?E():L()},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(I){a||(n={...n,zoom:I},m())}}}function Jo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var ji={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"},uw=/^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 mw(e){return uw.test(e)}function vs(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=ji[t];if(n)return n;let o=Us(t);if(ul(o)||o==="transparent"||mw(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(ji).slice(0,6).join(", ")}).`)}var Ki=_a.map(e=>e==="gray"?"neutral":e),fw={...Object.fromEntries(Ki.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Gi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=fw[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 Yi(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 Xi(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 gw={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ji(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=gw[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Qi(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=dl(t);return pl(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Zi(e){for(let t of as){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 _f=Zi("typo-font-family"),ga=Zi("typo-font-size"),ha=Zi("typo-font-weight"),qi=Zi("typo-line-height"),Vf={..._f,monospace:_f.mono},$f={...ga,small:ga.sm,md:ga.base,medium:ga.base,large:ga.lg},Uf={...ha,400:ha.normal,500:ha.medium,600:ha.semibold,700:ha.bold},zf={...qi,"1.25":qi.tight,"1.5":qi.normal,"1.625":qi.relaxed};function qf(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 jf="theme.palette.radius.";function hw(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of as)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(jf)&&typeof i=="string"&&(s[a.slice(jf.length)]=i);e[r[1]]=s}return e}var ya=hw(),Kf=["sm","md","lg","xl","full"];function tl(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?tl(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?tl(e,r,n,o+1):null}function el(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 xs(e){return e.replace(/^role-/,"")}function bw(e){for(let[t,n]of Object.entries(ya))if(Kf.every(o=>e[o]===n[o]))return t;return"custom"}function $r(e){var o,r;let t={};for(let s of Kf)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of Rr)n[xs(s.roleId)]=hl(a=>e.get(`theme.${a}`),s);return{brand:{primary:mc(e.get("theme.palette.colors.primary.500")),secondary:mc(e.get("theme.palette.colors.secondary.500")),accent:mc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:el(e,"theme.semantic.typography.fontFamily"),fontSize:el(e,"theme.semantic.typography.fontSize"),fontWeight:el(e,"theme.semantic.typography.fontWeight"),lineHeight:el(e,"theme.semantic.typography.lineHeight")},roundness:{style:bw(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function mc(e){return typeof e=="string"&&e!==""?e:null}var ba=[{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 Gf(e){let t=new Set(e.targets.map(n=>n.path));return ba.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var yw={AA:4.5,AAA:7};function vw(e){return Math.round(e*100)/100}function xw(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=rs.indexOf(a[2]),l=null,f=1/0;return rs.forEach((u,g)=>{let m=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&Na(m,n)>=o){let C=d>=0?Math.abs(g-d):g;C<f&&(f=C,l=`palette.colors.${i}.${u}`)}}),l}function va(e,t="AA",n="both",o){let r=yw[t],s=n==="both"?["light","dark"]:[n],a=o?ba.filter(d=>o.includes(d.key)):ba,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let f of a){let u=tl(e,f.fg,l),g=tl(e,f.bg,l);if(!u||!g)continue;let m=vw(Na(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 E=xw(e,f.fg,g,r,l);E&&(v.suggestion=E)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function ws(e,t,n="light",o="AA"){return t.length===0?[]:va(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 hn={};for(let e of Rr){let t=xs(e.roleId);hn[t]=e,hn[e.roleId]=e}Object.assign(hn,{surface:hn.surfaces,background:hn.surfaces,backgrounds:hn.surfaces,user:hn["user-messages"],"user-message":hn["user-messages"],assistant:hn["assistant-messages"],"assistant-message":hn["assistant-messages"],actions:hn["primary-actions"],buttons:hn["primary-actions"],composer:hn.input,links:hn["links-focus"],focus:hn["links-focus"],border:hn.borders,dividers:hn.borders,scroll:hn["scroll-to-bottom"]});function ww(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=hn[t];if(!n){let o=Rr.map(r=>xs(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Yf(){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 vl)t(n.sections);for(let n of Ja)t(n.sections);return e}var Cw={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Sw={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},fc=["bottom-right","bottom-left","top-right","top-left"],gc=["bubble","flat","minimal"],Aw={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Xf(e,t){var P;let n=(P=t==null?void 0:t.editTarget)!=null?P:"both",o=null,r=w=>w&&typeof w=="object"?w:{},s=(w,x,k=n)=>{let S={};return(k==="light"||k==="both")&&(S[`theme.${w}`]=x),(k==="dark"||k==="both")&&(S[`darkTheme.${w}`]=x),S},a=w=>{if(n==="both")return w;let x={};for(let[k,S]of Object.entries(w))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=S);return x},i=()=>n==="dark"?"dark":"light",d=(w,x=[])=>Jo({ok:!0,summary:$r(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),k={summary:$r(e),availableRoles:Rr.map(S=>({role:xs(S.roleId),helper:S.helper})),availableFamilies:Ki,presets:qs.map(S=>{var T;return{id:S.id,name:S.name,description:S.description,tags:(T=S.tags)!=null?T:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=Yf()),k.fieldIndex=Array.from(o.values()).map(S=>{var T;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(T=S.options)==null?void 0:T.map(_=>_.value)}})),Jo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(w){let x=r(w),k=["primary","secondary","accent"],S={},T={};for(let U of k){if(x[U]===void 0)continue;let G=vs(x[U]);T[U]=G;let ge=fl(G);for(let ue of rs){let ce=ge[ue];ce!==void 0&&Object.assign(S,s(`palette.colors.${U}.${ue}`,ce))}}if(Object.keys(T).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let _=ws(e,["primary-button","user-message"],i());return d(T,_)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:Ki},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(w){let x=r(w),k=ww(x.role),S=Gi(x.family,!0),T=Yi(x.intensity),_=a(Xa(S,T,k)),U=Object.keys(_).length;e.setBatch(_);let G=ws(e,Gf(k),i());return d({role:xs(k.roleId),family:S,intensity:T,tokensWritten:U},G)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(w){let x=r(w),k={},S={},T=(_,U)=>{var ge;if(x[_]===void 0)return;let G=qf(x[_],U,_);S[_]=(ge=G.split(".").pop())!=null?ge:G,Object.assign(k,s(`semantic.typography.${_}`,G))};if(T("fontFamily",Vf),T("fontSize",$f),T("fontWeight",Uf),T("lineHeight",zf),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(w){let x=r(w),k={},S={};if(x.style!==void 0){let T=Ji(x.style);S.style=T;for(let[_,U]of Object.entries(ya[T]))Object.assign(k,s(`palette.radius.${_}`,U))}if(x.radius!==void 0){let T=r(x.radius),_={};for(let U of["sm","md","lg","xl","full"]){if(T[U]===void 0)continue;let G=Qi(T[U]);_[U]=G,Object.assign(k,s(`palette.radius.${U}`,G))}S.radius=_}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(w){let x=r(w),k={};if(x.scheme!==void 0){let S=Xi(x.scheme);e.set("colorScheme",S),k.scheme=S}if(x.editTarget!==void 0){let S=String(x.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=S,k.editTarget=S}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Jo({ok:!0,summary:$r(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(w){let{presetId:x}=r(w),k=xl(String(x!=null?x:""));if(!k){let U=qs.map(G=>G.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${U}.`)}let S=un(k.theme,{validate:!1}),T={...e.getConfig()};k.darkTheme&&(T.darkTheme=un(k.darkTheme,{validate:!1})),k.toolCall&&(T.toolCall=k.toolCall),e.setFullConfig(T,S);let _=ws(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},_)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:fc},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:gc}},additionalProperties:!1}},additionalProperties:!1},execute(w){var U,G,ge;let x=r(w),k={},S={};if(x.launcherPosition!==void 0){let ue=String(x.launcherPosition);if(!fc.includes(ue))throw new Error(`Unknown launcherPosition "${ue}". Valid: ${fc.join(", ")}.`);k["launcher.position"]=ue,S.launcherPosition=ue}let T=r(x.features);for(let[ue,ce]of Object.entries(Cw))T[ue]!==void 0&&(k[ce]=!!T[ue],(U=S.features)!=null||(S.features={}),S.features[ue]=!!T[ue]);let _=r(x.layout);for(let[ue,ce]of Object.entries(Sw))if(_[ue]!==void 0)if(ue==="messageStyle"){let ke=String(_[ue]);if(!gc.includes(ke))throw new Error(`Unknown messageStyle "${ke}". Valid: ${gc.join(", ")}.`);k[ce]=ke,(G=S.layout)!=null||(S.layout={}),S.layout[ue]=ke}else k[ce]=!!_[ue],(ge=S.layout)!=null||(S.layout={}),S.layout[ue]=!!_[ue];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(w){let x=r(w),k={},S={};for(let[T,_]of Object.entries(Aw))x[T]!==void 0&&(k[_]=String(x[T]),S[T]=String(x[T]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let T=x.suggestions.filter(_=>typeof _=="string");k.suggestionChips=T,S.suggestions=T}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(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 _;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=Yf());let k={},S=[];for(let U of x){let G=r(U),ge=String((_=G.field)!=null?_:"");try{let ue=o.get(ge),ce=ue?ue.path:ge;if(!ue&&!/^(theme|darkTheme)\.|\./.test(ce))throw new Error(`Unknown field "${ge}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ke=Tw(ue,G.value);if(ue&&ce.startsWith("theme.")){let ve=s(ce.slice(6),ke);Object.assign(k,ve),S.push({field:ge,resolvedPath:Object.keys(ve),ok:!0})}else k[ce]=ke,S.push({field:ge,resolvedPath:ce,ok:!0})}catch(ue){S.push({field:ge,ok:!1,error:ue.message})}}let T=S.filter(U=>U.ok);return Object.keys(k).length>0&&e.setBatch(k),Jo({ok:T.length>0,summary:$r(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),k=x.level==="AAA"?"AAA":"AA",S=x.variant==="light"||x.variant==="dark"?x.variant:"both",T=va(e,k,S);return Jo({level:T.level,passing:T.checks.length-T.failures.length,total:T.checks.length,checks:T.checks,failures:T.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(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 Jo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Tw(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(vs(t)):vs(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{Yu as ADVANCED_TOKENS_SECTION,Rr as ALL_ROLES,vl as ALL_TABS,qu as BRAND_PALETTE_SECTION,Ju as BUILT_IN_PRESETS,Pg as COLORS_SECTIONS,gl as COLOR_FAMILIES,$u as COMPONENTS_SECTIONS,Vu as COMPONENT_COLOR_SECTIONS,_u as COMPONENT_SHAPE_SECTIONS,Uu as CONFIGURE_SECTIONS,Ja as CONFIGURE_SUB_GROUPS,ba as CONTRAST_PAIRS,ji as CSS_NAMED_COLORS,ys as DEVICE_DIMENSIONS,Wf as HOME_SUGGESTION_CHIPS,Ku as INTERFACE_ROLES_SECTION,Hf as MOCK_BROWSER_CONTENT,Df as MOCK_WORKSPACE_CONTENT,Ig as PALETTE_SECTION,Pf as PREVIEW_STORAGE_ADAPTER,ya as RADIUS_PRESETS,za as ROLE_ASSISTANT_MESSAGES,Ya as ROLE_BORDERS,_a as ROLE_FAMILIES,bg as ROLE_FAMILY_LABELS,$a as ROLE_HEADER,Ka as ROLE_INPUT,Do as ROLE_INTENSITIES,Ga as ROLE_LINKS_FOCUS,qa as ROLE_PRIMARY_ACTIONS,ja as ROLE_SCROLL_TO_BOTTOM,Va as ROLE_SURFACES,Ua as ROLE_USER_MESSAGES,Rg as SEMANTIC_COLORS_SECTION,rs as SHADE_KEYS,Ui as SHELL_STYLE_ID,Gu as STATUS_COLORS_SECTION,ju as STATUS_PALETTE_SECTION,as as STYLE_SECTIONS,gh as STYLE_SECTIONS_V2,qs as THEME_EDITOR_PRESETS,zu as THEME_SECTION,cl as ThemeEditorState,ic as ZOOM_MAX,ac as ZOOM_MIN,aw as appendPreviewTranscriptEntry,uc as applySceneConfig,cc as applyShellTheme,Vr as buildPreviewConfig,dw as buildPreviewConfigWithMessages,lc as buildShellCss,dc as buildSrcdoc,$r as buildSummary,iw as buildTranscriptStreamFrames,vs as coerceColor,Gi as coerceFamily,Yi as coerceIntensity,Qi as coerceRadius,Ji as coerceRoundnessStyle,Xi as coerceScheme,fg as convertFromPx,mg as convertToPx,Of as createPreviewMessages,pc as createPreviewTranscriptEntry,Xf as createThemeEditorTools,pw as createThemePreview,hl as detectRoleAssignment,zi as escapeHtml,bh as findSection,pl as formatCssValue,fl as generateColorScale,sw as getPreviewTranscriptPresetLabel,Bf as getShellPalette,xl as getThemeEditorPreset,Bu as hexToHsl,Hu as hslToHex,ul as isValidHex,Us as normalizeColorValue,gg as paletteColorPath,dl as parseCssValue,Ff as presetStreamsText,ws as quickContrastWarnings,Xa as resolveRoleAssignment,Du as resolveThemeColorPath,ml as rgbToHex,va as runContrastChecks,yh as scopeSection,hg as tokenRefDisplayName,Jo as toolResult,Na as wcagContrastRatio};
204
+ - Resizable panes`});(he=n.onAfterMount)==null||he.call(n,{iframes:V,controllers:[...o]})};for(let Se of V){let ie=Se.dataset.mountId;if(!ie)continue;let X=W.find(re=>re.mountId===ie);X&&(Se.addEventListener("load",()=>{K++,K>=fe&&ue()},{once:!0}),Se.srcdoc=k(ie,X.shellMode,Cn(X.config),C))}fe===0&&ue()}function L(){var H;if(a)return;let I=Gg(n);if(o.length!==I.length){E();return}if(I.some(R=>{let w=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!w||w.dataset.shellMode!==R.shellMode})){E();return}o.forEach((R,w)=>{var C;R.update(I[w].config),((C=n.scene)!=null?C:"conversation")==="minimized"&&R.close()});for(let R of I){let w=e.querySelector(`iframe[data-mount-id="${R.mountId}"]`);w&&gc(w,R.shellMode)}(H=n.onAfterUpdate)==null||H.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),E(),{update(I){if(a)return;let W=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},W?E():L()},destroy(){a||(a=!0,x(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return v()},getScale(){return d},setZoom(I){a||(n={...n,zoom:I},m())}}}function Jo(e){return{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:e}}var Gi={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"},Rw=/^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 Pw(e){return Rw.test(e)}function ws(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=Gi[t];if(n)return n;let o=zs(t);if(gl(o)||o==="transparent"||Pw(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(Gi).slice(0,6).join(", ")}).`)}var Yi=Ua.map(e=>e==="gray"?"neutral":e),Ww={...Object.fromEntries(Yi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Xi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Ww[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 Qi(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 Ji(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 Bw={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Zi(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Bw[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function el(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=ul(t);return ml(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function tl(e){for(let t of cs){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 Yg=tl("typo-font-family"),va=tl("typo-font-size"),xa=tl("typo-font-weight"),Ki=tl("typo-line-height"),Xg={...Yg,monospace:Yg.mono},Qg={...va,small:va.sm,md:va.base,medium:va.base,large:va.lg},Jg={...xa,400:xa.normal,500:xa.medium,600:xa.semibold,700:xa.bold},Zg={...Ki,"1.25":Ki.tight,"1.5":Ki.normal,"1.625":Ki.relaxed};function ef(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 tf="theme.palette.radius.";function Hw(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of cs)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(tf)&&typeof i=="string"&&(s[a.slice(tf.length)]=i);e[r[1]]=s}return e}var Ca=Hw(),nf=["sm","md","lg","xl","full"];function ol(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?ol(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?ol(e,r,n,o+1):null}function nl(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 Cs(e){return e.replace(/^role-/,"")}function Dw(e){for(let[t,n]of Object.entries(Ca))if(nf.every(o=>e[o]===n[o]))return t;return"custom"}function zr(e){var o,r;let t={};for(let s of nf)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of Wr)n[Cs(s.roleId)]=yl(a=>e.get(`theme.${a}`),s);return{brand:{primary:yc(e.get("theme.palette.colors.primary.500")),secondary:yc(e.get("theme.palette.colors.secondary.500")),accent:yc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:nl(e,"theme.semantic.typography.fontFamily"),fontSize:nl(e,"theme.semantic.typography.fontSize"),fontWeight:nl(e,"theme.semantic.typography.fontWeight"),lineHeight:nl(e,"theme.semantic.typography.lineHeight")},roundness:{style:Dw(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function yc(e){return typeof e=="string"&&e!==""?e:null}var wa=[{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 of(e){let t=new Set(e.targets.map(n=>n.path));return wa.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Ow={AA:4.5,AAA:7};function Fw(e){return Math.round(e*100)/100}function Nw(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=is.indexOf(a[2]),l=null,u=1/0;return is.forEach((g,f)=>{let m=e.get(`${r}.palette.colors.${i}.${g}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&$a(m,n)>=o){let x=d>=0?Math.abs(f-d):f;x<u&&(u=x,l=`palette.colors.${i}.${g}`)}}),l}function Sa(e,t="AA",n="both",o){let r=Ow[t],s=n==="both"?["light","dark"]:[n],a=o?wa.filter(d=>o.includes(d.key)):wa,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let g=ol(e,u.fg,l),f=ol(e,u.bg,l);if(!g||!f)continue;let m=Fw($a(g,f)),x=m>=r,v={pair:u.key,label:u.label,variant:d,fg:g,bg:f,ratio:m,threshold:r,passes:x};if(!x){let E=Nw(e,u.fg,f,r,l);E&&(v.suggestion=E)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Ss(e,t,n="light",o="AA"){return t.length===0?[]:Sa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var hn={};for(let e of Wr){let t=Cs(e.roleId);hn[t]=e,hn[e.roleId]=e}Object.assign(hn,{surface:hn.surfaces,background:hn.surfaces,backgrounds:hn.surfaces,user:hn["user-messages"],"user-message":hn["user-messages"],assistant:hn["assistant-messages"],"assistant-message":hn["assistant-messages"],actions:hn["primary-actions"],buttons:hn["primary-actions"],composer:hn.input,links:hn["links-focus"],focus:hn["links-focus"],border:hn.borders,dividers:hn.borders,scroll:hn["scroll-to-bottom"]});function _w(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=hn[t];if(!n){let o=Wr.map(r=>Cs(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function rf(){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 wl)t(n.sections);for(let n of ei)t(n.sections);return e}var Vw={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},$w={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},vc=["bottom-right","bottom-left","top-right","top-left"],xc=["bubble","flat","minimal"],Uw={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function sf(e,t){var R;let n=(R=t==null?void 0:t.editTarget)!=null?R:"both",o=null,r=w=>w&&typeof w=="object"?w:{},s=(w,C,k=n)=>{let A={};return(k==="light"||k==="both")&&(A[`theme.${w}`]=C),(k==="dark"||k==="both")&&(A[`darkTheme.${w}`]=C),A},a=w=>{if(n==="both")return w;let C={};for(let[k,A]of Object.entries(w))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(C[k]=A);return C},i=()=>n==="dark"?"dark":"light",d=(w,C=[])=>Jo({ok:!0,summary:zr(e),warnings:C,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:C}=r(w),k={summary:zr(e),availableRoles:Wr.map(A=>({role:Cs(A.roleId),helper:A.helper})),availableFamilies:Yi,presets:js.map(A=>{var S;return{id:A.id,name:A.name,description:A.description,tags:(S=A.tags)!=null?S:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return C==="full"&&(o!=null||(o=rf()),k.fieldIndex=Array.from(o.values()).map(A=>{var S;return{id:A.id,path:A.path,type:A.type,label:A.label,options:(S=A.options)==null?void 0:S.map(_=>_.value)}})),Jo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(w){let C=r(w),k=["primary","secondary","accent"],A={},S={};for(let V of k){if(C[V]===void 0)continue;let K=ws(C[V]);S[V]=K;let fe=hl(K);for(let ue of is){let ce=fe[ue];ce!==void 0&&Object.assign(A,s(`palette.colors.${V}.${ue}`,ce))}}if(Object.keys(S).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(A);let _=Ss(e,["primary-button","user-message"],i());return d(S,_)}},{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:Yi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(w){let C=r(w),k=_w(C.role),A=Xi(C.family,!0),S=Qi(C.intensity),_=a(Za(A,S,k)),V=Object.keys(_).length;e.setBatch(_);let K=Ss(e,of(k),i());return d({role:Cs(k.roleId),family:A,intensity:S,tokensWritten:V},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(w){let C=r(w),k={},A={},S=(_,V)=>{var fe;if(C[_]===void 0)return;let K=ef(C[_],V,_);A[_]=(fe=K.split(".").pop())!=null?fe:K,Object.assign(k,s(`semantic.typography.${_}`,K))};if(S("fontFamily",Xg),S("fontSize",Qg),S("fontWeight",Jg),S("lineHeight",Zg),Object.keys(A).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(A)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(w){let C=r(w),k={},A={};if(C.style!==void 0){let S=Zi(C.style);A.style=S;for(let[_,V]of Object.entries(Ca[S]))Object.assign(k,s(`palette.radius.${_}`,V))}if(C.radius!==void 0){let S=r(C.radius),_={};for(let V of["sm","md","lg","xl","full"]){if(S[V]===void 0)continue;let K=el(S[V]);_[V]=K,Object.assign(k,s(`palette.radius.${V}`,K))}A.radius=_}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(A)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(w){let C=r(w),k={};if(C.scheme!==void 0){let A=Ji(C.scheme);e.set("colorScheme",A),k.scheme=A}if(C.editTarget!==void 0){let A=String(C.editTarget).trim().toLowerCase();if(A!=="light"&&A!=="dark"&&A!=="both")throw new Error(`Unknown editTarget "${C.editTarget}". Valid: light, dark, both.`);n=A,k.editTarget=A}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Jo({ok:!0,summary:zr(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(w){let{presetId:C}=r(w),k=Cl(String(C!=null?C:""));if(!k){let V=js.map(K=>K.id).join(", ");throw new Error(`Unknown preset "${C}". Valid presets: ${V}.`)}let A=pn(k.theme,{validate:!1}),S={...e.getConfig()};k.darkTheme&&(S.darkTheme=pn(k.darkTheme,{validate:!1})),k.toolCall&&(S.toolCall=k.toolCall),e.setFullConfig(S,A);let _=Ss(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},_)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:vc},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:xc}},additionalProperties:!1}},additionalProperties:!1},execute(w){var V,K,fe;let C=r(w),k={},A={};if(C.launcherPosition!==void 0){let ue=String(C.launcherPosition);if(!vc.includes(ue))throw new Error(`Unknown launcherPosition "${ue}". Valid: ${vc.join(", ")}.`);k["launcher.position"]=ue,A.launcherPosition=ue}let S=r(C.features);for(let[ue,ce]of Object.entries(Vw))S[ue]!==void 0&&(k[ce]=!!S[ue],(V=A.features)!=null||(A.features={}),A.features[ue]=!!S[ue]);let _=r(C.layout);for(let[ue,ce]of Object.entries($w))if(_[ue]!==void 0)if(ue==="messageStyle"){let ke=String(_[ue]);if(!xc.includes(ke))throw new Error(`Unknown messageStyle "${ke}". Valid: ${xc.join(", ")}.`);k[ce]=ke,(K=A.layout)!=null||(A.layout={}),A.layout[ue]=ke}else k[ce]=!!_[ue],(fe=A.layout)!=null||(A.layout={}),A.layout[ue]=!!_[ue];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(A)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(w){let C=r(w),k={},A={};for(let[S,_]of Object.entries(Uw))C[S]!==void 0&&(k[_]=String(C[S]),A[S]=String(C[S]));if(C.suggestions!==void 0){if(!Array.isArray(C.suggestions))throw new Error("`suggestions` must be an array of strings.");let S=C.suggestions.filter(_=>typeof _=="string");k.suggestionChips=S,A.suggestions=S}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(A)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(w){var _;let{updates:C}=r(w);if(!Array.isArray(C)||C.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=rf());let k={},A=[];for(let V of C){let K=r(V),fe=String((_=K.field)!=null?_:"");try{let ue=o.get(fe),ce=ue?ue.path:fe;if(!ue&&!/^(theme|darkTheme)\.|\./.test(ce))throw new Error(`Unknown field "${fe}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ke=zw(ue,K.value);if(ue&&ce.startsWith("theme.")){let ve=s(ce.slice(6),ke);Object.assign(k,ve),A.push({field:fe,resolvedPath:Object.keys(ve),ok:!0})}else k[ce]=ke,A.push({field:fe,resolvedPath:ce,ok:!0})}catch(ue){A.push({field:fe,ok:!1,error:ue.message})}}let S=A.filter(V=>V.ok);return Object.keys(k).length>0&&e.setBatch(k),Jo({ok:S.length>0,summary:zr(e),warnings:[],applied:{updates:A}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(w){let C=r(w),k=C.level==="AAA"?"AAA":"AA",A=C.variant==="light"||C.variant==="dark"?C.variant:"both",S=Sa(e,k,A);return Jo({level:S.level,passing:S.checks.length-S.failures.length,total:S.checks.length,checks:S.checks,failures:S.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:C}=r(w);switch(C){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Jo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${C}". Valid: undo, redo, reset, export.`)}}}]}function zw(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ws(t)):ws(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{em as ADVANCED_TOKENS_SECTION,Wr as ALL_ROLES,wl as ALL_TABS,Xu as BRAND_PALETTE_SECTION,nm as BUILT_IN_PRESETS,Uf as COLORS_SECTIONS,bl as COLOR_FAMILIES,Ku as COMPONENTS_SECTIONS,ju as COMPONENT_COLOR_SECTIONS,qu as COMPONENT_SHAPE_SECTIONS,Gu as CONFIGURE_SECTIONS,ei as CONFIGURE_SUB_GROUPS,wa as CONTRAST_PAIRS,Gi as CSS_NAMED_COLORS,xs as DEVICE_DIMENSIONS,$g as HOME_SUGGESTION_CHIPS,Ju as INTERFACE_ROLES_SECTION,zg as MOCK_BROWSER_CONTENT,qg as MOCK_WORKSPACE_CONTENT,Vf as PALETTE_SECTION,Vg as PREVIEW_STORAGE_ADAPTER,Ca as RADIUS_PRESETS,Ka as ROLE_ASSISTANT_MESSAGES,Ja as ROLE_BORDERS,Ua as ROLE_FAMILIES,Mf as ROLE_FAMILY_LABELS,qa as ROLE_HEADER,Xa as ROLE_INPUT,Oo as ROLE_INTENSITIES,Qa as ROLE_LINKS_FOCUS,Ga as ROLE_PRIMARY_ACTIONS,Ya as ROLE_SCROLL_TO_BOTTOM,za as ROLE_SURFACES,ja as ROLE_USER_MESSAGES,$f as SEMANTIC_COLORS_SECTION,is as SHADE_KEYS,qi as SHELL_STYLE_ID,Zu as STATUS_COLORS_SECTION,Qu as STATUS_PALETTE_SECTION,cs as STYLE_SECTIONS,kh as STYLE_SECTIONS_V2,js as THEME_EDITOR_PRESETS,Yu as THEME_SECTION,pl as ThemeEditorState,uc as ZOOM_MAX,pc as ZOOM_MIN,Tw as appendPreviewTranscriptEntry,bc as applySceneConfig,gc as applyShellTheme,Ur as buildPreviewConfig,Lw as buildPreviewConfigWithMessages,mc as buildShellCss,fc as buildSrcdoc,zr as buildSummary,kw as buildTranscriptStreamFrames,ws as coerceColor,Xi as coerceFamily,Qi as coerceIntensity,el as coerceRadius,Zi as coerceRoundnessStyle,Ji as coerceScheme,Tf as convertFromPx,Af as convertToPx,Kg as createPreviewMessages,hc as createPreviewTranscriptEntry,sf as createThemeEditorTools,Iw as createThemePreview,yl as detectRoleAssignment,ji as escapeHtml,Mh as findSection,ml as formatCssValue,hl as generateColorScale,Aw as getPreviewTranscriptPresetLabel,Ug as getShellPalette,Cl as getThemeEditorPreset,Nu as hexToHsl,_u as hslToHex,gl as isValidHex,zs as normalizeColorValue,kf as paletteColorPath,ul as parseCssValue,jg as presetStreamsText,Ss as quickContrastWarnings,Za as resolveRoleAssignment,Vu as resolveThemeColorPath,fl as rgbToHex,Sa as runContrastChecks,Lh as scopeSection,Ef as tokenRefDisplayName,Jo as toolResult,$a as wcagContrastRatio};